method
stringlengths
13
441k
clean_method
stringlengths
7
313k
doc
stringlengths
17
17.3k
comment
stringlengths
3
1.42k
method_name
stringlengths
1
273
extra
dict
imports
sequence
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
sequence
libraries_info
stringlengths
6
661
id
int64
0
2.92M
void enterBulk_collect_into_clause(@NotNull PLSQLParser.Bulk_collect_into_clauseContext ctx); void exitBulk_collect_into_clause(@NotNull PLSQLParser.Bulk_collect_into_clauseContext ctx);
void enterBulk_collect_into_clause(@NotNull PLSQLParser.Bulk_collect_into_clauseContext ctx); void exitBulk_collect_into_clause(@NotNull PLSQLParser.Bulk_collect_into_clauseContext ctx);
/** * Exit a parse tree produced by {@link PLSQLParser#bulk_collect_into_clause}. * @param ctx the parse tree */
Exit a parse tree produced by <code>PLSQLParser#bulk_collect_into_clause</code>
exitBulk_collect_into_clause
{ "repo_name": "developeron29/PLSQLParser", "path": "PLSQLListener.java", "license": "mit", "size": 45486 }
[ "org.antlr.v4.runtime.misc.NotNull" ]
import org.antlr.v4.runtime.misc.NotNull;
import org.antlr.v4.runtime.misc.*;
[ "org.antlr.v4" ]
org.antlr.v4;
1,662,947
protected String buildAndEncodeConsentAttributes(final Map<String, List<Object>> attributes) { try { val json = MAPPER.writer(new MinimalPrettyPrinter()).writeValueAsString(attributes); val base64 = EncodingUtils.encodeBase64(json); return this.consentCipherExecutor.encode(base64); } catch (final Exception e) { throw new IllegalArgumentException("Could not serialize attributes for consent decision"); } }
String function(final Map<String, List<Object>> attributes) { try { val json = MAPPER.writer(new MinimalPrettyPrinter()).writeValueAsString(attributes); val base64 = EncodingUtils.encodeBase64(json); return this.consentCipherExecutor.encode(base64); } catch (final Exception e) { throw new IllegalArgumentException(STR); } }
/** * Build consent attribute names string. * * @param attributes the attributes * @return the string */
Build consent attribute names string
buildAndEncodeConsentAttributes
{ "repo_name": "leleuj/cas", "path": "support/cas-server-support-consent-core/src/main/java/org/apereo/cas/consent/DefaultConsentDecisionBuilder.java", "license": "apache-2.0", "size": 5301 }
[ "com.fasterxml.jackson.core.util.MinimalPrettyPrinter", "java.util.List", "java.util.Map", "org.apereo.cas.util.EncodingUtils" ]
import com.fasterxml.jackson.core.util.MinimalPrettyPrinter; import java.util.List; import java.util.Map; import org.apereo.cas.util.EncodingUtils;
import com.fasterxml.jackson.core.util.*; import java.util.*; import org.apereo.cas.util.*;
[ "com.fasterxml.jackson", "java.util", "org.apereo.cas" ]
com.fasterxml.jackson; java.util; org.apereo.cas;
879,602
public ServiceResponseWithHeaders<Void, LROSADsPostNonRetry400Headers> postNonRetry400() throws CloudException, IOException, InterruptedException { final Product product = null; Response<ResponseBody> result = service.postNonRetry400(product, this.client.acceptLanguage(), this.client.userAgent()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken<Void>() { }.getType(), LROSADsPostNonRetry400Headers.class); }
ServiceResponseWithHeaders<Void, LROSADsPostNonRetry400Headers> function() throws CloudException, IOException, InterruptedException { final Product product = null; Response<ResponseBody> result = service.postNonRetry400(product, this.client.acceptLanguage(), this.client.userAgent()).execute(); return client.getAzureClient().getPostOrDeleteResultWithHeaders(result, new TypeToken<Void>() { }.getType(), LROSADsPostNonRetry400Headers.class); }
/** * Long running post request, service returns a 400 with no error body. * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws InterruptedException exception thrown when long running operation is interrupted * @return the ServiceResponseWithHeaders object if successful. */
Long running post request, service returns a 400 with no error body
postNonRetry400
{ "repo_name": "yaqiyang/autorest", "path": "src/generator/AutoRest.Java.Azure.Tests/src/main/java/fixtures/lro/implementation/LROSADsImpl.java", "license": "mit", "size": 244275 }
[ "com.google.common.reflect.TypeToken", "com.microsoft.azure.CloudException", "com.microsoft.rest.ServiceResponseWithHeaders", "java.io.IOException" ]
import com.google.common.reflect.TypeToken; import com.microsoft.azure.CloudException; import com.microsoft.rest.ServiceResponseWithHeaders; import java.io.IOException;
import com.google.common.reflect.*; import com.microsoft.azure.*; import com.microsoft.rest.*; import java.io.*;
[ "com.google.common", "com.microsoft.azure", "com.microsoft.rest", "java.io" ]
com.google.common; com.microsoft.azure; com.microsoft.rest; java.io;
2,798,938
public void setThemeFiles(final List<IFileSpecification> files) { if (files != null) this.themeFiles = ImmutableList.copyOf(files); else this.themeFiles = ImmutableList.of(); clean(); }
void function(final List<IFileSpecification> files) { if (files != null) this.themeFiles = ImmutableList.copyOf(files); else this.themeFiles = ImmutableList.of(); clean(); }
/** * Set a list of theme files for this project. Themes are additive. The * theme file closer to the end of the list has higher priorities. Calling * this method will remove all the previous set theme files. * * @param files A list of theme file specifications. */
Set a list of theme files for this project. Themes are additive. The theme file closer to the end of the list has higher priorities. Calling this method will remove all the previous set theme files
setThemeFiles
{ "repo_name": "greg-dove/flex-falcon", "path": "compiler/src/main/java/org/apache/flex/compiler/internal/projects/FlexProject.java", "license": "apache-2.0", "size": 73716 }
[ "com.google.common.collect.ImmutableList", "java.util.List", "org.apache.flex.compiler.filespecs.IFileSpecification" ]
import com.google.common.collect.ImmutableList; import java.util.List; import org.apache.flex.compiler.filespecs.IFileSpecification;
import com.google.common.collect.*; import java.util.*; import org.apache.flex.compiler.filespecs.*;
[ "com.google.common", "java.util", "org.apache.flex" ]
com.google.common; java.util; org.apache.flex;
994,381
KeyValueIterator<Windowed<K>, AGG> findSessions(final K key, long earliestSessionEndTime, final long latestSessionStartTime);
KeyValueIterator<Windowed<K>, AGG> findSessions(final K key, long earliestSessionEndTime, final long latestSessionStartTime);
/** * Fetch any sessions with the matching key and the sessions end is &le earliestEndTime and the sessions * start is &ge latestStartTime */
Fetch any sessions with the matching key and the sessions end is &le earliestEndTime and the sessions start is &ge latestStartTime
findSessions
{ "repo_name": "ijuma/kafka", "path": "streams/src/main/java/org/apache/kafka/streams/state/SessionStore.java", "license": "apache-2.0", "size": 1951 }
[ "org.apache.kafka.streams.kstream.Windowed" ]
import org.apache.kafka.streams.kstream.Windowed;
import org.apache.kafka.streams.kstream.*;
[ "org.apache.kafka" ]
org.apache.kafka;
728,243
public BoundingBox extendBoundingBox (final BoundingBox out) { final int n = nodes.size; for (int i = 0; i < n; i++) nodes.get(i).extendBoundingBox(out); return out; }
BoundingBox function (final BoundingBox out) { final int n = nodes.size; for (int i = 0; i < n; i++) nodes.get(i).extendBoundingBox(out); return out; }
/** Extends the bounding box with the bounds of this model instance. This is a potential slow operation, it is advised to cache * the result. * @param out the {@link BoundingBox} that will be extended with the bounds. * @return the out parameter for chaining */
Extends the bounding box with the bounds of this model instance. This is a potential slow operation, it is advised to cache the result
extendBoundingBox
{ "repo_name": "0359xiaodong/libgdx", "path": "gdx/src/com/badlogic/gdx/graphics/g3d/ModelInstance.java", "license": "apache-2.0", "size": 20255 }
[ "com.badlogic.gdx.math.collision.BoundingBox" ]
import com.badlogic.gdx.math.collision.BoundingBox;
import com.badlogic.gdx.math.collision.*;
[ "com.badlogic.gdx" ]
com.badlogic.gdx;
1,373,714
StateModelDefinition.Builder builder =new StateModelDefinition.Builder(name); // init state builder.initialState(States.OFFLINE.name()); // add states builder.addState(States.MASTER.name(), 0); builder.addState(States.OFFLINE.name(), 1); for (HelixDefinedState state : HelixDefinedState.values()) { builder.addState(state.name()); } // add transitions builder.addTransition(States.MASTER.name(), States.OFFLINE.name(), 0); builder.addTransition(States.OFFLINE.name(), States.MASTER.name(), 1); builder.addTransition(States.OFFLINE.name(), HelixDefinedState.DROPPED.name()); // bounds builder.dynamicUpperBound(States.MASTER.name(), "N"); return builder.build(); }
StateModelDefinition.Builder builder =new StateModelDefinition.Builder(name); builder.initialState(States.OFFLINE.name()); builder.addState(States.MASTER.name(), 0); builder.addState(States.OFFLINE.name(), 1); for (HelixDefinedState state : HelixDefinedState.values()) { builder.addState(state.name()); } builder.addTransition(States.MASTER.name(), States.OFFLINE.name(), 0); builder.addTransition(States.OFFLINE.name(), States.MASTER.name(), 1); builder.addTransition(States.OFFLINE.name(), HelixDefinedState.DROPPED.name()); builder.dynamicUpperBound(States.MASTER.name(), "N"); return builder.build(); }
/** * Build StorageSchemata state model definition * @return */
Build StorageSchemata state model definition
build
{ "repo_name": "apache/helix", "path": "helix-core/src/main/java/org/apache/helix/model/StorageSchemataSMD.java", "license": "apache-2.0", "size": 4684 }
[ "org.apache.helix.HelixDefinedState" ]
import org.apache.helix.HelixDefinedState;
import org.apache.helix.*;
[ "org.apache.helix" ]
org.apache.helix;
871,655
private void updateAPI(API api, int tenantId, String username) throws APIManagementException { apiMgtDAO.updateAPI(api, username); if (log.isDebugEnabled()) { log.debug("Successfully updated the API: " + api.getId() + " metadata in the database"); } updateAPIResources(api, tenantId); }
void function(API api, int tenantId, String username) throws APIManagementException { apiMgtDAO.updateAPI(api, username); if (log.isDebugEnabled()) { log.debug(STR + api.getId() + STR); } updateAPIResources(api, tenantId); }
/** * Update API metadata and resources. * * @param api API to update * @param tenantId Tenant Id * @param username Username of the user who is updating * @throws APIManagementException If fails to update API. */
Update API metadata and resources
updateAPI
{ "repo_name": "tharikaGitHub/carbon-apimgt", "path": "components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIProviderImpl.java", "license": "apache-2.0", "size": 497958 }
[ "org.wso2.carbon.apimgt.api.APIManagementException" ]
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.*;
[ "org.wso2.carbon" ]
org.wso2.carbon;
2,403,341
private String readUntil(String endChars) throws IOException { StringBuffer sb = new StringBuffer(); int ch = nextToken(); while (ch != -1) { if (ch == '\\') { ch = nextToken(); if (ch == -1) { break; } } else { if (endChars.indexOf((char) ch) != -1) { pushBack(ch); break; } } sb.append((char) ch); ch = nextToken(); } return sb.toString(); }
String function(String endChars) throws IOException { StringBuffer sb = new StringBuffer(); int ch = nextToken(); while (ch != -1) { if (ch == '\\') { ch = nextToken(); if (ch == -1) { break; } } else { if (endChars.indexOf((char) ch) != -1) { pushBack(ch); break; } } sb.append((char) ch); ch = nextToken(); } return sb.toString(); }
/** * Reads the stream until it meets one of the specified ending characters, or stream end. The ending character will be left in * the stream. * * @param endChars DOCUMENT ME! * * @return DOCUMENT ME! * * @throws IOException DOCUMENT ME! */
Reads the stream until it meets one of the specified ending characters, or stream end. The ending character will be left in the stream
readUntil
{ "repo_name": "hgschmie/EyeWiki", "path": "src/java/de/softwareforge/eyewiki/TranslatorReader.java", "license": "lgpl-2.1", "size": 102523 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
146,109
public SourceValidity getValidity() { return NOPValidity.SHARED_INSTANCE; }
SourceValidity function() { return NOPValidity.SHARED_INSTANCE; }
/** * Generate the cache validity object. */
Generate the cache validity object
getValidity
{ "repo_name": "rnathanday/dryad-repo", "path": "dspace/modules/xmlui/src/main/java/org/dspace/app/xmlui/aspect/dryadfeedback/MembershipApplicationSubmitted.java", "license": "bsd-3-clause", "size": 2076 }
[ "org.apache.excalibur.source.SourceValidity", "org.apache.excalibur.source.impl.validity.NOPValidity" ]
import org.apache.excalibur.source.SourceValidity; import org.apache.excalibur.source.impl.validity.NOPValidity;
import org.apache.excalibur.source.*; import org.apache.excalibur.source.impl.validity.*;
[ "org.apache.excalibur" ]
org.apache.excalibur;
1,745,904
@Override public void run() { amIActive = true; String outputHeader = null; WhiteboxRaster image = null; WhiteboxRaster output = null; int cols = 0; int rows = 0; double imageNoData = -32768; double outputNoData = -32768; int numImages; double z; float progress = 0; int col, row; int a, i; String inputFilesString = null; String[] imageFiles; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (i = 0; i < args.length; i++) { if (i == 0) { inputFilesString = args[i]; } else if (i == 1) { outputHeader = args[i]; } } imageFiles = inputFilesString.split(";"); numImages = imageFiles.length; // check to see that the inputHeader and outputHeader are not null. if (numImages < 2) { showFeedback("At least two images must be specified."); return; } try { double[] data; // check that each of the input images has the same number of rows and columns // and calculate the image averages. updateProgress("Calculating min values:", 0); for (a = 0; a < numImages; a++) { image = new WhiteboxRaster(imageFiles[a], "r"); imageNoData = image.getNoDataValue(); String label = "Loop " + String.valueOf(a + 1) + " of " + String.valueOf(numImages) + ":"; if (a == 0) { rows = image.getNumberRows(); cols = image.getNumberColumns(); outputNoData = imageNoData; output = new WhiteboxRaster(outputHeader, "rw", imageFiles[0], WhiteboxRaster.DataType.FLOAT, outputNoData); output.setPreferredPalette(image.getPreferredPalette()); } else { if (image.getNumberColumns() != cols || image.getNumberRows() != rows) { showFeedback("All input images must have the same dimensions (rows and columns)."); return; } } for (row = 0; row < rows; row++) { data = image.getRowValues(row); for (col = 0; col < cols; col++) { if (data[col] != imageNoData) { z = output.getValue(row, col); if (z != outputNoData) { if (data[col] < z) { output.setValue(row, col, data[col]); } } else { output.setValue(row, col, data[col]); } } } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * row / (rows - 1)); updateProgress(label, (int) progress); } image.close(); progress = a / (numImages - 1) * 100; updateProgress("Calculating image average:", (int)progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); output.close(); // returning a header file string displays the image. returnData(outputHeader); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(), e); } finally { updateProgress("Progress: ", 0); // tells the main application that this process is completed. amIActive = false; myHost.pluginComplete(); } }
void function() { amIActive = true; String outputHeader = null; WhiteboxRaster image = null; WhiteboxRaster output = null; int cols = 0; int rows = 0; double imageNoData = -32768; double outputNoData = -32768; int numImages; double z; float progress = 0; int col, row; int a, i; String inputFilesString = null; String[] imageFiles; if (args.length <= 0) { showFeedback(STR); return; } for (i = 0; i < args.length; i++) { if (i == 0) { inputFilesString = args[i]; } else if (i == 1) { outputHeader = args[i]; } } imageFiles = inputFilesString.split(";"); numImages = imageFiles.length; if (numImages < 2) { showFeedback(STR); return; } try { double[] data; updateProgress(STR, 0); for (a = 0; a < numImages; a++) { image = new WhiteboxRaster(imageFiles[a], "r"); imageNoData = image.getNoDataValue(); String label = STR + String.valueOf(a + 1) + STR + String.valueOf(numImages) + ":"; if (a == 0) { rows = image.getNumberRows(); cols = image.getNumberColumns(); outputNoData = imageNoData; output = new WhiteboxRaster(outputHeader, "rw", imageFiles[0], WhiteboxRaster.DataType.FLOAT, outputNoData); output.setPreferredPalette(image.getPreferredPalette()); } else { if (image.getNumberColumns() != cols image.getNumberRows() != rows) { showFeedback(STR); return; } } for (row = 0; row < rows; row++) { data = image.getRowValues(row); for (col = 0; col < cols; col++) { if (data[col] != imageNoData) { z = output.getValue(row, col); if (z != outputNoData) { if (data[col] < z) { output.setValue(row, col, data[col]); } } else { output.setValue(row, col, data[col]); } } } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * row / (rows - 1)); updateProgress(label, (int) progress); } image.close(); progress = a / (numImages - 1) * 100; updateProgress(STR, (int)progress); } output.addMetadataEntry(STR + getDescriptiveName() + STR); output.addMetadataEntry(STR + new Date()); output.close(); returnData(outputHeader); } catch (OutOfMemoryError oe) { myHost.showFeedback(STR); } catch (Exception e) { myHost.showFeedback(STR); myHost.logException(STR + getDescriptiveName(), e); } finally { updateProgress(STR, 0); amIActive = false; myHost.pluginComplete(); } }
/** * Used to execute this plugin tool. */
Used to execute this plugin tool
run
{ "repo_name": "jblindsay/jblindsay.github.io", "path": "ghrg/Whitebox/WhiteboxGAT-linux/resources/plugins/source_files/MinOverlay.java", "license": "mit", "size": 9934 }
[ "java.util.Date" ]
import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
1,504,597
public static <T, E extends Throwable> T compute(@NotNull ThrowableComputable<T, E> action) throws E { return ApplicationManager.getApplication().runWriteAction(action); }
static <T, E extends Throwable> T function(@NotNull ThrowableComputable<T, E> action) throws E { return ApplicationManager.getApplication().runWriteAction(action); }
/** * Executes {@code action} inside write action and returns the result. * Must be called from the EDT. */
Executes action inside write action and returns the result. Must be called from the EDT
compute
{ "repo_name": "mdanielwork/intellij-community", "path": "platform/core-api/src/com/intellij/openapi/application/WriteAction.java", "license": "apache-2.0", "size": 6109 }
[ "com.intellij.openapi.util.ThrowableComputable", "org.jetbrains.annotations.NotNull" ]
import com.intellij.openapi.util.ThrowableComputable; import org.jetbrains.annotations.NotNull;
import com.intellij.openapi.util.*; import org.jetbrains.annotations.*;
[ "com.intellij.openapi", "org.jetbrains.annotations" ]
com.intellij.openapi; org.jetbrains.annotations;
1,952,713
public static String loadContentFromFile(final Class<?> clazz, final String resourceName) { // prevent NullPointerException if (clazz == null || resourceName == null) { LogUtils.warnf(UIHelper.class, "loadContentFromFile not invoked, due to null arguments"); return ""; } // check if resource is there final InputStream is = clazz.getResourceAsStream(resourceName); if (is == null) { LogUtils.warnf(UIHelper.class, "Resource '%s' couldn't be loaded from class '%s'", resourceName, clazz.getName()); return ""; } // resource is there, so we can try loading it BufferedReader bufferedReader = null; StringBuilder result = new StringBuilder(100); try { bufferedReader = new BufferedReader(new InputStreamReader(is)); String eachLine = null; while ((eachLine = bufferedReader.readLine()) != null) { result.append(eachLine); result.append(System.getProperty("line.separator")); } } catch (IOException ioEx) { LogUtils.errorf(clazz, ioEx, "Error while reading resource from '%s'.", resourceName); } finally { closeSilently(bufferedReader); } return result.toString(); }
static String function(final Class<?> clazz, final String resourceName) { if (clazz == null resourceName == null) { LogUtils.warnf(UIHelper.class, STR); return STRResource '%s' couldn't be loaded from class '%s'STRSTRline.separatorSTRError while reading resource from '%s'.", resourceName); } finally { closeSilently(bufferedReader); } return result.toString(); }
/** * Loads the <code>resourceName</code> from the classpath using the given * <code>clazz</code>. If the resource couldn't be loaded an empty string is * returned. * * @param clazz * The class to use for loading the resource. * @param resourceName * The name of the resource to be loaded (e.g. * /folder/filename.txt) * @return The content of the file, each line separated by line.separator or * empty string if the resource does not exist. */
Loads the <code>resourceName</code> from the classpath using the given <code>clazz</code>. If the resource couldn't be loaded an empty string is returned
loadContentFromFile
{ "repo_name": "RangerRick/opennms", "path": "features/jmx-config-generator-webui/src/main/java/org/opennms/features/jmxconfiggenerator/webui/ui/UIHelper.java", "license": "gpl-2.0", "size": 8778 }
[ "org.opennms.core.utils.LogUtils" ]
import org.opennms.core.utils.LogUtils;
import org.opennms.core.utils.*;
[ "org.opennms.core" ]
org.opennms.core;
666,922
public void testGetAll() throws Exception { List<Arm> actual = getDao().getAll(); assertEquals(8, actual.size()); List<Integer> ids = collectIds(actual); assertContains("Wrong arm found", ids, 1000); assertContains("Wrong arm found", ids, 1001); assertContains("Wrong arm found", ids, 1002); assertContains("Wrong arm found", ids, 1003); assertContains("Wrong arm found", ids, 1004); assertContains("Wrong arm found", ids, 1005); assertContains("Wrong arm found", ids, 1006); assertContains("Wrong arm found", ids, 1007); }
void function() throws Exception { List<Arm> actual = getDao().getAll(); assertEquals(8, actual.size()); List<Integer> ids = collectIds(actual); assertContains(STR, ids, 1000); assertContains(STR, ids, 1001); assertContains(STR, ids, 1002); assertContains(STR, ids, 1003); assertContains(STR, ids, 1004); assertContains(STR, ids, 1005); assertContains(STR, ids, 1006); assertContains(STR, ids, 1007); }
/** * Test for loading all Arms * * @throws Exception */
Test for loading all Arms
testGetAll
{ "repo_name": "NCIP/c3pr", "path": "codebase/projects/core/test/src/java/edu/duke/cabig/c3pr/dao/ArmDaoTest.java", "license": "bsd-3-clause", "size": 2308 }
[ "edu.duke.cabig.c3pr.domain.Arm", "edu.nwu.bioinformatics.commons.testing.CoreTestCase", "java.util.List" ]
import edu.duke.cabig.c3pr.domain.Arm; import edu.nwu.bioinformatics.commons.testing.CoreTestCase; import java.util.List;
import edu.duke.cabig.c3pr.domain.*; import edu.nwu.bioinformatics.commons.testing.*; import java.util.*;
[ "edu.duke.cabig", "edu.nwu.bioinformatics", "java.util" ]
edu.duke.cabig; edu.nwu.bioinformatics; java.util;
2,644,390
private void appendMultiPointText(MultiPoint multiPoint, int level, Writer writer) throws IOException { if (multiPoint.isEmpty()) { writer.write("EMPTY"); } else { writer.write("("); for (int i = 0; i < multiPoint.getNumGeometries(); i++) { if (i > 0) { writer.write(", "); indentCoords(i, level + 1, writer); } writer.write("("); appendCoordinate(((Point) multiPoint.getGeometryN(i)).getCoordinate(), writer); writer.write(")"); } writer.write(")"); } }
void function(MultiPoint multiPoint, int level, Writer writer) throws IOException { if (multiPoint.isEmpty()) { writer.write("EMPTY"); } else { writer.write("("); for (int i = 0; i < multiPoint.getNumGeometries(); i++) { if (i > 0) { writer.write(STR); indentCoords(i, level + 1, writer); } writer.write("("); appendCoordinate(((Point) multiPoint.getGeometryN(i)).getCoordinate(), writer); writer.write(")"); } writer.write(")"); } }
/** * Converts a <code>MultiPoint</code> to &lt;MultiPoint Text&gt; format, then * appends it to the writer. * *@param multiPoint the <code>MultiPoint</code> to process *@param writer the output writer to append to */
Converts a <code>MultiPoint</code> to &lt;MultiPoint Text&gt; format, then appends it to the writer
appendMultiPointText
{ "repo_name": "metteo/jts", "path": "jts-core/src/main/java/com/vividsolutions/jts/io/WKTWriter.java", "license": "lgpl-2.1", "size": 23679 }
[ "com.vividsolutions.jts.geom.MultiPoint", "com.vividsolutions.jts.geom.Point", "java.io.IOException", "java.io.Writer" ]
import com.vividsolutions.jts.geom.MultiPoint; import com.vividsolutions.jts.geom.Point; import java.io.IOException; import java.io.Writer;
import com.vividsolutions.jts.geom.*; import java.io.*;
[ "com.vividsolutions.jts", "java.io" ]
com.vividsolutions.jts; java.io;
1,595,151
public void cleanup() { cache = null; cacheCfg = null; evictMgr = null; qryMgr = null; dataStructuresMgr = null; cacheObjCtx = null; if (expiryPlc instanceof Closeable) U.closeQuiet((Closeable)expiryPlc); mgrs.clear(); }
void function() { cache = null; cacheCfg = null; evictMgr = null; qryMgr = null; dataStructuresMgr = null; cacheObjCtx = null; if (expiryPlc instanceof Closeable) U.closeQuiet((Closeable)expiryPlc); mgrs.clear(); }
/** * Nulling references to potentially leak-prone objects. */
Nulling references to potentially leak-prone objects
cleanup
{ "repo_name": "samaitra/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheContext.java", "license": "apache-2.0", "size": 72682 }
[ "java.io.Closeable", "org.apache.ignite.internal.util.typedef.internal.U" ]
import java.io.Closeable; import org.apache.ignite.internal.util.typedef.internal.U;
import java.io.*; import org.apache.ignite.internal.util.typedef.internal.*;
[ "java.io", "org.apache.ignite" ]
java.io; org.apache.ignite;
560,424
public void init() { // Get the screen width and height. screenWidth = getWidth(); screenHeight = getHeight(); pre_x = screenWidth / 2; pre_y = screenHeight / 2; try { if (getParameter("file") != null) { fileName = getParameter("file"); } } catch (Exception e) { // Nothing to do. } count = 0; fps = 0; time = 0; if (shader == FLAT) { renderer = new FlatRenderer(screenWidth, screenHeight); } else { renderer = new TextureRenderer(screenWidth, screenHeight); } // Create offscreen buffer. offImage = new BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_BGR); offg = offImage.createGraphics(); clearImage(); // Create a 3D object. obj = new Object3D(); obj.setRot(new Vector3f(theta, phi, 0.0f)); try { // Load a .OBJ object. obj.load(new URL(getCodeBase(), fileName + ".obj")); } catch (MalformedURLException e) { // e.printStackTrace(); System.exit(1); } catch (IOException e) { // e.printStackTrace(); System.exit(1); } catch (Exception e) { try { obj.load(new FileInputStream(fileName + ".obj")); } catch (FileNotFoundException e1) { System.exit(1); } catch (IOException e1) { System.exit(1); } } // Load a texture. try { texture = ImageIO.read(new URL(getCodeBase(), fileName + ".jpg")); // Set a texture to the renderer. renderer.setTexture(texture); } catch (Exception e) { try { texture = ImageIO.read(new FileInputStream(fileName + ".jpg")); // Set a texture to the renderer. renderer.setTexture(texture); } catch (FileNotFoundException e1) { System.exit(1); } catch (IOException e1) { System.exit(1); } } }
void function() { screenWidth = getWidth(); screenHeight = getHeight(); pre_x = screenWidth / 2; pre_y = screenHeight / 2; try { if (getParameter("file") != null) { fileName = getParameter("file"); } } catch (Exception e) { } count = 0; fps = 0; time = 0; if (shader == FLAT) { renderer = new FlatRenderer(screenWidth, screenHeight); } else { renderer = new TextureRenderer(screenWidth, screenHeight); } offImage = new BufferedImage(screenWidth, screenHeight, BufferedImage.TYPE_INT_BGR); offg = offImage.createGraphics(); clearImage(); obj = new Object3D(); obj.setRot(new Vector3f(theta, phi, 0.0f)); try { obj.load(new URL(getCodeBase(), fileName + ".obj")); } catch (MalformedURLException e) { System.exit(1); } catch (IOException e) { System.exit(1); } catch (Exception e) { try { obj.load(new FileInputStream(fileName + ".obj")); } catch (FileNotFoundException e1) { System.exit(1); } catch (IOException e1) { System.exit(1); } } try { texture = ImageIO.read(new URL(getCodeBase(), fileName + ".jpg")); renderer.setTexture(texture); } catch (Exception e) { try { texture = ImageIO.read(new FileInputStream(fileName + ".jpg")); renderer.setTexture(texture); } catch (FileNotFoundException e1) { System.exit(1); } catch (IOException e1) { System.exit(1); } } }
/** * <p> * Initialize an applet. * </p> * Get the screen size when invoking the applet. * * @see java.applet.Applet#init() */
Initialize an applet. Get the screen size when invoking the applet
init
{ "repo_name": "drjiro/WaViewer3D", "path": "src/com/drjiro/viewer/WadViewer3D.java", "license": "mit", "size": 8670 }
[ "java.awt.image.BufferedImage", "java.io.FileInputStream", "java.io.FileNotFoundException", "java.io.IOException", "java.net.MalformedURLException", "javax.imageio.ImageIO" ]
import java.awt.image.BufferedImage; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.MalformedURLException; import javax.imageio.ImageIO;
import java.awt.image.*; import java.io.*; import java.net.*; import javax.imageio.*;
[ "java.awt", "java.io", "java.net", "javax.imageio" ]
java.awt; java.io; java.net; javax.imageio;
2,182,268
private void peepHoleOptimization(MethodGenerator methodGen) { InstructionList il = methodGen.getInstructionList(); InstructionFinder find = new InstructionFinder(il); InstructionHandle ih; String pattern; // LoadInstruction, POP => (removed) pattern = "LoadInstruction POP"; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[]) iter.next(); try { if (!match[0].hasTargeters() && !match[1].hasTargeters()) { il.delete(match[0], match[1]); } } catch (TargetLostException e) { // TODO: move target down into the list } } // ILOAD_N, ILOAD_N, SWAP, ISTORE_N => ILOAD_N pattern = "ILOAD ILOAD SWAP ISTORE"; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[]) iter.next(); try { org.apache.bcel.generic.ILOAD iload1 = (org.apache.bcel.generic.ILOAD) match[0].getInstruction(); org.apache.bcel.generic.ILOAD iload2 = (org.apache.bcel.generic.ILOAD) match[1].getInstruction(); org.apache.bcel.generic.ISTORE istore = (org.apache.bcel.generic.ISTORE) match[3].getInstruction(); if (!match[1].hasTargeters() && !match[2].hasTargeters() && !match[3].hasTargeters() && iload1.getIndex() == iload2.getIndex() && iload2.getIndex() == istore.getIndex()) { il.delete(match[1], match[3]); } } catch (TargetLostException e) { // TODO: move target down into the list } } // LoadInstruction_N, LoadInstruction_M, SWAP => LoadInstruction_M, LoadInstruction_N pattern = "LoadInstruction LoadInstruction SWAP"; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[])iter.next(); try { if (!match[0].hasTargeters() && !match[1].hasTargeters() && !match[2].hasTargeters()) { Instruction load_m = match[1].getInstruction(); il.insert(match[0], load_m); il.delete(match[1], match[2]); } } catch (TargetLostException e) { // TODO: move target down into the list } } // ALOAD_N ALOAD_N => ALOAD_N DUP pattern = "ALOAD ALOAD"; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[])iter.next(); try { if (!match[1].hasTargeters()) { org.apache.bcel.generic.ALOAD aload1 = (org.apache.bcel.generic.ALOAD) match[0].getInstruction(); org.apache.bcel.generic.ALOAD aload2 = (org.apache.bcel.generic.ALOAD) match[1].getInstruction(); if (aload1.getIndex() == aload2.getIndex()) { il.insert(match[1], new DUP()); il.delete(match[1]); } } } catch (TargetLostException e) { // TODO: move target down into the list } } }
void function(MethodGenerator methodGen) { InstructionList il = methodGen.getInstructionList(); InstructionFinder find = new InstructionFinder(il); InstructionHandle ih; String pattern; pattern = STR; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[]) iter.next(); try { if (!match[0].hasTargeters() && !match[1].hasTargeters()) { il.delete(match[0], match[1]); } } catch (TargetLostException e) { } } pattern = STR; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[]) iter.next(); try { org.apache.bcel.generic.ILOAD iload1 = (org.apache.bcel.generic.ILOAD) match[0].getInstruction(); org.apache.bcel.generic.ILOAD iload2 = (org.apache.bcel.generic.ILOAD) match[1].getInstruction(); org.apache.bcel.generic.ISTORE istore = (org.apache.bcel.generic.ISTORE) match[3].getInstruction(); if (!match[1].hasTargeters() && !match[2].hasTargeters() && !match[3].hasTargeters() && iload1.getIndex() == iload2.getIndex() && iload2.getIndex() == istore.getIndex()) { il.delete(match[1], match[3]); } } catch (TargetLostException e) { } } pattern = STR; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[])iter.next(); try { if (!match[0].hasTargeters() && !match[1].hasTargeters() && !match[2].hasTargeters()) { Instruction load_m = match[1].getInstruction(); il.insert(match[0], load_m); il.delete(match[1], match[2]); } } catch (TargetLostException e) { } } pattern = STR; for (Iterator iter = find.search(pattern); iter.hasNext();) { InstructionHandle[] match = (InstructionHandle[])iter.next(); try { if (!match[1].hasTargeters()) { org.apache.bcel.generic.ALOAD aload1 = (org.apache.bcel.generic.ALOAD) match[0].getInstruction(); org.apache.bcel.generic.ALOAD aload2 = (org.apache.bcel.generic.ALOAD) match[1].getInstruction(); if (aload1.getIndex() == aload2.getIndex()) { il.insert(match[1], new DUP()); il.delete(match[1]); } } } catch (TargetLostException e) { } } }
/** * Peephole optimization. */
Peephole optimization
peepHoleOptimization
{ "repo_name": "kcsl/immutability-benchmark", "path": "benchmark-applications/reiminfer-oopsla-2012/source/Xalan/src/org/apache/xalan/xsltc/compiler/Mode.java", "license": "mit", "size": 52223 }
[ "java.util.Iterator", "org.apache.bcel.generic.Instruction", "org.apache.bcel.generic.InstructionHandle", "org.apache.bcel.generic.InstructionList", "org.apache.bcel.generic.TargetLostException", "org.apache.bcel.util.InstructionFinder", "org.apache.xalan.xsltc.compiler.util.MethodGenerator" ]
import java.util.Iterator; import org.apache.bcel.generic.Instruction; import org.apache.bcel.generic.InstructionHandle; import org.apache.bcel.generic.InstructionList; import org.apache.bcel.generic.TargetLostException; import org.apache.bcel.util.InstructionFinder; import org.apache.xalan.xsltc.compiler.util.MethodGenerator;
import java.util.*; import org.apache.bcel.generic.*; import org.apache.bcel.util.*; import org.apache.xalan.xsltc.compiler.util.*;
[ "java.util", "org.apache.bcel", "org.apache.xalan" ]
java.util; org.apache.bcel; org.apache.xalan;
1,331,802
public void invalidate(Token t) { invalidateHelper(root, partitioner.getMinimumToken(), t); }
void function(Token t) { invalidateHelper(root, partitioner.getMinimumToken(), t); }
/** * Invalidates the ranges containing the given token. */
Invalidates the ranges containing the given token
invalidate
{ "repo_name": "stuhood/cassandra-old", "path": "src/java/org/apache/cassandra/utils/MerkleTree.java", "license": "apache-2.0", "size": 25550 }
[ "org.apache.cassandra.dht.Token" ]
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.dht.*;
[ "org.apache.cassandra" ]
org.apache.cassandra;
437,552
private Document getXmlDocFromString(String xmlString) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document xmlDocument = builder.parse(new InputSource(new StringReader(xmlString))); return xmlDocument; }
Document function(String xmlString) throws ParserConfigurationException, SAXException, IOException { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); final DocumentBuilder builder = factory.newDocumentBuilder(); final Document xmlDocument = builder.parse(new InputSource(new StringReader(xmlString))); return xmlDocument; }
/** * converts the string we got from the radio to a parsable XML document * * @param xmlString * the XML string read from the radio * @return the parsed XML document * @throws ParserConfigurationException * @throws SAXException * @throws IOException */
converts the string we got from the radio to a parsable XML document
getXmlDocFromString
{ "repo_name": "jowiho/openhab", "path": "bundles/binding/org.openhab.binding.frontiersiliconradio/src/main/java/org/openhab/binding/frontiersiliconradio/internal/FrontierSiliconRadioApiResult.java", "license": "epl-1.0", "size": 7691 }
[ "java.io.IOException", "java.io.StringReader", "javax.xml.parsers.DocumentBuilder", "javax.xml.parsers.DocumentBuilderFactory", "javax.xml.parsers.ParserConfigurationException", "org.w3c.dom.Document", "org.xml.sax.InputSource", "org.xml.sax.SAXException" ]
import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.xml.sax.InputSource; import org.xml.sax.SAXException;
import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*;
[ "java.io", "javax.xml", "org.w3c.dom", "org.xml.sax" ]
java.io; javax.xml; org.w3c.dom; org.xml.sax;
1,991,716
public boolean isAirBlock(BlockPos pos) { IBlockState state = this.getBlockState(pos); return state.getBlock().isAir(state, this, pos); }
boolean function(BlockPos pos) { IBlockState state = this.getBlockState(pos); return state.getBlock().isAir(state, this, pos); }
/** * Checks to see if an air block exists at the provided location. Note that this only checks to see if the blocks * material is set to air, meaning it is possible for non-vanilla blocks to still pass this check. */
Checks to see if an air block exists at the provided location. Note that this only checks to see if the blocks material is set to air, meaning it is possible for non-vanilla blocks to still pass this check
isAirBlock
{ "repo_name": "danielyc/test-1.9.4", "path": "build/tmp/recompileMc/sources/net/minecraft/world/ChunkCache.java", "license": "gpl-3.0", "size": 6897 }
[ "net.minecraft.block.state.IBlockState", "net.minecraft.util.math.BlockPos" ]
import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos;
import net.minecraft.block.state.*; import net.minecraft.util.math.*;
[ "net.minecraft.block", "net.minecraft.util" ]
net.minecraft.block; net.minecraft.util;
2,160,039
public List<String> getDefaultWerte() { List<String> defaultWerte = new ArrayList<String>(); String[] lines = this.bemerkung.trim().split("\n"); for (int i = 0; i < lines.length; i++) { String[] values = lines[i].split("="); if (values.length == 2) { defaultWerte.add(values[0].trim()); } } return defaultWerte; }
List<String> function() { List<String> defaultWerte = new ArrayList<String>(); String[] lines = this.bemerkung.trim().split("\n"); for (int i = 0; i < lines.length; i++) { String[] values = lines[i].split("="); if (values.length == 2) { defaultWerte.add(values[0].trim()); } } return defaultWerte; }
/** * Die Default-Werte werde aus dem Bemerkungsfeld abgeleitet. Dies wird * vor allem fuer die moeglichen Wagnisarten verwendet. * * @return Liste mit moeglichen Werten (kann leer sein) */
Die Default-Werte werde aus dem Bemerkungsfeld abgeleitet. Dies wird vor allem fuer die moeglichen Wagnisarten verwendet
getDefaultWerte
{ "repo_name": "oboehm/gdv.xport", "path": "lib/src/main/java/gdv/xport/satz/xml/FeldReferenz.java", "license": "apache-2.0", "size": 4818 }
[ "java.util.ArrayList", "java.util.List" ]
import java.util.ArrayList; import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
2,314,059
public void setEntityResolver(XMLEntityResolver entityResolver) { fEntityResolver = entityResolver; } // setEntityResolver(XMLEntityResolver)
void function(XMLEntityResolver entityResolver) { fEntityResolver = entityResolver; }
/** * Sets the entity resolver. * * @param entityResolver The new entity resolver. */
Sets the entity resolver
setEntityResolver
{ "repo_name": "FauxFaux/jdk9-jaxp", "path": "src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XMLGrammarPreparser.java", "license": "gpl-2.0", "size": 13522 }
[ "com.sun.org.apache.xerces.internal.xni.parser.XMLEntityResolver" ]
import com.sun.org.apache.xerces.internal.xni.parser.XMLEntityResolver;
import com.sun.org.apache.xerces.internal.xni.parser.*;
[ "com.sun.org" ]
com.sun.org;
623,326
protected ScannerParam getScannerParam() { if (scannerParam == null) { scannerParam = new ScannerParam(); } return scannerParam; }
ScannerParam function() { if (scannerParam == null) { scannerParam = new ScannerParam(); } return scannerParam; }
/** * This method initializes scannerParam * * @return org.parosproxy.paros.core.scanner.ScannerParam */
This method initializes scannerParam
getScannerParam
{ "repo_name": "Harinus/zaproxy", "path": "src/org/zaproxy/zap/extension/ascan/ExtensionActiveScan.java", "license": "apache-2.0", "size": 24232 }
[ "org.parosproxy.paros.core.scanner.ScannerParam" ]
import org.parosproxy.paros.core.scanner.ScannerParam;
import org.parosproxy.paros.core.scanner.*;
[ "org.parosproxy.paros" ]
org.parosproxy.paros;
225,678
protected void initialize (TestParameters tParam, PrintWriter log) { SOfficeFactory SOF = SOfficeFactory.getFactory ( (XMultiServiceFactory) tParam.getMSF ()); try { log.println ("creating a Spreadsheet document"); xSheetDoc = SOF.createCalcDoc (null); } catch (com.sun.star.uno.Exception e) { // Some exception occurs.FAILED e.printStackTrace (log); throw new StatusException ("Couldn't create document", e); } }
void function (TestParameters tParam, PrintWriter log) { SOfficeFactory SOF = SOfficeFactory.getFactory ( (XMultiServiceFactory) tParam.getMSF ()); try { log.println (STR); xSheetDoc = SOF.createCalcDoc (null); } catch (com.sun.star.uno.Exception e) { e.printStackTrace (log); throw new StatusException (STR, e); } }
/** * Creates Spreadsheet document. */
Creates Spreadsheet document
initialize
{ "repo_name": "qt-haiku/LibreOffice", "path": "qadevOOo/tests/java/mod/_sc/ScDataPilotFieldGroupObj.java", "license": "gpl-3.0", "size": 13221 }
[ "com.sun.star.lang.XMultiServiceFactory", "java.io.PrintWriter" ]
import com.sun.star.lang.XMultiServiceFactory; import java.io.PrintWriter;
import com.sun.star.lang.*; import java.io.*;
[ "com.sun.star", "java.io" ]
com.sun.star; java.io;
2,120,460
void addLoaded(DefDescriptor<?> descriptor, String uid);
void addLoaded(DefDescriptor<?> descriptor, String uid);
/** * Add a loaded descriptor+UID pair. * * This routine will remember a descriptor in the set of loaded descriptors along with a uid for validating the load * (and 'timestamping' it). This should be used with care, as it will be serialized with every request, so size * should be a consideration. * * @param descriptor The loaded descriptor. * @param uid the UID that was loaded. */
Add a loaded descriptor+UID pair. This routine will remember a descriptor in the set of loaded descriptors along with a uid for validating the load (and 'timestamping' it). This should be used with care, as it will be serialized with every request, so size should be a consideration
addLoaded
{ "repo_name": "igor-sfdc/aura", "path": "aura/src/main/java/org/auraframework/system/AuraContext.java", "license": "apache-2.0", "size": 16789 }
[ "org.auraframework.def.DefDescriptor" ]
import org.auraframework.def.DefDescriptor;
import org.auraframework.def.*;
[ "org.auraframework.def" ]
org.auraframework.def;
2,706,580
void dial(String address, int clirMode, UUSInfo uusInfo, Message result);
void dial(String address, int clirMode, UUSInfo uusInfo, Message result);
/** * returned message * retMsg.obj = AsyncResult ar * ar.exception carries exception on failure * ar.userObject contains the orignal value of result.obj * ar.result is null on success and failure * * CLIR_DEFAULT == on "use subscription default value" * CLIR_SUPPRESSION == on "CLIR suppression" (allow CLI presentation) * CLIR_INVOCATION == on "CLIR invocation" (restrict CLI presentation) */
returned message retMsg.obj = AsyncResult ar ar.exception carries exception on failure ar.userObject contains the orignal value of result.obj ar.result is null on success and failure CLIR_DEFAULT == on "use subscription default value" CLIR_SUPPRESSION == on "CLIR suppression" (allow CLI presentation) CLIR_INVOCATION == on "CLIR invocation" (restrict CLI presentation)
dial
{ "repo_name": "indashnet/InDashNet.Open.UN2000", "path": "android/frameworks/opt/telephony/src/java/com/android/internal/telephony/CommandsInterface.java", "license": "apache-2.0", "size": 60442 }
[ "android.os.Message" ]
import android.os.Message;
import android.os.*;
[ "android.os" ]
android.os;
1,621,193
public static <T> MutableList<T> toSortedList(Iterable<T> iterable, Comparator<? super T> comparator) { return FastList.newList(iterable).sortThis(comparator); }
static <T> MutableList<T> function(Iterable<T> iterable, Comparator<? super T> comparator) { return FastList.newList(iterable).sortThis(comparator); }
/** * Return the specified collection as a sorted List using the specified Comparator. */
Return the specified collection as a sorted List using the specified Comparator
toSortedList
{ "repo_name": "g-votte/eclipse-collections", "path": "eclipse-collections/src/main/java/org/eclipse/collections/impl/utility/Iterate.java", "license": "bsd-3-clause", "size": 138506 }
[ "java.util.Comparator", "org.eclipse.collections.api.list.MutableList", "org.eclipse.collections.impl.list.mutable.FastList" ]
import java.util.Comparator; import org.eclipse.collections.api.list.MutableList; import org.eclipse.collections.impl.list.mutable.FastList;
import java.util.*; import org.eclipse.collections.api.list.*; import org.eclipse.collections.impl.list.mutable.*;
[ "java.util", "org.eclipse.collections" ]
java.util; org.eclipse.collections;
1,185,135
public boolean hasHigherTombstoneGCVersions(RegionVersionVector<T> other) { if (this.localGCVersion.get() > 0) { Long version = other.memberToGCVersion.get(this.myId); if (version == null) { return true; // this vector has removed locally created tombstones that the other hasn't // reaped } else if (this.localGCVersion.get() > version.longValue()) { return true; } } // see if I have members with GC versions that the other vector doesn't have for (T mbr : this.memberToGCVersion.keySet()) { if (!other.memberToGCVersion.containsKey(mbr)) { if (!mbr.equals(other.getOwnerId())) { return true; } } } // see if the other vector has members that have been removed from this // vector. If this happens we don't know if tombstones were removed for (T id : other.memberToGCVersion.keySet()) { if (!id.equals(this.myId) && !this.memberToGCVersion.containsKey(id)) { return true; } } // now see if I have anything newer for things we have in common for (Map.Entry<T, Long> entry : other.memberToGCVersion.entrySet()) { Long version = this.memberToGCVersion.get(entry.getKey()); if (version != null) { Long otherVersion = entry.getValue(); if (version.longValue() > otherVersion.longValue()) { return true; } } } return false; }
boolean function(RegionVersionVector<T> other) { if (this.localGCVersion.get() > 0) { Long version = other.memberToGCVersion.get(this.myId); if (version == null) { return true; } else if (this.localGCVersion.get() > version.longValue()) { return true; } } for (T mbr : this.memberToGCVersion.keySet()) { if (!other.memberToGCVersion.containsKey(mbr)) { if (!mbr.equals(other.getOwnerId())) { return true; } } } for (T id : other.memberToGCVersion.keySet()) { if (!id.equals(this.myId) && !this.memberToGCVersion.containsKey(id)) { return true; } } for (Map.Entry<T, Long> entry : other.memberToGCVersion.entrySet()) { Long version = this.memberToGCVersion.get(entry.getKey()); if (version != null) { Long otherVersion = entry.getValue(); if (version.longValue() > otherVersion.longValue()) { return true; } } } return false; }
/** * check to see if tombstone removal in this RVV indicates that tombstones have been removed from * its Region that have not been removed from the argument's Region. If this is the case, then a * delta GII may leave entries in the other RVV's Region that should be deleted. * * @return true if there have been tombstone removals in this vector's Region that were not done * in the argument's region */
check to see if tombstone removal in this RVV indicates that tombstones have been removed from its Region that have not been removed from the argument's Region. If this is the case, then a delta GII may leave entries in the other RVV's Region that should be deleted
hasHigherTombstoneGCVersions
{ "repo_name": "davebarnes97/geode", "path": "geode-core/src/main/java/org/apache/geode/internal/cache/versions/RegionVersionVector.java", "license": "apache-2.0", "size": 56609 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
1,570,160
public Menu getOptionsMenu() { return optionsMenu; }
Menu function() { return optionsMenu; }
/** * Return the options menu. * * @return Options menu. */
Return the options menu
getOptionsMenu
{ "repo_name": "macklinu/robolectric", "path": "robolectric-shadows/shadows-core/src/main/java/org/robolectric/shadows/ShadowActivity.java", "license": "mit", "size": 18092 }
[ "android.view.Menu" ]
import android.view.Menu;
import android.view.*;
[ "android.view" ]
android.view;
2,217,841
@Test(expected = GenieNotFoundException.class) public void testRemoveTagForCommandNoCommand() throws GenieException { final String id = UUID.randomUUID().toString(); Mockito.when(this.commandRepository.findOne(id)).thenReturn(null); this.service.removeTagForCommand(id, "something"); }
@Test(expected = GenieNotFoundException.class) void function() throws GenieException { final String id = UUID.randomUUID().toString(); Mockito.when(this.commandRepository.findOne(id)).thenReturn(null); this.service.removeTagForCommand(id, STR); }
/** * Test remove configuration for command. * * @throws GenieException For any problem */
Test remove configuration for command
testRemoveTagForCommandNoCommand
{ "repo_name": "sensaid/genie", "path": "genie-core/src/test/java/com/netflix/genie/core/services/impl/jpa/TestCommandConfigServiceJPAImpl.java", "license": "apache-2.0", "size": 16163 }
[ "com.netflix.genie.common.exceptions.GenieException", "com.netflix.genie.common.exceptions.GenieNotFoundException", "java.util.UUID", "org.junit.Test", "org.mockito.Mockito" ]
import com.netflix.genie.common.exceptions.GenieException; import com.netflix.genie.common.exceptions.GenieNotFoundException; import java.util.UUID; import org.junit.Test; import org.mockito.Mockito;
import com.netflix.genie.common.exceptions.*; import java.util.*; import org.junit.*; import org.mockito.*;
[ "com.netflix.genie", "java.util", "org.junit", "org.mockito" ]
com.netflix.genie; java.util; org.junit; org.mockito;
2,757,945
public static MethodHandle getNumberGuard() { return JSType.IS_NUMBER.methodHandle(); }
static MethodHandle function() { return JSType.IS_NUMBER.methodHandle(); }
/** * Get a guard that checks if in item is a JS number. * * @return method handle for guard */
Get a guard that checks if in item is a JS number
getNumberGuard
{ "repo_name": "md-5/jdk10", "path": "src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/linker/NashornGuards.java", "license": "gpl-2.0", "size": 10260 }
[ "java.lang.invoke.MethodHandle" ]
import java.lang.invoke.MethodHandle;
import java.lang.invoke.*;
[ "java.lang" ]
java.lang;
1,371,397
@Message(id = 308, value = "expiration cannot be null while creating a single action timer") IllegalArgumentException expirationIsNull();
@Message(id = 308, value = STR) IllegalArgumentException expirationIsNull();
/** * Creates an exception indicating the expiration cannot be null while creating a single action timer * * @return an {@link IllegalArgumentException} for the error. */
Creates an exception indicating the expiration cannot be null while creating a single action timer
expirationIsNull
{ "repo_name": "99sono/wildfly", "path": "ejb3/src/main/java/org/jboss/as/ejb3/logging/EjbLogger.java", "license": "lgpl-2.1", "size": 144385 }
[ "org.jboss.logging.annotations.Message" ]
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.*;
[ "org.jboss.logging" ]
org.jboss.logging;
2,045,689
public static <T> List<T> findAll(List<T> self) { return findAll(self, Closure.IDENTITY); }
static <T> List<T> function(List<T> self) { return findAll(self, Closure.IDENTITY); }
/** * Finds the items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth). * <p> * Example: * <pre class="groovyTestCase"> * def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] * assert items.findAll() == [1, 2, true, 'foo', [4, 5]] * </pre> * * @param self a List * @return a List of the truthy values * @since 2.4.0 * @see Closure#IDENTITY */
Finds the items matching the IDENTITY Closure (i.e.&#160;matching Groovy truth). Example: def items = [1, 2, 0, false, true, '', 'foo', [], [4, 5], null] assert items.findAll() == [1, 2, true, 'foo', [4, 5]] </code>
findAll
{ "repo_name": "apache/incubator-groovy", "path": "src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java", "license": "apache-2.0", "size": 703151 }
[ "groovy.lang.Closure", "java.util.List" ]
import groovy.lang.Closure; import java.util.List;
import groovy.lang.*; import java.util.*;
[ "groovy.lang", "java.util" ]
groovy.lang; java.util;
2,620,535
private void findControllerServiceReferencingComponentIdentifiers(final ControllerServiceReference reference, final Set<ControllerServiceNode> visited) { for (final ConfiguredComponent component : reference.getReferencingComponents()) { // if this is a ControllerService consider it's referencing components if (component instanceof ControllerServiceNode) { final ControllerServiceNode node = (ControllerServiceNode) component; if (!visited.contains(node)) { findControllerServiceReferencingComponentIdentifiers(node.getReferences(), visited); } visited.add(node); } } }
void function(final ControllerServiceReference reference, final Set<ControllerServiceNode> visited) { for (final ConfiguredComponent component : reference.getReferencingComponents()) { if (component instanceof ControllerServiceNode) { final ControllerServiceNode node = (ControllerServiceNode) component; if (!visited.contains(node)) { findControllerServiceReferencingComponentIdentifiers(node.getReferences(), visited); } visited.add(node); } } }
/** * Finds the identifiers for all components referencing a ControllerService. * * @param reference ControllerServiceReference * @param visited ControllerServices we've already visited */
Finds the identifiers for all components referencing a ControllerService
findControllerServiceReferencingComponentIdentifiers
{ "repo_name": "Xsixteen/nifi", "path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/StandardNiFiServiceFacade.java", "license": "apache-2.0", "size": 252586 }
[ "java.util.Set", "org.apache.nifi.controller.ConfiguredComponent", "org.apache.nifi.controller.service.ControllerServiceNode", "org.apache.nifi.controller.service.ControllerServiceReference" ]
import java.util.Set; import org.apache.nifi.controller.ConfiguredComponent; import org.apache.nifi.controller.service.ControllerServiceNode; import org.apache.nifi.controller.service.ControllerServiceReference;
import java.util.*; import org.apache.nifi.controller.*; import org.apache.nifi.controller.service.*;
[ "java.util", "org.apache.nifi" ]
java.util; org.apache.nifi;
1,797,324
Id getNode();
Id getNode();
/** * Get the Id of the node of this edge * @return */
Get the Id of the node of this edge
getNode
{ "repo_name": "mdunker/usergrid", "path": "stack/corepersistence/graph/src/main/java/org/apache/usergrid/persistence/graph/SearchEdgeType.java", "license": "apache-2.0", "size": 1514 }
[ "org.apache.usergrid.persistence.model.entity.Id" ]
import org.apache.usergrid.persistence.model.entity.Id;
import org.apache.usergrid.persistence.model.entity.*;
[ "org.apache.usergrid" ]
org.apache.usergrid;
721,404
public static boolean isTokenLoggable(String tokenName) { IdentityLogTokenParser identityLogTokenParser = IdentityLogTokenParser.getInstance(); Map<String, String> logTokenMap = identityLogTokenParser.getLogTokenMap(); return Boolean.valueOf(logTokenMap.get(tokenName)); }
static boolean function(String tokenName) { IdentityLogTokenParser identityLogTokenParser = IdentityLogTokenParser.getInstance(); Map<String, String> logTokenMap = identityLogTokenParser.getLogTokenMap(); return Boolean.valueOf(logTokenMap.get(tokenName)); }
/** * Check whether the given token value is appropriate to log. * * @param tokenName Name of the token. * @return True if token is appropriate to log. */
Check whether the given token value is appropriate to log
isTokenLoggable
{ "repo_name": "wso2/carbon-identity-framework", "path": "components/identity-core/org.wso2.carbon.identity.core/src/main/java/org/wso2/carbon/identity/core/util/IdentityUtil.java", "license": "apache-2.0", "size": 73793 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
90,473
private BinarySecurity createSecurityToken(Element element) throws WSSecurityException { String type = element.getAttribute("ValueType"); if (X509Security.X509_V3_TYPE.equals(type)) { X509Security x509 = new X509Security(element); return (BinarySecurity) x509; } else if (PKIPathSecurity.getType().equals(type)) { PKIPathSecurity pkiPath = new PKIPathSecurity(element); return (BinarySecurity) pkiPath; } throw new WSSecurityException( WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "unsupportedBinaryTokenType", new Object[]{type} ); }
BinarySecurity function(Element element) throws WSSecurityException { String type = element.getAttribute(STR); if (X509Security.X509_V3_TYPE.equals(type)) { X509Security x509 = new X509Security(element); return (BinarySecurity) x509; } else if (PKIPathSecurity.getType().equals(type)) { PKIPathSecurity pkiPath = new PKIPathSecurity(element); return (BinarySecurity) pkiPath; } throw new WSSecurityException( WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, STR, new Object[]{type} ); }
/** * Checks the <code>element</code> and creates appropriate binary security object. * * @param element The XML element that contains either a <code>BinarySecurityToken * </code> or a <code>PKIPath</code> element. Other element types a not * supported * @return the BinarySecurity object, either a <code>X509Security</code> or a * <code>PKIPathSecurity</code> object. * @throws WSSecurityException */
Checks the <code>element</code> and creates appropriate binary security object
createSecurityToken
{ "repo_name": "madurangasiriwardena/wso2-wss4j", "path": "modules/wss4j/src/org/apache/ws/security/processor/SignatureProcessor.java", "license": "apache-2.0", "size": 35558 }
[ "org.apache.ws.security.WSSecurityException", "org.apache.ws.security.message.token.BinarySecurity", "org.apache.ws.security.message.token.PKIPathSecurity", "org.apache.ws.security.message.token.X509Security", "org.w3c.dom.Element" ]
import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.message.token.BinarySecurity; import org.apache.ws.security.message.token.PKIPathSecurity; import org.apache.ws.security.message.token.X509Security; import org.w3c.dom.Element;
import org.apache.ws.security.*; import org.apache.ws.security.message.token.*; import org.w3c.dom.*;
[ "org.apache.ws", "org.w3c.dom" ]
org.apache.ws; org.w3c.dom;
2,644,920
public void setInstallationDateTime(Calendar installationDateTime) { this.installationDateTime = installationDateTime; } private Calendar uninstallationDateTime = new Calendar() {
void function(Calendar installationDateTime) { this.installationDateTime = installationDateTime; } private Calendar uninstallationDateTime = new Calendar() {
/** * Setter of the property <tt>installationDateTime</tt> * @param installationDateTime The installationDateTime to set. * @uml.property name="installationDateTime" */
Setter of the property installationDateTime
setInstallationDateTime
{ "repo_name": "environmentalinformatics-marburg/jacky", "path": "src/jacky/util/stations/Station.java", "license": "gpl-3.0", "size": 11522 }
[ "java.util.Calendar" ]
import java.util.Calendar;
import java.util.*;
[ "java.util" ]
java.util;
2,421,367
EList<IfcValue> getEnumerationValues();
EList<IfcValue> getEnumerationValues();
/** * Returns the value of the '<em><b>Enumeration Values</b></em>' reference list. * The list contents are of type {@link org.bimserver.models.ifc4.IfcValue}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Enumeration Values</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Enumeration Values</em>' reference list. * @see org.bimserver.models.ifc4.Ifc4Package#getIfcPropertyEnumeration_EnumerationValues() * @model * @generated */
Returns the value of the 'Enumeration Values' reference list. The list contents are of type <code>org.bimserver.models.ifc4.IfcValue</code>. If the meaning of the 'Enumeration Values' reference list isn't clear, there really should be more of a description here...
getEnumerationValues
{ "repo_name": "opensourceBIM/BIMserver", "path": "PluginBase/generated/org/bimserver/models/ifc4/IfcPropertyEnumeration.java", "license": "agpl-3.0", "size": 5557 }
[ "org.eclipse.emf.common.util.EList" ]
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
1,599,786
setName("Create Database Dialog"); setTitle(Messages.getMessage("createdatabase.title")); setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); final String acceptableCharacters = RestrictedInputDocument.WORD_CHARACTERS + "-"; String[] encodingOptions = {"SQL_ASCII", "UTF8"}; productionServerField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); productionNameField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); productionUserNameField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); productionPasswordField = new JTextField(20); productionEncodingCombo = new JComboBox(encodingOptions); itemsServerField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); itemsNameField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); itemsUserNameField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); itemsPasswordField = new JTextField(20); itemsEncodingCombo = new JComboBox(encodingOptions); profileServerField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); profileNameField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); profileUserNameField = new JTextField(new RestrictedInputDocument(acceptableCharacters), "", 20); profilePasswordField = new JTextField(20); profileEncodingCombo = new JComboBox(encodingOptions); Container cp = getContentPane(); GridBagConstraints cons = GridBagHelper.setup(cp); cons.gridwidth = GridBagConstraints.REMAINDER; cons.weightx = 1; cp.add(new JLabel(Messages.getMessage("createdatabase.header")), cons); cons.gridy++; cp.add(new JLabel(Messages.getMessage("database.production")), cons); addDatabaseLabels(cons); cons.gridy++; cons.gridwidth = GridBagConstraints.REMAINDER; cons.weightx = 1; cp.add(new JLabel(Messages.getMessage("database.commontargetitems")), cons); addDatabaseLabels(cons); cons.gridy++; cons.gridwidth = GridBagConstraints.REMAINDER; cons.weightx = 1; cp.add(new JLabel(Messages.getMessage("database.userprofile")), cons); addDatabaseLabels(cons); cons.gridx++; cons.gridy = 2; cons.weightx = 1; cp.add(productionServerField, cons); cons.gridy++; cp.add(productionNameField, cons); cons.gridy++; cp.add(productionUserNameField, cons); cons.gridy++; cp.add(productionPasswordField, cons); cons.gridy++; cp.add(productionEncodingCombo, cons); cons.gridy += 2; cp.add(itemsServerField, cons); cons.gridy++; cp.add(itemsNameField, cons); cons.gridy++; cp.add(itemsUserNameField, cons); cons.gridy++; cp.add(itemsPasswordField, cons); cons.gridy++; cp.add(itemsEncodingCombo, cons); cons.gridy += 2; cp.add(profileServerField, cons); cons.gridy++; cp.add(profileNameField, cons); cons.gridy++; cp.add(profileUserNameField, cons); cons.gridy++; cp.add(profilePasswordField, cons); cons.gridy++; cp.add(profileEncodingCombo, cons); cons.gridy++; cons.gridx = 0; cons.gridwidth = GridBagConstraints.REMAINDER; cons.weightx = 1.0; cp.add(new ButtonPanel(getRootPane(), 1, createDatabaseAction, nextAction, new CancelAction()), cons); DocumentListener fieldListener = new FieldListener(); productionServerField.getDocument().addDocumentListener(fieldListener); productionNameField.getDocument().addDocumentListener(fieldListener); productionUserNameField.getDocument().addDocumentListener(fieldListener); productionPasswordField.getDocument().addDocumentListener(fieldListener); itemsServerField.getDocument().addDocumentListener(fieldListener); itemsNameField.getDocument().addDocumentListener(fieldListener); itemsUserNameField.getDocument().addDocumentListener(fieldListener); itemsPasswordField.getDocument().addDocumentListener(fieldListener); profileServerField.getDocument().addDocumentListener(fieldListener); profileNameField.getDocument().addDocumentListener(fieldListener); profileUserNameField.getDocument().addDocumentListener(fieldListener); profilePasswordField.getDocument().addDocumentListener(fieldListener); pack(); }
setName(STR); setTitle(Messages.getMessage(STR)); setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE); final String acceptableCharacters = RestrictedInputDocument.WORD_CHARACTERS + "-"; String[] encodingOptions = {STR, "UTF8"}; productionServerField = new JTextField(new RestrictedInputDocument(acceptableCharacters), STRSTRSTRSTRSTRSTRSTRSTRSTRcreatedatabase.headerSTRdatabase.productionSTRdatabase.commontargetitemsSTRdatabase.userprofile")), cons); addDatabaseLabels(cons); cons.gridx++; cons.gridy = 2; cons.weightx = 1; cp.add(productionServerField, cons); cons.gridy++; cp.add(productionNameField, cons); cons.gridy++; cp.add(productionUserNameField, cons); cons.gridy++; cp.add(productionPasswordField, cons); cons.gridy++; cp.add(productionEncodingCombo, cons); cons.gridy += 2; cp.add(itemsServerField, cons); cons.gridy++; cp.add(itemsNameField, cons); cons.gridy++; cp.add(itemsUserNameField, cons); cons.gridy++; cp.add(itemsPasswordField, cons); cons.gridy++; cp.add(itemsEncodingCombo, cons); cons.gridy += 2; cp.add(profileServerField, cons); cons.gridy++; cp.add(profileNameField, cons); cons.gridy++; cp.add(profileUserNameField, cons); cons.gridy++; cp.add(profilePasswordField, cons); cons.gridy++; cp.add(profileEncodingCombo, cons); cons.gridy++; cons.gridx = 0; cons.gridwidth = GridBagConstraints.REMAINDER; cons.weightx = 1.0; cp.add(new ButtonPanel(getRootPane(), 1, createDatabaseAction, nextAction, new CancelAction()), cons); DocumentListener fieldListener = new FieldListener(); productionServerField.getDocument().addDocumentListener(fieldListener); productionNameField.getDocument().addDocumentListener(fieldListener); productionUserNameField.getDocument().addDocumentListener(fieldListener); productionPasswordField.getDocument().addDocumentListener(fieldListener); itemsServerField.getDocument().addDocumentListener(fieldListener); itemsNameField.getDocument().addDocumentListener(fieldListener); itemsUserNameField.getDocument().addDocumentListener(fieldListener); itemsPasswordField.getDocument().addDocumentListener(fieldListener); profileServerField.getDocument().addDocumentListener(fieldListener); profileNameField.getDocument().addDocumentListener(fieldListener); profileUserNameField.getDocument().addDocumentListener(fieldListener); profilePasswordField.getDocument().addDocumentListener(fieldListener); pack(); }
/** * Common initialisation: lays out the child components and wires up the necessary * event listeners. */
Common initialisation: lays out the child components and wires up the necessary event listeners
init
{ "repo_name": "drhee/toxoMine", "path": "intermine/MineManager/installer/src/main/java/org/intermine/install/swing/CreateDatabaseDialog.java", "license": "lgpl-2.1", "size": 24777 }
[ "java.awt.GridBagConstraints", "javax.swing.JTextField", "javax.swing.WindowConstants", "javax.swing.event.DocumentListener", "org.intermine.common.swing.ButtonPanel", "org.intermine.common.swing.Messages", "org.intermine.common.swing.text.RestrictedInputDocument" ]
import java.awt.GridBagConstraints; import javax.swing.JTextField; import javax.swing.WindowConstants; import javax.swing.event.DocumentListener; import org.intermine.common.swing.ButtonPanel; import org.intermine.common.swing.Messages; import org.intermine.common.swing.text.RestrictedInputDocument;
import java.awt.*; import javax.swing.*; import javax.swing.event.*; import org.intermine.common.swing.*; import org.intermine.common.swing.text.*;
[ "java.awt", "javax.swing", "org.intermine.common" ]
java.awt; javax.swing; org.intermine.common;
2,238,404
public void createResourceUri_String_String() { when(testResourceServiceImplBase.createResourceUri(anyString(), anyString())).thenCallRealMethod(); URI mockResourceUri = URI.create("mockResourceUri:/"); when(testResourceServiceImplBase.createResourceUri(anyString(), (URI)any(), anyString(), anyString(), anyString())).thenReturn(mockResourceUri); URI resourceUri = testResourceServiceImplBase.createResourceUri("testResourceType", "/test/path"); InOrder inOrder = inOrder(testResourceServiceImplBase); inOrder.verify(testResourceServiceImplBase).createResourceUri("testResourceType", "/test/path"); inOrder.verify(testResourceServiceImplBase).createResourceUri("testResourceType", null, "/test/path", null, null); assertSame(mockResourceUri, resourceUri); verifyNoMoreInteractions(testResourceServiceImplBase); } /** * Test the {@link ResourceServiceImplBase#createResourceUri(String, String, String)} * method. * <p> * This test asserts that the {@link ResourceServiceImplBase#createResourceUri(String, String, String)} * method correctly invokes the {@link ResourceServiceImplBase#createResourceUri(String, URI, String, String, String)}
void function() { when(testResourceServiceImplBase.createResourceUri(anyString(), anyString())).thenCallRealMethod(); URI mockResourceUri = URI.create(STR); when(testResourceServiceImplBase.createResourceUri(anyString(), (URI)any(), anyString(), anyString(), anyString())).thenReturn(mockResourceUri); URI resourceUri = testResourceServiceImplBase.createResourceUri(STR, STR); InOrder inOrder = inOrder(testResourceServiceImplBase); inOrder.verify(testResourceServiceImplBase).createResourceUri(STR, STR); inOrder.verify(testResourceServiceImplBase).createResourceUri(STR, null, STR, null, null); assertSame(mockResourceUri, resourceUri); verifyNoMoreInteractions(testResourceServiceImplBase); } /** * Test the {@link ResourceServiceImplBase#createResourceUri(String, String, String)} * method. * <p> * This test asserts that the {@link ResourceServiceImplBase#createResourceUri(String, String, String)} * method correctly invokes the {@link ResourceServiceImplBase#createResourceUri(String, URI, String, String, String)}
/** * Test the {@link ResourceServiceImplBase#createResourceUri(String, String)} * method. * <p> * This test asserts that the {@link ResourceServiceImplBase#createResourceUri(String, String)} * method correctly invokes the {@link ResourceServiceImplBase#createResourceUri(String, URI, String, String, String)} * method. */
Test the <code>ResourceServiceImplBase#createResourceUri(String, String)</code> method. This test asserts that the <code>ResourceServiceImplBase#createResourceUri(String, String)</code> method correctly invokes the <code>ResourceServiceImplBase#createResourceUri(String, URI, String, String, String)</code> method
createResourceUri_String_String
{ "repo_name": "kjots/java-lib", "path": "service.resource/src/test/java/org/kjots/lib/service/resource/shared/impl/ResourceServiceImplBaseTest.java", "license": "apache-2.0", "size": 13195 }
[ "java.net.URI", "org.junit.Assert", "org.junit.Test", "org.mockito.InOrder", "org.mockito.Matchers", "org.mockito.Mockito", "org.powermock.api.mockito.PowerMockito" ]
import java.net.URI; import org.junit.Assert; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Matchers; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito;
import java.net.*; import org.junit.*; import org.mockito.*; import org.powermock.api.mockito.*;
[ "java.net", "org.junit", "org.mockito", "org.powermock.api" ]
java.net; org.junit; org.mockito; org.powermock.api;
1,445,727
if (n == null) { return null; } digest.reset(); digest.update(n.getBytes(), 0, n.getLength()); byte[] shaBytes = digest.digest(); String shaHex = Hex.encodeHexString(shaBytes); result.set(shaHex); return result; }
if (n == null) { return null; } digest.reset(); digest.update(n.getBytes(), 0, n.getLength()); byte[] shaBytes = digest.digest(); String shaHex = Hex.encodeHexString(shaBytes); result.set(shaHex); return result; }
/** * Convert String to SHA-1 */
Convert String to SHA-1
evaluate
{ "repo_name": "alanfgates/hive", "path": "ql/src/java/org/apache/hadoop/hive/ql/udf/UDFSha1.java", "license": "apache-2.0", "size": 2510 }
[ "org.apache.commons.codec.binary.Hex" ]
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.binary.*;
[ "org.apache.commons" ]
org.apache.commons;
1,637,713
public static void main(String[] args) { // Read the developer key from the properties file. try { // This object is used to make YouTube Data API requests. The last // argument is required, but since we don't need anything // initialized when the HttpRequest is initialized, we override // the interface and provide a no-op function. YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException {}
static void function(String[] args) { try { YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException {}
/** * Initialize a YouTube object to search for videos on YouTube. Then * display the name and thumbnail image of each video in the result set. * * @param args command line args. */
Initialize a YouTube object to search for videos on YouTube. Then display the name and thumbnail image of each video in the result set
main
{ "repo_name": "EUMSSI/EUMSSI-platform", "path": "crawlers/Youtube-Video/ycrawler/src/de/l3s/eumssi/Youtube/Search.java", "license": "apache-2.0", "size": 6563 }
[ "com.google.api.client.http.HttpRequest", "com.google.api.client.http.HttpRequestInitializer", "com.google.api.services.youtube.YouTube", "java.io.IOException" ]
import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.services.youtube.YouTube; import java.io.IOException;
import com.google.api.client.http.*; import com.google.api.services.youtube.*; import java.io.*;
[ "com.google.api", "java.io" ]
com.google.api; java.io;
1,937,945
public void commitLog( LogTableCoreInterface logTable ) throws KettleDatabaseException { this.commitLog( false, logTable ); }
void function( LogTableCoreInterface logTable ) throws KettleDatabaseException { this.commitLog( false, logTable ); }
/** * This methods may be removed in future. * * @param logTable * @throws KettleDatabaseException */
This methods may be removed in future
commitLog
{ "repo_name": "bmorrise/pentaho-kettle", "path": "core/src/main/java/org/pentaho/di/core/database/Database.java", "license": "apache-2.0", "size": 181052 }
[ "org.pentaho.di.core.exception.KettleDatabaseException", "org.pentaho.di.core.logging.LogTableCoreInterface" ]
import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.logging.LogTableCoreInterface;
import org.pentaho.di.core.exception.*; import org.pentaho.di.core.logging.*;
[ "org.pentaho.di" ]
org.pentaho.di;
1,028,009
EReference getTraceCase__TraceCaseDeactivation_1();
EReference getTraceCase__TraceCaseDeactivation_1();
/** * Returns the meta object for the containment reference list '{@link cruise.umple.umple.TraceCase_#getTraceCaseDeactivation_1 <em>Trace Case Deactivation 1</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Trace Case Deactivation 1</em>'. * @see cruise.umple.umple.TraceCase_#getTraceCaseDeactivation_1() * @see #getTraceCase_() * @generated */
Returns the meta object for the containment reference list '<code>cruise.umple.umple.TraceCase_#getTraceCaseDeactivation_1 Trace Case Deactivation 1</code>'.
getTraceCase__TraceCaseDeactivation_1
{ "repo_name": "ahmedvc/umple", "path": "cruise.umple.xtext/src-gen/cruise/umple/umple/UmplePackage.java", "license": "mit", "size": 485842 }
[ "org.eclipse.emf.ecore.EReference" ]
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
392,423
@Override public void clearData() { //Synch is needed because a clear can occur while add occurs synchronized (lock) { model.clearData(); tableRows.clear(); tableRows.put(TOTAL_ROW_LABEL, new Calculator(TOTAL_ROW_LABEL)); model.addRow(tableRows.get(TOTAL_ROW_LABEL)); } }
void function() { synchronized (lock) { model.clearData(); tableRows.clear(); tableRows.put(TOTAL_ROW_LABEL, new Calculator(TOTAL_ROW_LABEL)); model.addRow(tableRows.get(TOTAL_ROW_LABEL)); } }
/** * Clears this visualizer and its model, and forces a repaint of the table. */
Clears this visualizer and its model, and forces a repaint of the table
clearData
{ "repo_name": "ubikfsabbe/jmeter", "path": "src/components/org/apache/jmeter/visualizers/SummaryReport.java", "license": "apache-2.0", "size": 11160 }
[ "org.apache.jmeter.util.Calculator" ]
import org.apache.jmeter.util.Calculator;
import org.apache.jmeter.util.*;
[ "org.apache.jmeter" ]
org.apache.jmeter;
525,754
public Group[] getGroups(SecurityAccess securityAccess) throws GeneralSecurityException { return registry.getGroupsWithRole(securityAccess, this); }
Group[] function(SecurityAccess securityAccess) throws GeneralSecurityException { return registry.getGroupsWithRole(securityAccess, this); }
/** * Returns the <code>Group</code> s that are associated with this role * DIRECTLY, i.e. not via membership in other roles. * * @param securityAccess * @throws GeneralSecurityException */
Returns the <code>Group</code> s that are associated with this role DIRECTLY, i.e. not via membership in other roles
getGroups
{ "repo_name": "lat-lon/deegree2-base", "path": "deegree2-core/src/main/java/org/deegree/security/drm/model/Role.java", "license": "lgpl-2.1", "size": 8607 }
[ "org.deegree.security.GeneralSecurityException", "org.deegree.security.drm.SecurityAccess" ]
import org.deegree.security.GeneralSecurityException; import org.deegree.security.drm.SecurityAccess;
import org.deegree.security.*; import org.deegree.security.drm.*;
[ "org.deegree.security" ]
org.deegree.security;
804,899
public static Font decode (String fontspec) { String name = null; int style = PLAIN; int size = 12; StringTokenizer st = new StringTokenizer(fontspec, "-"); while (st.hasMoreTokens()) { String token = st.nextToken(); if (name == null) { name = token; continue; } if (token.toUpperCase().equals("BOLD")) { style = BOLD; continue; } if (token.toUpperCase().equals("ITALIC")) { style = ITALIC; continue; } if (token.toUpperCase().equals("BOLDITALIC")) { style = BOLD | ITALIC; continue; } int tokenval = 0; try { tokenval = Integer.parseInt(token); } catch(NumberFormatException e) { ; } if (tokenval != 0) size = tokenval; } return getFontFromToolkit (name, attrsToMap (style, size)); }
static Font function (String fontspec) { String name = null; int style = PLAIN; int size = 12; StringTokenizer st = new StringTokenizer(fontspec, "-"); while (st.hasMoreTokens()) { String token = st.nextToken(); if (name == null) { name = token; continue; } if (token.toUpperCase().equals("BOLD")) { style = BOLD; continue; } if (token.toUpperCase().equals(STR)) { style = ITALIC; continue; } if (token.toUpperCase().equals(STR)) { style = BOLD ITALIC; continue; } int tokenval = 0; try { tokenval = Integer.parseInt(token); } catch(NumberFormatException e) { ; } if (tokenval != 0) size = tokenval; } return getFontFromToolkit (name, attrsToMap (style, size)); }
/** * Creates a <code>Font</code> object from the specified string, which * is in one of the following formats: * <p> * <ul> * <li>fontname-style-pointsize * <li>fontname-style * <li>fontname-pointsize * <li>fontname * </ul> * <p> * The style should be one of BOLD, ITALIC, or BOLDITALIC. The default * style if none is specified is PLAIN. The default size if none * is specified is 12. */
Creates a <code>Font</code> object from the specified string, which is in one of the following formats: fontname-style-pointsize fontname-style fontname-pointsize fontname The style should be one of BOLD, ITALIC, or BOLDITALIC. The default style if none is specified is PLAIN. The default size if none is specified is 12
decode
{ "repo_name": "aosm/gcc_40", "path": "libjava/java/awt/Font.java", "license": "gpl-2.0", "size": 39444 }
[ "java.util.StringTokenizer" ]
import java.util.StringTokenizer;
import java.util.*;
[ "java.util" ]
java.util;
345,225
public void valueForPathChanged(TreePath path, Object newValue) { System.out.println("*** valueForPathChanged : " + path + " --> " + newValue); }
void function(TreePath path, Object newValue) { System.out.println(STR + path + STR + newValue); }
/** * Messaged when the user has altered the value for the item identified by * path to newValue. Not used by this model. */
Messaged when the user has altered the value for the item identified by path to newValue. Not used by this model
valueForPathChanged
{ "repo_name": "jalian-systems/marathonv5", "path": "marathon-java/marathon-test-helpers/src/main/java/components/GenealogyModel.java", "license": "apache-2.0", "size": 5669 }
[ "javax.swing.tree.TreePath" ]
import javax.swing.tree.TreePath;
import javax.swing.tree.*;
[ "javax.swing" ]
javax.swing;
942,947
static Pair<RelTraitSet, List<RelTraitSet>> passThroughTraitsForJoin( RelTraitSet required, JoinRelType joinType, int leftInputFieldCount, RelTraitSet joinTraitSet) { RelCollation collation = required.getCollation(); if (collation == null || collation == RelCollations.EMPTY || joinType == JoinRelType.FULL || joinType == JoinRelType.RIGHT) { return null; } for (RelFieldCollation fc : collation.getFieldCollations()) { // If field collation belongs to right input: cannot push down collation. if (fc.getFieldIndex() >= leftInputFieldCount) { return null; } } RelTraitSet passthroughTraitSet = joinTraitSet.replace(collation); return Pair.of(passthroughTraitSet, ImmutableList.of( passthroughTraitSet, passthroughTraitSet.replace(RelCollations.EMPTY))); }
static Pair<RelTraitSet, List<RelTraitSet>> passThroughTraitsForJoin( RelTraitSet required, JoinRelType joinType, int leftInputFieldCount, RelTraitSet joinTraitSet) { RelCollation collation = required.getCollation(); if (collation == null collation == RelCollations.EMPTY joinType == JoinRelType.FULL joinType == JoinRelType.RIGHT) { return null; } for (RelFieldCollation fc : collation.getFieldCollations()) { if (fc.getFieldIndex() >= leftInputFieldCount) { return null; } } RelTraitSet passthroughTraitSet = joinTraitSet.replace(collation); return Pair.of(passthroughTraitSet, ImmutableList.of( passthroughTraitSet, passthroughTraitSet.replace(RelCollations.EMPTY))); }
/** * This function can be reused when a Join's traits pass-down shall only * pass through collation to left input. * * @param required required trait set for the join * @param joinType the join type * @param leftInputFieldCount number of field count of left join input * @param joinTraitSet trait set of the join */
This function can be reused when a Join's traits pass-down shall only pass through collation to left input
passThroughTraitsForJoin
{ "repo_name": "vlsi/calcite", "path": "core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTraitsUtils.java", "license": "apache-2.0", "size": 7906 }
[ "com.google.common.collect.ImmutableList", "java.util.List", "org.apache.calcite.plan.RelTraitSet", "org.apache.calcite.rel.RelCollation", "org.apache.calcite.rel.RelCollations", "org.apache.calcite.rel.RelFieldCollation", "org.apache.calcite.rel.core.JoinRelType", "org.apache.calcite.util.Pair" ]
import com.google.common.collect.ImmutableList; import java.util.List; import org.apache.calcite.plan.RelTraitSet; import org.apache.calcite.rel.RelCollation; import org.apache.calcite.rel.RelCollations; import org.apache.calcite.rel.RelFieldCollation; import org.apache.calcite.rel.core.JoinRelType; import org.apache.calcite.util.Pair;
import com.google.common.collect.*; import java.util.*; import org.apache.calcite.plan.*; import org.apache.calcite.rel.*; import org.apache.calcite.rel.core.*; import org.apache.calcite.util.*;
[ "com.google.common", "java.util", "org.apache.calcite" ]
com.google.common; java.util; org.apache.calcite;
2,227,462
private List<String> getPartsInPathTemplate(String templateString) { //divide the node's templateString in parts of regular expression and normal string List<String> parts = new ArrayList<String>(); Matcher matcher = FeedDataPath.PATTERN.matcher(templateString); int currentIndex = 0; while (matcher.find()) { parts.add(templateString.substring(currentIndex, matcher.start())); parts.add(matcher.group()); currentIndex = matcher.end(); } if (currentIndex != templateString.length()) { parts.add(templateString.substring(currentIndex)); } return Collections.unmodifiableList(parts); }
List<String> function(String templateString) { List<String> parts = new ArrayList<String>(); Matcher matcher = FeedDataPath.PATTERN.matcher(templateString); int currentIndex = 0; while (matcher.find()) { parts.add(templateString.substring(currentIndex, matcher.start())); parts.add(matcher.group()); currentIndex = matcher.end(); } if (currentIndex != templateString.length()) { parts.add(templateString.substring(currentIndex)); } return Collections.unmodifiableList(parts); }
/** * Divide a given template string into parts of regex and character strings * e.g. /data/cas/${YEAR}/${MONTH}/${DAY} will be converted to * [/data/cas/, ${YEAR}, /, ${MONTH}, /, ${DAY}] * @param templateString input string representing a feed's path template * @return list of parts in input templateString which are either completely regex or normal string. */
Divide a given template string into parts of regex and character strings e.g. /data/cas/${YEAR}/${MONTH}/${DAY} will be converted to [/data/cas/, ${YEAR}, /, ${MONTH}, /, ${DAY}]
getPartsInPathTemplate
{ "repo_name": "sriksun/falcon", "path": "common/src/main/java/org/apache/falcon/util/FalconRadixUtils.java", "license": "apache-2.0", "size": 13636 }
[ "java.util.ArrayList", "java.util.Collections", "java.util.List", "java.util.regex.Matcher", "org.apache.falcon.entity.common.FeedDataPath" ]
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import org.apache.falcon.entity.common.FeedDataPath;
import java.util.*; import java.util.regex.*; import org.apache.falcon.entity.common.*;
[ "java.util", "org.apache.falcon" ]
java.util; org.apache.falcon;
2,117,280
public Date getLastupdatedtime() { return lastupdatedtime; }
Date function() { return lastupdatedtime; }
/** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product_catalog.lastUpdatedTime * * @return the value of m_crm_product_catalog.lastUpdatedTime * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */
This method was generated by MyBatis Generator. This method returns the value of the database column m_crm_product_catalog.lastUpdatedTime
getLastupdatedtime
{ "repo_name": "maduhu/mycollab", "path": "mycollab-services/src/main/java/com/esofthead/mycollab/module/crm/domain/ProductCatalog.java", "license": "agpl-3.0", "size": 25847 }
[ "java.util.Date" ]
import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
2,404,610
public Rect getBounds(boolean reverse) { mBounds.set(0, 0, mWidth, mMaxEffectHeight); mBounds.offset(mX, mY - (reverse ? mMaxEffectHeight : 0)); return mBounds; }
Rect function(boolean reverse) { mBounds.set(0, 0, mWidth, mMaxEffectHeight); mBounds.offset(mX, mY - (reverse ? mMaxEffectHeight : 0)); return mBounds; }
/** * Returns the bounds of the edge effect. * * @hide */
Returns the bounds of the edge effect
getBounds
{ "repo_name": "haikuowuya/android_system_code", "path": "src/android/widget/EdgeEffect.java", "license": "apache-2.0", "size": 16615 }
[ "android.graphics.Rect" ]
import android.graphics.Rect;
import android.graphics.*;
[ "android.graphics" ]
android.graphics;
1,161,280
@Deprecated public void setContainerProperties(OioUrl url, Map<String, String> properties, boolean clear, RequestContext reqCtx) { setContainerProperties(url, properties, clear, null, reqCtx); }
void function(OioUrl url, Map<String, String> properties, boolean clear, RequestContext reqCtx) { setContainerProperties(url, properties, clear, null, reqCtx); }
/** * Set properties to the specified container. * * @param url * the URL of the container to set properties * @param properties * the properties to set * @param clear * clear previous properties * @param reqCtx * common parameters to all requests * @throws ContainerNotFoundException * if the specified container doesn't exist * @throws OioSystemException * if any error occurs during request execution */
Set properties to the specified container
setContainerProperties
{ "repo_name": "open-io/oio-api-java", "path": "src/main/java/io/openio/sds/proxy/ProxyClient.java", "license": "lgpl-3.0", "size": 69667 }
[ "io.openio.sds.RequestContext", "io.openio.sds.models.OioUrl", "java.util.Map" ]
import io.openio.sds.RequestContext; import io.openio.sds.models.OioUrl; import java.util.Map;
import io.openio.sds.*; import io.openio.sds.models.*; import java.util.*;
[ "io.openio.sds", "java.util" ]
io.openio.sds; java.util;
454,452
public boolean isEnabled(Object id) { Action action = getAction(id); if (action != null) { return action.isEnabled(); } return false; }
boolean function(Object id) { Action action = getAction(id); if (action != null) { return action.isEnabled(); } return false; }
/** * Returns the enabled state of the <code>Action</code>. When enabled, * any component associated with this object is active and * able to fire this object's <code>actionPerformed</code> method. * * @param id value of the action id * @return true if this <code>Action</code> is enabled; false if the * action doesn't exist or disabled. */
Returns the enabled state of the <code>Action</code>. When enabled, any component associated with this object is active and able to fire this object's <code>actionPerformed</code> method
isEnabled
{ "repo_name": "Mindtoeye/Hoop", "path": "src/org/jdesktop/swingx/action/ActionManager.java", "license": "lgpl-3.0", "size": 12416 }
[ "javax.swing.Action" ]
import javax.swing.Action;
import javax.swing.*;
[ "javax.swing" ]
javax.swing;
2,692,676
public static <C extends AlluxioService.Client> void closeThriftClient(C client) { // Note that the input and output protocol is the same in Alluxio. TTransport transport = client.getOutputProtocol().getTransport(); if (transport.isOpen()) { transport.close(); } }
static <C extends AlluxioService.Client> void function(C client) { TTransport transport = client.getOutputProtocol().getTransport(); if (transport.isOpen()) { transport.close(); } }
/** * A helper function to close thrift clients. * * @param client the thrift client to close * @param <C> the thrift client type */
A helper function to close thrift clients
closeThriftClient
{ "repo_name": "yuluo-ding/alluxio", "path": "core/common/src/main/java/alluxio/network/connection/ThriftClientPool.java", "license": "apache-2.0", "size": 10482 }
[ "org.apache.thrift.transport.TTransport" ]
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.*;
[ "org.apache.thrift" ]
org.apache.thrift;
2,446,898
public static void verifyAndAddTransactionalProperties(JobConf job, StorageDescriptor sd) { if (AcidUtils.isTablePropertyTransactional(job)) { AcidUtils.setTransactionalTableScan(job, true); // No work is needed, if schema evolution is used if (Utilities.isSchemaEvolutionEnabled(job, true) && job.get(IOConstants.SCHEMA_EVOLUTION_COLUMNS) != null && job.get(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES) != null) { return; } String colNames; String colTypes; // Try to get get column names and types from table or partition properties. If they are absent there, get columns // data from storage descriptor of the table colNames = job.get(serdeConstants.LIST_COLUMNS); colTypes = job.get(serdeConstants.LIST_COLUMN_TYPES); if (colNames == null || colTypes == null) { colNames = sd.getCols().stream() .map(FieldSchema::getName) .collect(Collectors.joining(",")); colTypes = sd.getCols().stream() .map(FieldSchema::getType) .collect(Collectors.joining(",")); } job.set(IOConstants.SCHEMA_EVOLUTION_COLUMNS, colNames); job.set(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, colTypes); } }
static void function(JobConf job, StorageDescriptor sd) { if (AcidUtils.isTablePropertyTransactional(job)) { AcidUtils.setTransactionalTableScan(job, true); if (Utilities.isSchemaEvolutionEnabled(job, true) && job.get(IOConstants.SCHEMA_EVOLUTION_COLUMNS) != null && job.get(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES) != null) { return; } String colNames; String colTypes; colNames = job.get(serdeConstants.LIST_COLUMNS); colTypes = job.get(serdeConstants.LIST_COLUMN_TYPES); if (colNames == null colTypes == null) { colNames = sd.getCols().stream() .map(FieldSchema::getName) .collect(Collectors.joining(",")); colTypes = sd.getCols().stream() .map(FieldSchema::getType) .collect(Collectors.joining(",")); } job.set(IOConstants.SCHEMA_EVOLUTION_COLUMNS, colNames); job.set(IOConstants.SCHEMA_EVOLUTION_COLUMNS_TYPES, colTypes); } }
/** * This method checks whether the table is transactional and set necessary properties in {@link JobConf}.<br> * If schema evolution properties aren't set in job conf for the input format, method sets the column names * and types from table/partition properties or storage descriptor. * * @param job the job to update * @param sd storage descriptor */
This method checks whether the table is transactional and set necessary properties in <code>JobConf</code>. If schema evolution properties aren't set in job conf for the input format, method sets the column names and types from table/partition properties or storage descriptor
verifyAndAddTransactionalProperties
{ "repo_name": "Ben-Zvi/drill", "path": "contrib/storage-hive/core/src/main/java/org/apache/drill/exec/store/hive/HiveUtilities.java", "license": "apache-2.0", "size": 37094 }
[ "java.util.stream.Collectors", "org.apache.hadoop.hive.metastore.api.FieldSchema", "org.apache.hadoop.hive.metastore.api.StorageDescriptor", "org.apache.hadoop.hive.ql.exec.Utilities", "org.apache.hadoop.hive.ql.io.AcidUtils", "org.apache.hadoop.hive.ql.io.IOConstants", "org.apache.hadoop.mapred.JobConf" ]
import java.util.stream.Collectors; import org.apache.hadoop.hive.metastore.api.FieldSchema; import org.apache.hadoop.hive.metastore.api.StorageDescriptor; import org.apache.hadoop.hive.ql.exec.Utilities; import org.apache.hadoop.hive.ql.io.AcidUtils; import org.apache.hadoop.hive.ql.io.IOConstants; import org.apache.hadoop.mapred.JobConf;
import java.util.stream.*; import org.apache.hadoop.hive.metastore.api.*; import org.apache.hadoop.hive.ql.exec.*; import org.apache.hadoop.hive.ql.io.*; import org.apache.hadoop.mapred.*;
[ "java.util", "org.apache.hadoop" ]
java.util; org.apache.hadoop;
1,521,316
@Test @WithMockAuth(id="1") public void testGlobalsettingsPut() throws Exception { given(mockSettingsRepository.findById(1)).willReturn(mockSettings); mockMvc.perform(put("/api/globalsettings") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\n" + " \"deadline\": \"13:00:00.000\",\n" + " \"currency\": \"string\",\n" + " \"notes\": \"string\",\n" + " \"tos\": \"string\",\n" + " \"policy\": \"string\",\n" + " \"lastEdit\": {\n" + " \"timeStamp\": \"2017-05-03T09:54:00.741Z\",\n" + " \"version\": 0\n" + " }\n" + "}") ).andExpect(status().isNoContent()); // we verify that we called findAll method once only on the repo. verify(mockSettingsRepository, times(1)).findById(1); // we verify that we didnt call anything else on the repo verifyNoMoreInteractions(mockSettingsRepository); }
@WithMockAuth(id="1") void function() throws Exception { given(mockSettingsRepository.findById(1)).willReturn(mockSettings); mockMvc.perform(put(STR) .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\n" + STRdeadline\STR13:00:00.000\",\n" + STRcurrency\STRstring\",\n" + STRnotes\STRstring\",\n" + STRtos\STRstring\",\n" + STRpolicy\STRstring\",\n" + STRlastEdit\STR + STRtimeStamp\STR2017-05-03T09:54:00.741Z\",\n" + STRversion\STR + STR + "}") ).andExpect(status().isNoContent()); verify(mockSettingsRepository, times(1)).findById(1); verifyNoMoreInteractions(mockSettingsRepository); }
/** * Test of globalsettingsPut method, of class GlobalsettingsApiController. */
Test of globalsettingsPut method, of class GlobalsettingsApiController
testGlobalsettingsPut
{ "repo_name": "aliartos/yum", "path": "Yum/src/test/java/com/jrtechnologies/yum/api/GlobalsettingsApiControllerTest.java", "license": "gpl-3.0", "size": 7622 }
[ "com.jrtechnologies.test.annotation.WithMockAuth", "org.mockito.BDDMockito", "org.mockito.Mockito", "org.springframework.http.MediaType", "org.springframework.test.web.servlet.result.MockMvcResultMatchers" ]
import com.jrtechnologies.test.annotation.WithMockAuth; import org.mockito.BDDMockito; import org.mockito.Mockito; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import com.jrtechnologies.test.annotation.*; import org.mockito.*; import org.springframework.http.*; import org.springframework.test.web.servlet.result.*;
[ "com.jrtechnologies.test", "org.mockito", "org.springframework.http", "org.springframework.test" ]
com.jrtechnologies.test; org.mockito; org.springframework.http; org.springframework.test;
893,296
public EntityPlayer getOriginal() { return original; }
EntityPlayer function() { return original; }
/** * The old EntityPlayer that this new entity is a clone of. */
The old EntityPlayer that this new entity is a clone of
getOriginal
{ "repo_name": "Im-Jrotica/forge_latest", "path": "build/tmp/recompileMc/sources/net/minecraftforge/event/entity/player/PlayerEvent.java", "license": "lgpl-2.1", "size": 12100 }
[ "net.minecraft.entity.player.EntityPlayer" ]
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.*;
[ "net.minecraft.entity" ]
net.minecraft.entity;
1,438,622
public Set<String> getTargetLanguages() { return targetLanguages; }
Set<String> function() { return targetLanguages; }
/** * Returns the set of target languages. * * @return The set of target languages. */
Returns the set of target languages
getTargetLanguages
{ "repo_name": "IBM-Bluemix/gaas-java-client", "path": "src/main/java/com/ibm/g11n/pipeline/client/NewDocumentData.java", "license": "apache-2.0", "size": 3220 }
[ "java.util.Set" ]
import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
1,607,872
boolean saveFrame(@NonNull Frame frame, @NonNull String sequenceID);
boolean saveFrame(@NonNull Frame frame, @NonNull String sequenceID);
/** * Persists the given frame into the persistence. * @param frame the {@code Frame} which will be saved. It cannot be null. * @param sequenceID the {@code identifier} for the sequence to which the frame corresponds to. * @return {@code true} if the save operation was performed successful, {@code false} otherwise. */
Persists the given frame into the persistence
saveFrame
{ "repo_name": "openstreetview/android", "path": "app/src/main/java/com/telenav/osv/data/frame/datasource/local/FrameLocalDataSource.java", "license": "lgpl-3.0", "size": 3263 }
[ "androidx.annotation.NonNull", "com.telenav.osv.data.frame.model.Frame" ]
import androidx.annotation.NonNull; import com.telenav.osv.data.frame.model.Frame;
import androidx.annotation.*; import com.telenav.osv.data.frame.model.*;
[ "androidx.annotation", "com.telenav.osv" ]
androidx.annotation; com.telenav.osv;
102,394
protected void drawDashedHorizontalLine(Graphics g, int y, int x1, int x2) { g.setColor(getHashColor()); for (int i = x1; i < x2; i += 2) g.drawLine(i, y, i + 1, y); }
void function(Graphics g, int y, int x1, int x2) { g.setColor(getHashColor()); for (int i = x1; i < x2; i += 2) g.drawLine(i, y, i + 1, y); }
/** * Draws a dashed horizontal line. * * @param g - the graphics configuration. * @param y - the y location to start drawing at * @param x1 - the x location to start drawing at * @param x2 - the x location to finish drawing at */
Draws a dashed horizontal line
drawDashedHorizontalLine
{ "repo_name": "taciano-perez/JamVM-PH", "path": "src/classpath/javax/swing/plaf/basic/BasicTreeUI.java", "license": "gpl-2.0", "size": 115323 }
[ "java.awt.Graphics" ]
import java.awt.Graphics;
import java.awt.*;
[ "java.awt" ]
java.awt;
573,388
@SmallTest @Feature({"ContextualSearch"}) @Restriction({RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) public void testContextualSearchDismissedOnForegroundTabCrash() throws InterruptedException, TimeoutException { clickWordNode("states"); assertEquals("States", getSelectedText()); waitForPanelToPeekAndAssert();
@Feature({STR}) @Restriction({RESTRICTION_TYPE_PHONE, RESTRICTION_TYPE_NON_LOW_END_DEVICE}) void function() throws InterruptedException, TimeoutException { clickWordNode(STR); assertEquals(STR, getSelectedText()); waitForPanelToPeekAndAssert();
/** * Tests that the panel closes when its base page crashes. */
Tests that the panel closes when its base page crashes
testContextualSearchDismissedOnForegroundTabCrash
{ "repo_name": "Just-D/chromium-1", "path": "chrome/android/javatests/src/org/chromium/chrome/browser/contextualsearch/ContextualSearchManagerTest.java", "license": "bsd-3-clause", "size": 70757 }
[ "java.util.concurrent.TimeoutException", "org.chromium.base.test.util.Feature", "org.chromium.base.test.util.Restriction" ]
import java.util.concurrent.TimeoutException; import org.chromium.base.test.util.Feature; import org.chromium.base.test.util.Restriction;
import java.util.concurrent.*; import org.chromium.base.test.util.*;
[ "java.util", "org.chromium.base" ]
java.util; org.chromium.base;
2,739,025
protected List<VOMSServerInfo> getVOMSServerInfos(VOMSACRequest request) { List<VOMSServerInfo> vomsServerInfos = new ArrayList<VOMSServerInfo>( serverInfoStore.getVOMSServerInfo(request.getVoName())); if (!vomsServerInfos.isEmpty()) { Collections.shuffle(vomsServerInfos); } return vomsServerInfos; } public static class Builder { private VOMSRequestListener requestListener = NullListener.INSTANCE; private VOMSProtocolListener protocolListener = NullListener.INSTANCE; private VOMSServerInfoStoreListener storeListener = NullListener.INSTANCE; private X509CertChainValidatorExt validator; private VOMSServerInfoStore serverInfoStore; private VOMSESLookupStrategy vomsesLookupStrategy; private List<String> vomsesLocations; private int connectTimeout = AbstractVOMSProtocol.DEFAULT_CONNECT_TIMEOUT; private int readTimeout = AbstractVOMSProtocol.DEFAULT_READ_TIMEOUT; private boolean skipHostnameChecks = true; protected VOMSProtocol httpProtocol; protected VOMSProtocol legacyProtocol; public Builder(X509CertChainValidatorExt certChainValidator) { if (certChainValidator == null) throw new NullPointerException( "Please provide a non-null certificate chain validator"); this.validator = certChainValidator; }
List<VOMSServerInfo> function(VOMSACRequest request) { List<VOMSServerInfo> vomsServerInfos = new ArrayList<VOMSServerInfo>( serverInfoStore.getVOMSServerInfo(request.getVoName())); if (!vomsServerInfos.isEmpty()) { Collections.shuffle(vomsServerInfos); } return vomsServerInfos; } public static class Builder { private VOMSRequestListener requestListener = NullListener.INSTANCE; private VOMSProtocolListener protocolListener = NullListener.INSTANCE; private VOMSServerInfoStoreListener storeListener = NullListener.INSTANCE; private X509CertChainValidatorExt validator; private VOMSServerInfoStore serverInfoStore; private VOMSESLookupStrategy vomsesLookupStrategy; private List<String> vomsesLocations; private int connectTimeout = AbstractVOMSProtocol.DEFAULT_CONNECT_TIMEOUT; private int readTimeout = AbstractVOMSProtocol.DEFAULT_READ_TIMEOUT; private boolean skipHostnameChecks = true; protected VOMSProtocol httpProtocol; protected VOMSProtocol legacyProtocol; public Builder(X509CertChainValidatorExt certChainValidator) { if (certChainValidator == null) throw new NullPointerException( STR); this.validator = certChainValidator; }
/** * Get VOMS server endpoint information that matches with the * {@link VOMSACRequest} passed as argument. * * This method returns a random shuffle of the {@link VOMSServerInfo} objects * that match the input request. * * @param request * the request * @return a possibly empty {@link List} of {@link VOMSServerInfo} objects */
Get VOMS server endpoint information that matches with the <code>VOMSACRequest</code> passed as argument. This method returns a random shuffle of the <code>VOMSServerInfo</code> objects that match the input request
getVOMSServerInfos
{ "repo_name": "ellert/voms-api-java", "path": "src/main/java/org/italiangrid/voms/request/impl/DefaultVOMSACService.java", "license": "apache-2.0", "size": 16378 }
[ "eu.emi.security.authn.x509.X509CertChainValidatorExt", "java.util.ArrayList", "java.util.Collections", "java.util.List", "org.italiangrid.voms.request.VOMSACRequest", "org.italiangrid.voms.request.VOMSESLookupStrategy", "org.italiangrid.voms.request.VOMSProtocol", "org.italiangrid.voms.request.VOMSProtocolListener", "org.italiangrid.voms.request.VOMSRequestListener", "org.italiangrid.voms.request.VOMSServerInfo", "org.italiangrid.voms.request.VOMSServerInfoStore", "org.italiangrid.voms.request.VOMSServerInfoStoreListener", "org.italiangrid.voms.util.NullListener" ]
import eu.emi.security.authn.x509.X509CertChainValidatorExt; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.italiangrid.voms.request.VOMSACRequest; import org.italiangrid.voms.request.VOMSESLookupStrategy; import org.italiangrid.voms.request.VOMSProtocol; import org.italiangrid.voms.request.VOMSProtocolListener; import org.italiangrid.voms.request.VOMSRequestListener; import org.italiangrid.voms.request.VOMSServerInfo; import org.italiangrid.voms.request.VOMSServerInfoStore; import org.italiangrid.voms.request.VOMSServerInfoStoreListener; import org.italiangrid.voms.util.NullListener;
import eu.emi.security.authn.x509.*; import java.util.*; import org.italiangrid.voms.request.*; import org.italiangrid.voms.util.*;
[ "eu.emi.security", "java.util", "org.italiangrid.voms" ]
eu.emi.security; java.util; org.italiangrid.voms;
2,603,736
YangRequestWorkBench ydtBuilder = integer32Ydt(); validateTree(ydtBuilder); }
YangRequestWorkBench ydtBuilder = integer32Ydt(); validateTree(ydtBuilder); }
/** * Creates and validates integer32 ydt covering different positive scenario. */
Creates and validates integer32 ydt covering different positive scenario
positiveTest
{ "repo_name": "sdnwiselab/onos", "path": "apps/yms/ut/src/test/java/org/onosproject/yms/app/ydt/YdtInteger32Test.java", "license": "apache-2.0", "size": 16480 }
[ "org.onosproject.yms.app.ydt.YdtTestUtils" ]
import org.onosproject.yms.app.ydt.YdtTestUtils;
import org.onosproject.yms.app.ydt.*;
[ "org.onosproject.yms" ]
org.onosproject.yms;
1,747,738
public void annotateText(com.google.cloud.language.v1beta2.AnnotateTextRequest request, io.grpc.stub.StreamObserver<com.google.cloud.language.v1beta2.AnnotateTextResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_ANNOTATE_TEXT, getCallOptions()), request, responseObserver); } } public static final class LanguageServiceBlockingStub extends io.grpc.stub.AbstractStub<LanguageServiceBlockingStub> { private LanguageServiceBlockingStub(io.grpc.Channel channel) { super(channel); } private LanguageServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); }
void function(com.google.cloud.language.v1beta2.AnnotateTextRequest request, io.grpc.stub.StreamObserver<com.google.cloud.language.v1beta2.AnnotateTextResponse> responseObserver) { asyncUnaryCall( getChannel().newCall(METHOD_ANNOTATE_TEXT, getCallOptions()), request, responseObserver); } } public static final class LanguageServiceBlockingStub extends io.grpc.stub.AbstractStub<LanguageServiceBlockingStub> { private LanguageServiceBlockingStub(io.grpc.Channel channel) { super(channel); } private LanguageServiceBlockingStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { super(channel, callOptions); }
/** * <pre> * A convenience method that provides all syntax, sentiment, and entity * features in one call. * </pre> */
<code> A convenience method that provides all syntax, sentiment, and entity features in one call. </code>
annotateText
{ "repo_name": "landrito/api-client-staging", "path": "generated/java/grpc-google-cloud-language-v1beta2/src/main/java/com/google/cloud/language/v1beta2/LanguageServiceGrpc.java", "license": "bsd-3-clause", "size": 24028 }
[ "io.grpc.stub.ClientCalls", "io.grpc.stub.ServerCalls" ]
import io.grpc.stub.ClientCalls; import io.grpc.stub.ServerCalls;
import io.grpc.stub.*;
[ "io.grpc.stub" ]
io.grpc.stub;
550,694
@Override public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, World worldIn, BlockPos pos) { return new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.99D, 1.0D); }
AxisAlignedBB function(IBlockState blockState, World worldIn, BlockPos pos) { return new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.99D, 1.0D); }
/** * Verschnellt ein kolitiertes Entity * @param blockState * @param worldIn * @param pos * @return */
Verschnellt ein kolitiertes Entity
getCollisionBoundingBox
{ "repo_name": "MineCraftModMaker/MoveCraft", "path": "src/main/java/com/mcmm/movecraft/Street/darkstreet/DarkStreet.java", "license": "gpl-3.0", "size": 2850 }
[ "net.minecraft.block.state.IBlockState", "net.minecraft.util.math.AxisAlignedBB", "net.minecraft.util.math.BlockPos", "net.minecraft.world.World" ]
import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World;
import net.minecraft.block.state.*; import net.minecraft.util.math.*; import net.minecraft.world.*;
[ "net.minecraft.block", "net.minecraft.util", "net.minecraft.world" ]
net.minecraft.block; net.minecraft.util; net.minecraft.world;
665,995
public int deleteAllContacts() { // CALLER_IS_SYNCADAPTER allows us to actually wipe the RawContact from the device, otherwise // would be just flagged for deletion Uri deleteUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon(). appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); Log.d(Constants.TAG, "Deleting all raw contacts associated to OK..."); int delete = mContentResolver.delete(deleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[]{ Constants.ACCOUNT_TYPE }); Uri mainProfileDeleteUri = ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); delete += mContentResolver.delete(mainProfileDeleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[]{ Constants.ACCOUNT_TYPE }); return delete; }
int function() { Uri deleteUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon(). appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); Log.d(Constants.TAG, STR); int delete = mContentResolver.delete(deleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[]{ Constants.ACCOUNT_TYPE }); Uri mainProfileDeleteUri = ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI.buildUpon() .appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build(); delete += mContentResolver.delete(mainProfileDeleteUri, ContactsContract.RawContacts.ACCOUNT_TYPE + "=?", new String[]{ Constants.ACCOUNT_TYPE }); return delete; }
/** * Delete all raw contacts associated to OpenKeychain, including those from "me" contact * defined by ContactsContract.Profile * * @return number of rows deleted */
Delete all raw contacts associated to OpenKeychain, including those from "me" contact defined by ContactsContract.Profile
deleteAllContacts
{ "repo_name": "fjodorver/open-keychain", "path": "OpenKeychain/src/main/java/org/sufficientlysecure/keychain/util/ContactHelper.java", "license": "gpl-3.0", "size": 35712 }
[ "android.net.Uri", "android.provider.ContactsContract", "org.sufficientlysecure.keychain.Constants" ]
import android.net.Uri; import android.provider.ContactsContract; import org.sufficientlysecure.keychain.Constants;
import android.net.*; import android.provider.*; import org.sufficientlysecure.keychain.*;
[ "android.net", "android.provider", "org.sufficientlysecure.keychain" ]
android.net; android.provider; org.sufficientlysecure.keychain;
1,646,266
@ServiceMethod(returns = ReturnType.SINGLE) private Mono<PrivateEndpointConnectionInner> updateAsync( String privateEndpointConnectionName, String resourceGroupName, String resourceName, PrivateEndpointConnectionInner parameters) { return updateWithResponseAsync(privateEndpointConnectionName, resourceGroupName, resourceName, parameters) .flatMap( (Response<PrivateEndpointConnectionInner> res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); }
@ServiceMethod(returns = ReturnType.SINGLE) Mono<PrivateEndpointConnectionInner> function( String privateEndpointConnectionName, String resourceGroupName, String resourceName, PrivateEndpointConnectionInner parameters) { return updateWithResponseAsync(privateEndpointConnectionName, resourceGroupName, resourceName, parameters) .flatMap( (Response<PrivateEndpointConnectionInner> res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); }
/** * Update the state of specified private endpoint connection. * * @param privateEndpointConnectionName The name of the private endpoint connection. * @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 resourceName The name of the resource. * @param parameters The resource of private endpoint and its properties. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a private endpoint connection to an azure resource. */
Update the state of specified private endpoint connection
updateAsync
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/webpubsub/azure-resourcemanager-webpubsub/src/main/java/com/azure/resourcemanager/webpubsub/implementation/WebPubSubPrivateEndpointConnectionsClientImpl.java", "license": "mit", "size": 53433 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.http.rest.Response", "com.azure.resourcemanager.webpubsub.fluent.models.PrivateEndpointConnectionInner" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.resourcemanager.webpubsub.fluent.models.PrivateEndpointConnectionInner;
import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.webpubsub.fluent.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
892,878
public static String getFedoraDatastreamsList(KConfiguration configuration, String pid) { String datastreamsListPath = configuration.getFedoraHost() + "/objects/" + pid + "/datastreams?format=xml"; return datastreamsListPath; }
static String function(KConfiguration configuration, String pid) { String datastreamsListPath = configuration.getFedoraHost() + STR + pid + STR; return datastreamsListPath; }
/** * Returns list of fedora streams * @param configuration KConfiguration configuration object * @param uuid UUID reqested object * @return */
Returns list of fedora streams
getFedoraDatastreamsList
{ "repo_name": "moravianlibrary/kramerius", "path": "common/src/main/java/cz/incad/kramerius/utils/FedoraUtils.java", "license": "gpl-3.0", "size": 10706 }
[ "cz.incad.kramerius.utils.conf.KConfiguration" ]
import cz.incad.kramerius.utils.conf.KConfiguration;
import cz.incad.kramerius.utils.conf.*;
[ "cz.incad.kramerius" ]
cz.incad.kramerius;
945,538
private String getWikiToolPageName(Event event) { String toolName = "Wiki"; Tool tool = toolManager.getCurrentTool(); if (tool != null) { toolName = tool.getTitle(); String toolId = tool.getId(); // sakai.rwiki // get the site id String siteId = getSite(); if (StringUtils.isEmpty(siteId)) { Reference ref = entityManager.newReference(event.getResource()); siteId = getSiteId(ref.getContext()); } if (StringUtils.isNotEmpty(siteId)) { try { Site site = siteService.getSite(siteId); List<SitePage> pages = site.getPages(); for (SitePage p : pages) { Collection<ToolConfiguration> toolConfigurations = p.getTools(new String[] {toolId}); // if tool exists in this page, get the page title if (CollectionUtils.isNotEmpty(toolConfigurations)) { toolName = p.getTitle(); break; } } } catch (IdUnusedException e) { log.error("Site not found while getting wiki name", e); } } } return toolName; }
String function(Event event) { String toolName = "Wiki"; Tool tool = toolManager.getCurrentTool(); if (tool != null) { toolName = tool.getTitle(); String toolId = tool.getId(); String siteId = getSite(); if (StringUtils.isEmpty(siteId)) { Reference ref = entityManager.newReference(event.getResource()); siteId = getSiteId(ref.getContext()); } if (StringUtils.isNotEmpty(siteId)) { try { Site site = siteService.getSite(siteId); List<SitePage> pages = site.getPages(); for (SitePage p : pages) { Collection<ToolConfiguration> toolConfigurations = p.getTools(new String[] {toolId}); if (CollectionUtils.isNotEmpty(toolConfigurations)) { toolName = p.getTitle(); break; } } } catch (IdUnusedException e) { log.error(STR, e); } } } return toolName; }
/** * Get the wiki tool's page name * * @param event Event the event * @return the name of the wiki tool's page */
Get the wiki tool's page name
getWikiToolPageName
{ "repo_name": "OpenCollabZA/sakai", "path": "rwiki/rwiki-impl/impl/src/java/uk/ac/cam/caret/sakai/rwiki/component/service/impl/SiteEmailNotificationRWiki.java", "license": "apache-2.0", "size": 17024 }
[ "java.util.Collection", "java.util.List", "org.apache.commons.collections4.CollectionUtils", "org.apache.commons.lang3.StringUtils", "org.sakaiproject.entity.api.Reference", "org.sakaiproject.event.api.Event", "org.sakaiproject.exception.IdUnusedException", "org.sakaiproject.site.api.Site", "org.sakaiproject.site.api.SitePage", "org.sakaiproject.site.api.ToolConfiguration", "org.sakaiproject.tool.api.Tool" ]
import java.util.Collection; import java.util.List; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.sakaiproject.entity.api.Reference; import org.sakaiproject.event.api.Event; import org.sakaiproject.exception.IdUnusedException; import org.sakaiproject.site.api.Site; import org.sakaiproject.site.api.SitePage; import org.sakaiproject.site.api.ToolConfiguration; import org.sakaiproject.tool.api.Tool;
import java.util.*; import org.apache.commons.collections4.*; import org.apache.commons.lang3.*; import org.sakaiproject.entity.api.*; import org.sakaiproject.event.api.*; import org.sakaiproject.exception.*; import org.sakaiproject.site.api.*; import org.sakaiproject.tool.api.*;
[ "java.util", "org.apache.commons", "org.sakaiproject.entity", "org.sakaiproject.event", "org.sakaiproject.exception", "org.sakaiproject.site", "org.sakaiproject.tool" ]
java.util; org.apache.commons; org.sakaiproject.entity; org.sakaiproject.event; org.sakaiproject.exception; org.sakaiproject.site; org.sakaiproject.tool;
625,872
@Override public int getPeerCount() throws IOException { DataInputStream data = new DataInputStream(new FileInputStream( PEER_FILE_LOCATION)); try { // count our phone in the returned peer count int peers = readPeerCount(data); return peers >= 0 ? peers + 1 : 1; } finally { data.close(); } }
int function() throws IOException { DataInputStream data = new DataInputStream(new FileInputStream( PEER_FILE_LOCATION)); try { int peers = readPeerCount(data); return peers >= 0 ? peers + 1 : 1; } finally { data.close(); } }
/** * Read the file at the path specified at the time of instantiation and * return the number of peers * * @return the number of peers or -1 if the information is stale * * @throws IOException * if any IO operation on the file fails */
Read the file at the path specified at the time of instantiation and return the number of peers
getPeerCount
{ "repo_name": "aiQon/crowdshare", "path": "src/org/servalproject/batman/Batman.java", "license": "gpl-3.0", "size": 5332 }
[ "java.io.DataInputStream", "java.io.FileInputStream", "java.io.IOException" ]
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
537,178
EClass getPlanImport();
EClass getPlanImport();
/** * Returns the meta object for class '{@link com.lowcoupling.lng.plan.plan.PlanImport <em>Import</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>Import</em>'. * @see com.lowcoupling.lng.plan.plan.PlanImport * @generated */
Returns the meta object for class '<code>com.lowcoupling.lng.plan.plan.PlanImport Import</code>'.
getPlanImport
{ "repo_name": "lowcoupling/plan", "path": "com.lowcoupling.lng.plan/src-gen/com/lowcoupling/lng/plan/plan/PlanPackage.java", "license": "epl-1.0", "size": 60425 }
[ "org.eclipse.emf.ecore.EClass" ]
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
1,063,204
return Collections.emptyMap(); }
return Collections.emptyMap(); }
/** * Returns repository types added by this plugin. * * @param env The environment for the local node, which may be used for the local settings and path.repo * * The key of the returned {@link Map} is the type name of the repository and * the value is a factory to construct the {@link Repository} interface. */
Returns repository types added by this plugin
getRepositories
{ "repo_name": "strapdata/elassandra", "path": "server/src/main/java/org/elasticsearch/plugins/RepositoryPlugin.java", "license": "apache-2.0", "size": 2313 }
[ "java.util.Collections" ]
import java.util.Collections;
import java.util.*;
[ "java.util" ]
java.util;
2,730,895
public static HasDeviceType hasDeviceType(@Nonnull Matcher<? super DeviceType> subMatcher) { return new HasDeviceType(subMatcher); }
static HasDeviceType function(@Nonnull Matcher<? super DeviceType> subMatcher) { return new HasDeviceType(subMatcher); }
/** * Provides a matcher that matches if the provided {@code subMatcher} matches the configuration's * device type */
Provides a matcher that matches if the provided subMatcher matches the configuration's device type
hasDeviceType
{ "repo_name": "arifogel/batfish", "path": "projects/batfish-common-protocol/src/test/java/org/batfish/datamodel/matchers/ConfigurationMatchers.java", "license": "apache-2.0", "size": 10497 }
[ "javax.annotation.Nonnull", "org.batfish.datamodel.DeviceType", "org.batfish.datamodel.matchers.ConfigurationMatchersImpl", "org.hamcrest.Matcher" ]
import javax.annotation.Nonnull; import org.batfish.datamodel.DeviceType; import org.batfish.datamodel.matchers.ConfigurationMatchersImpl; import org.hamcrest.Matcher;
import javax.annotation.*; import org.batfish.datamodel.*; import org.batfish.datamodel.matchers.*; import org.hamcrest.*;
[ "javax.annotation", "org.batfish.datamodel", "org.hamcrest" ]
javax.annotation; org.batfish.datamodel; org.hamcrest;
1,991,398
public long getTotalMemoryConsumption() { long totalDataPagesSize = 0L; for (MemoryBlock dataPage : dataPages) { totalDataPagesSize += dataPage.size(); } return totalDataPagesSize + ((longArray != null) ? longArray.memoryBlock().size() : 0L); }
long function() { long totalDataPagesSize = 0L; for (MemoryBlock dataPage : dataPages) { totalDataPagesSize += dataPage.size(); } return totalDataPagesSize + ((longArray != null) ? longArray.memoryBlock().size() : 0L); }
/** * Returns the total amount of memory, in bytes, consumed by this map's managed structures. */
Returns the total amount of memory, in bytes, consumed by this map's managed structures
getTotalMemoryConsumption
{ "repo_name": "chenc10/Spark-PAF", "path": "core/src/main/java/org/apache/spark/unsafe/map/BytesToBytesMap.java", "license": "apache-2.0", "size": 30348 }
[ "org.apache.spark.unsafe.memory.MemoryBlock" ]
import org.apache.spark.unsafe.memory.MemoryBlock;
import org.apache.spark.unsafe.memory.*;
[ "org.apache.spark" ]
org.apache.spark;
2,456,292
public void fireProjectionChanged(Projection p) { projectionSupport.fireProjectionChanged(p); }
void function(Projection p) { projectionSupport.fireProjectionChanged(p); }
/** * Fire the changed projection from the support. */
Fire the changed projection from the support
fireProjectionChanged
{ "repo_name": "d2fn/passage", "path": "src/main/java/com/bbn/openmap/gui/menu/ProjectionMenu.java", "license": "mit", "size": 8119 }
[ "com.bbn.openmap.proj.Projection" ]
import com.bbn.openmap.proj.Projection;
import com.bbn.openmap.proj.*;
[ "com.bbn.openmap" ]
com.bbn.openmap;
1,348,406
void updateManifest(DashManifest newManifest, int periodIndex);
void updateManifest(DashManifest newManifest, int periodIndex);
/** * Updates the manifest. * * @param newManifest The new manifest. */
Updates the manifest
updateManifest
{ "repo_name": "androidx/media", "path": "libraries/exoplayer_dash/src/main/java/androidx/media3/exoplayer/dash/DashChunkSource.java", "license": "apache-2.0", "size": 3736 }
[ "androidx.media3.exoplayer.dash.manifest.DashManifest" ]
import androidx.media3.exoplayer.dash.manifest.DashManifest;
import androidx.media3.exoplayer.dash.manifest.*;
[ "androidx.media3" ]
androidx.media3;
2,017,927
private static int getNumberOfHits(String page, String marker, Pattern pattern) throws IOException { int ind = page.indexOf(marker); if (ind >= 0) { String substring = page.substring(ind, Math.min(ind + 100, page.length())); Matcher m = pattern.matcher(substring); if (m.find()) { try { String number = m.group(1); number = number.replace(",", ""); // Remove , as in 1,234 return Integer.parseInt(number); } catch (NumberFormatException ex) { throw new IOException("Cannot parse number of hits"); } } LOGGER.info("Unmatched! " + substring); } throw new IOException("Cannot parse number of hits"); }
static int function(String page, String marker, Pattern pattern) throws IOException { int ind = page.indexOf(marker); if (ind >= 0) { String substring = page.substring(ind, Math.min(ind + 100, page.length())); Matcher m = pattern.matcher(substring); if (m.find()) { try { String number = m.group(1); number = number.replace(",", STRCannot parse number of hitsSTRUnmatched! STRCannot parse number of hits"); }
/** * Find out how many hits were found. * @param page */
Find out how many hits were found
getNumberOfHits
{ "repo_name": "tobiasdiez/jabref", "path": "src/main/java/org/jabref/gui/importer/fetcher/ACMPortalFetcher.java", "license": "mit", "size": 16990 }
[ "java.io.IOException", "java.util.regex.Matcher", "java.util.regex.Pattern" ]
import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern;
import java.io.*; import java.util.regex.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,277,379
protected void writeStructureToNBT(NBTTagCompound tagCompound) { super.writeStructureToNBT(tagCompound); tagCompound.setInteger("CA", Block.REGISTRY.getIDForObject(this.cropTypeA)); tagCompound.setInteger("CB", Block.REGISTRY.getIDForObject(this.cropTypeB)); tagCompound.setInteger("CC", Block.REGISTRY.getIDForObject(this.cropTypeC)); tagCompound.setInteger("CD", Block.REGISTRY.getIDForObject(this.cropTypeD)); }
void function(NBTTagCompound tagCompound) { super.writeStructureToNBT(tagCompound); tagCompound.setInteger("CA", Block.REGISTRY.getIDForObject(this.cropTypeA)); tagCompound.setInteger("CB", Block.REGISTRY.getIDForObject(this.cropTypeB)); tagCompound.setInteger("CC", Block.REGISTRY.getIDForObject(this.cropTypeC)); tagCompound.setInteger("CD", Block.REGISTRY.getIDForObject(this.cropTypeD)); }
/** * (abstract) Helper method to write subclass data to NBT */
(abstract) Helper method to write subclass data to NBT
writeStructureToNBT
{ "repo_name": "Im-Jrotica/forge_latest", "path": "build/tmp/recompileMc/sources/net/minecraft/world/gen/structure/StructureVillagePieces.java", "license": "lgpl-2.1", "size": 136617 }
[ "net.minecraft.block.Block", "net.minecraft.nbt.NBTTagCompound" ]
import net.minecraft.block.Block; import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.block.*; import net.minecraft.nbt.*;
[ "net.minecraft.block", "net.minecraft.nbt" ]
net.minecraft.block; net.minecraft.nbt;
141,040
@Override public String toString() { return (Integer.toString(m_value)); } private static final ProjectTimeFormat[] TYPE_VALUES = EnumUtility.createTypeArray(ProjectTimeFormat.class); private int m_value;
@Override String function() { return (Integer.toString(m_value)); } private static final ProjectTimeFormat[] TYPE_VALUES = EnumUtility.createTypeArray(ProjectTimeFormat.class); private int m_value;
/** * Returns a string representation of the time format type * to be used as part of an MPX file. * * @return string representation */
Returns a string representation of the time format type to be used as part of an MPX file
toString
{ "repo_name": "tmyroadctfig/mpxj", "path": "net/sf/mpxj/ProjectTimeFormat.java", "license": "lgpl-2.1", "size": 2827 }
[ "net.sf.mpxj.utility.EnumUtility" ]
import net.sf.mpxj.utility.EnumUtility;
import net.sf.mpxj.utility.*;
[ "net.sf.mpxj" ]
net.sf.mpxj;
569,169
public static int intValue(Object o) { if (o == null) { return 0; } if (o instanceof String) { return SNumber.intValue((String) o); } if (o instanceof Number) { return ((Number) o).intValue(); } return SNumber.intValue(o.toString()); }
static int function(Object o) { if (o == null) { return 0; } if (o instanceof String) { return SNumber.intValue((String) o); } if (o instanceof Number) { return ((Number) o).intValue(); } return SNumber.intValue(o.toString()); }
/** * Returns the integer representation of the specified object. String's that * don't start with a numeric sequence always return zero * * @param o * the object * @return the integer representing the object */
Returns the integer representation of the specified object. String's that don't start with a numeric sequence always return zero
intValue
{ "repo_name": "appnativa/rare", "path": "source/rare/core/com/appnativa/rare/scripting/Functions.java", "license": "gpl-3.0", "size": 107843 }
[ "com.appnativa.util.SNumber" ]
import com.appnativa.util.SNumber;
import com.appnativa.util.*;
[ "com.appnativa.util" ]
com.appnativa.util;
2,073,828
private boolean isDenied(AccessControlEntry ace, Set<String> authorisations, Set<Pair<String, PermissionReference>> allowed, PermissionContext context) { // If the permission entry denies then we just deny if (ace.getAccessStatus() == AccessStatus.ALLOWED) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), ace.getPermission())); Set<PermissionReference> granters = modelDAO.getGrantingPermissions(ace.getPermission()); for (PermissionReference granter : granters) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), granter)); } // All the things granted by this permission must be // denied Set<PermissionReference> grantees = modelDAO.getGranteePermissions(ace.getPermission()); for (PermissionReference grantee : grantees) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), grantee)); } // All permission excludes all permissions available for // the node. if (ace.getPermission().equals(getAllPermissionReference()) || ace.getPermission().equals(OLD_ALL_PERMISSIONS_REFERENCE)) { for (PermissionReference deny : modelDAO.getAllPermissions(context.getType(), context.getAspects())) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), deny)); } } return false; } // The permission is denied but we allow it as it is in the allowed // set if (allowed != null) { Pair<String, PermissionReference> specific = new Pair<String, PermissionReference>(ace.getAuthority(), required); if (allowed.contains(specific)) { return false; } } // If the permission has a match in both the authorities and // granters list it is allowed // It applies to the current user and it is granted if (authorisations.contains(ace.getAuthority()) && granters.contains(ace.getPermission())) { { return true; } } // Default allow return false; }
boolean function(AccessControlEntry ace, Set<String> authorisations, Set<Pair<String, PermissionReference>> allowed, PermissionContext context) { if (ace.getAccessStatus() == AccessStatus.ALLOWED) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), ace.getPermission())); Set<PermissionReference> granters = modelDAO.getGrantingPermissions(ace.getPermission()); for (PermissionReference granter : granters) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), granter)); } Set<PermissionReference> grantees = modelDAO.getGranteePermissions(ace.getPermission()); for (PermissionReference grantee : grantees) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), grantee)); } if (ace.getPermission().equals(getAllPermissionReference()) ace.getPermission().equals(OLD_ALL_PERMISSIONS_REFERENCE)) { for (PermissionReference deny : modelDAO.getAllPermissions(context.getType(), context.getAspects())) { allowed.add(new Pair<String, PermissionReference>(ace.getAuthority(), deny)); } } return false; } if (allowed != null) { Pair<String, PermissionReference> specific = new Pair<String, PermissionReference>(ace.getAuthority(), required); if (allowed.contains(specific)) { return false; } } if (authorisations.contains(ace.getAuthority()) && granters.contains(ace.getPermission())) { { return true; } } return false; }
/** * Is a permission granted * * @param ace AccessControlEntry * @param authorisations - * the set of authorities * @param allowed - * the set of denied permissions/authority pais * @param context PermissionContext * @return true if granted */
Is a permission granted
isDenied
{ "repo_name": "Kast0rTr0y/community-edition", "path": "projects/repository/source/java/org/alfresco/repo/security/permissions/impl/PermissionServiceImpl.java", "license": "lgpl-3.0", "size": 102917 }
[ "java.util.Set", "org.alfresco.repo.security.permissions.AccessControlEntry", "org.alfresco.repo.security.permissions.PermissionReference", "org.alfresco.service.cmr.security.AccessStatus", "org.alfresco.service.cmr.security.PermissionContext", "org.alfresco.util.Pair" ]
import java.util.Set; import org.alfresco.repo.security.permissions.AccessControlEntry; import org.alfresco.repo.security.permissions.PermissionReference; import org.alfresco.service.cmr.security.AccessStatus; import org.alfresco.service.cmr.security.PermissionContext; import org.alfresco.util.Pair;
import java.util.*; import org.alfresco.repo.security.permissions.*; import org.alfresco.service.cmr.security.*; import org.alfresco.util.*;
[ "java.util", "org.alfresco.repo", "org.alfresco.service", "org.alfresco.util" ]
java.util; org.alfresco.repo; org.alfresco.service; org.alfresco.util;
1,992,526
public void run() { try { active = true; HTTPProxyHost = System.getProperty("http.proxyHost"); if ((HTTPProxyHost != null) && HTTPProxyHost.equals("")) { HTTPProxyHost = null; } if (HTTPProxyHost != null) { String tmp = System.getProperty("http.proxyPort"); if ((tmp != null) && tmp.equals("")) { tmp = null; } if (tmp == null) { HTTPProxyPort = 80; } else { HTTPProxyPort = Integer.parseInt(tmp); } } if (inSocket != null) { fromHost = (inSocket.getInetAddress()).getHostName(); } else { fromHost = "resend"; } String dateformat = TCPMon.getMessage("dateformat00", "yyyy-MM-dd HH:mm:ss"); DateFormat df = new SimpleDateFormat(dateformat); time = df.format(new Date()); int count = listener.connections.size(); listener.tableModel.insertRow(count + 1, new Object[]{ TCPMon.getMessage("active00","Active"), time, fromHost, listener.hostField.getText(), ""}); listener.connections.add(this); inputText = new JTextArea(null, null, 20, 80); inputScroll = new JScrollPane(inputText); outputText = new JTextArea(null, null, 20, 80); outputScroll = new JScrollPane(outputText); ListSelectionModel lsm = listener.connectionTable.getSelectionModel(); if ((count == 0) || (lsm.getLeadSelectionIndex() == 0)) { listener.outPane.setVisible(false); int divLoc = listener.outPane.getDividerLocation(); listener.setLeft(inputScroll); listener.setRight(outputScroll); listener.removeButton.setEnabled(false); listener.removeAllButton.setEnabled(true); listener.saveButton.setEnabled(true); listener.resendButton.setEnabled(true); listener.outPane.setDividerLocation(divLoc); listener.outPane.setVisible(true); } String targetHost = listener.hostField.getText(); int targetPort = Integer.parseInt(listener.tPortField.getText()); int listenPort = Integer.parseInt(listener.portField.getText()); InputStream tmpIn1 = inputStream; OutputStream tmpOut1 = null; InputStream tmpIn2 = null; OutputStream tmpOut2 = null; if (tmpIn1 == null) { tmpIn1 = inSocket.getInputStream(); } if (inSocket != null) { tmpOut1 = inSocket.getOutputStream(); } String bufferedData = null; StringBuffer buf = null; int index = listener.connections.indexOf(this); if (listener.isProxyBox.isSelected() || (HTTPProxyHost != null)) { // Check if we're a proxy byte[] b = new byte[1]; buf = new StringBuffer(); String s; for (; ;) { int len; len = tmpIn1.read(b, 0, 1); if (len == -1) { break; } s = new String(b); buf.append(s); if (b[0] != '\n') { continue; } break; } bufferedData = buf.toString(); inputText.append(bufferedData); if (bufferedData.startsWith("GET ") || bufferedData.startsWith("POST ") || bufferedData.startsWith("PUT ") || bufferedData.startsWith("DELETE ")) { int start, end; URL url; start = bufferedData.indexOf(' ') + 1; while (bufferedData.charAt(start) == ' ') { start++; } end = bufferedData.indexOf(' ', start); String urlString = bufferedData.substring(start, end); if (urlString.charAt(0) == '/') { urlString = urlString.substring(1); } if (listener.isProxyBox.isSelected()) { url = new URL(urlString); targetHost = url.getHost(); targetPort = url.getPort(); if (targetPort == -1) { targetPort = 80; } listener.tableModel.setValueAt(targetHost, index + 1, TCPMon.OUTHOST_COLUMN); bufferedData = bufferedData.substring(0, start) + url.getFile() + bufferedData.substring(end); } else { url = new URL("http://" + targetHost + ":" + targetPort + "/" + urlString); listener.tableModel.setValueAt(targetHost, index + 1, TCPMon.OUTHOST_COLUMN); bufferedData = bufferedData.substring(0, start) + url.toExternalForm() + bufferedData.substring(end); targetHost = HTTPProxyHost; targetPort = HTTPProxyPort; } } } else { // // Change Host: header to point to correct host // byte[] b1 = new byte[1]; buf = new StringBuffer(); String s1; String lastLine = null; for (; ;) { int len; len = tmpIn1.read(b1, 0, 1); if (len == -1) { break; } s1 = new String(b1); buf.append(s1); if (b1[0] != '\n') { continue; } // we have a complete line String line = buf.toString(); buf.setLength(0); // check to see if we have found Host: header if (line.startsWith("Host: ")) { // we need to update the hostname to target host String newHost = "Host: " + targetHost + ":" + targetPort + "\r\n"; bufferedData = bufferedData.concat(newHost); break; } // add it to our headers so far if (bufferedData == null) { bufferedData = line; } else { bufferedData = bufferedData.concat(line); } // failsafe if (line.equals("\r\n")) { break; } if ("\n".equals(lastLine) && line.equals("\n")) { break; } lastLine = line; } if (bufferedData != null) { inputText.append(bufferedData); int idx = (bufferedData.length() < 50) ? bufferedData.length() : 50; s1 = bufferedData.substring(0, idx); int i = s1.indexOf('\n'); if (i > 0) { s1 = s1.substring(0, i - 1); } s1 = s1 + " " + " "; s1 = s1.substring(0, 51); listener.tableModel.setValueAt(s1, index + 1, TCPMon.REQ_COLUMN); } } if (targetPort == -1) { targetPort = 80; } outSocket = new Socket(targetHost, targetPort); tmpIn2 = outSocket.getInputStream(); tmpOut2 = outSocket.getOutputStream(); if (bufferedData != null) { byte[] b = bufferedData.getBytes(); tmpOut2.write(b); slowLink.pump(b.length); } boolean format = listener.xmlFormatBox.isSelected(); // this is the channel to the endpoint rr1 = new SocketRR(this, inSocket, tmpIn1, outSocket, tmpOut2, inputText, format, listener.tableModel, index + 1, "request:", slowLink); // create the response slow link from the inbound slow link SlowLinkSimulator responseLink = new SlowLinkSimulator(slowLink); // this is the channel from the endpoint rr2 = new SocketRR(this, outSocket, tmpIn2, inSocket, tmpOut1, outputText, format, null, 0, "response:", responseLink); while ((rr1 != null) || (rr2 != null)) { if (rr2 != null) { listener.tableModel.setValueAt(rr2.getElapsed(), 1 + index, TCPMon.ELAPSED_COLUMN); } // Only loop as long as the connection to the target // machine is available - once that's gone we can stop. // The old way, loop until both are closed, left us // looping forever since no one closed the 1st one. if ((null != rr1) && rr1.isDone()) { if ((index >= 0) && (rr2 != null)) { listener.tableModel.setValueAt( TCPMon.getMessage("resp00", "Resp"), 1 + index, TCPMon.STATE_COLUMN); } rr1 = null; } if ((null != rr2) && rr2.isDone()) { if ((index >= 0) && (rr1 != null)) { listener.tableModel.setValueAt( TCPMon.getMessage("req00", "Req"), 1 + index, TCPMon.STATE_COLUMN); } rr2 = null; } synchronized (this) { this.wait(100); // Safety just incase we're not told to wake up. } } active = false; if (index >= 0) { listener.tableModel.setValueAt( TCPMon.getMessage("done00", "Done"), 1 + index, TCPMon.STATE_COLUMN); } } catch (Exception e) { StringWriter st = new StringWriter(); PrintWriter wr = new PrintWriter(st); int index = listener.connections.indexOf(this); if (index >= 0) { listener.tableModel.setValueAt( TCPMon.getMessage("error00", "Error"), 1 + index, TCPMon.STATE_COLUMN); } e.printStackTrace(wr); wr.close(); if (outputText != null) { outputText.append(st.toString()); } else { // something went wrong before we had the output area System.out.println(st.toString()); } halt(); } }
void function() { try { active = true; HTTPProxyHost = System.getProperty(STR); if ((HTTPProxyHost != null) && HTTPProxyHost.equals(STRhttp.proxyPortSTRSTRresendSTRdateformat00STRyyyy-MM-dd HH:mm:ssSTRactive00","ActiveSTRSTRGET STRPOST STRPUT STRDELETE STRhttp: + targetPort + "/" + urlString); listener.tableModel.setValueAt(targetHost, index + 1, TCPMon.OUTHOST_COLUMN); bufferedData = bufferedData.substring(0, start) + url.toExternalForm() + bufferedData.substring(end); targetHost = HTTPProxyHost; targetPort = HTTPProxyPort; } } } else { byte[] b1 = new byte[1]; buf = new StringBuffer(); String s1; String lastLine = null; for (; ;) { int len; len = tmpIn1.read(b1, 0, 1); if (len == -1) { break; } s1 = new String(b1); buf.append(s1); if (b1[0] != '\n') { continue; } String line = buf.toString(); buf.setLength(0); if (line.startsWith(STR)) { String newHost = STR + targetHost + ":" + targetPort + "\r\n"; bufferedData = bufferedData.concat(newHost); break; } if (bufferedData == null) { bufferedData = line; } else { bufferedData = bufferedData.concat(line); } if (line.equals("\r\n")) { break; } if ("\n".equals(lastLine) && line.equals("\n")) { break; } lastLine = line; } if (bufferedData != null) { inputText.append(bufferedData); int idx = (bufferedData.length() < 50) ? bufferedData.length() : 50; s1 = bufferedData.substring(0, idx); int i = s1.indexOf('\n'); if (i > 0) { s1 = s1.substring(0, i - 1); } s1 = s1 + " " + " "; s1 = s1.substring(0, 51); listener.tableModel.setValueAt(s1, index + 1, TCPMon.REQ_COLUMN); } } if (targetPort == -1) { targetPort = 80; } outSocket = new Socket(targetHost, targetPort); tmpIn2 = outSocket.getInputStream(); tmpOut2 = outSocket.getOutputStream(); if (bufferedData != null) { byte[] b = bufferedData.getBytes(); tmpOut2.write(b); slowLink.pump(b.length); } boolean format = listener.xmlFormatBox.isSelected(); rr1 = new SocketRR(this, inSocket, tmpIn1, outSocket, tmpOut2, inputText, format, listener.tableModel, index + 1, STR, slowLink); SlowLinkSimulator responseLink = new SlowLinkSimulator(slowLink); rr2 = new SocketRR(this, outSocket, tmpIn2, inSocket, tmpOut1, outputText, format, null, 0, STR, responseLink); while ((rr1 != null) (rr2 != null)) { if (rr2 != null) { listener.tableModel.setValueAt(rr2.getElapsed(), 1 + index, TCPMon.ELAPSED_COLUMN); } if ((null != rr1) && rr1.isDone()) { if ((index >= 0) && (rr2 != null)) { listener.tableModel.setValueAt( TCPMon.getMessage("resp00STRResp"), 1 + index, TCPMon.STATE_COLUMN); } rr1 = null; } if ((null != rr2) && rr2.isDone()) { if ((index >= 0) && (rr1 != null)) { listener.tableModel.setValueAt( TCPMon.getMessage("req00STRReq"), 1 + index, TCPMon.STATE_COLUMN); } rr2 = null; } synchronized (this) { this.wait(100); } } active = false; if (index >= 0) { listener.tableModel.setValueAt( TCPMon.getMessage("done00STRDone"), 1 + index, TCPMon.STATE_COLUMN); } } catch (Exception e) { StringWriter st = new StringWriter(); PrintWriter wr = new PrintWriter(st); int index = listener.connections.indexOf(this); if (index >= 0) { listener.tableModel.setValueAt( TCPMon.getMessage("error00STRError"), 1 + index, TCPMon.STATE_COLUMN); } e.printStackTrace(wr); wr.close(); if (outputText != null) { outputText.append(st.toString()); } else { System.out.println(st.toString()); } halt(); } }
/** * Method run */
Method run
run
{ "repo_name": "robertbachmann/tcpmon", "path": "src/org/apache/ws/commons/tcpmon/Connection.java", "license": "apache-2.0", "size": 16110 }
[ "java.io.PrintWriter", "java.io.StringWriter", "java.net.Socket" ]
import java.io.PrintWriter; import java.io.StringWriter; import java.net.Socket;
import java.io.*; import java.net.*;
[ "java.io", "java.net" ]
java.io; java.net;
243,965
public static MethodBinding computeCompatibleMethod(MethodBinding originalMethod, TypeBinding[] arguments, Scope scope, InvocationSite invocationSite) { LookupEnvironment environment = scope.environment(); if(environment.globalOptions.isAnnotationBasedNullAnalysisEnabled) { ImplicitNullAnnotationVerifier.ensureNullnessIsKnown(originalMethod, scope); } ParameterizedGenericMethodBinding methodSubstitute; TypeVariableBinding[] typeVariables = originalMethod.typeVariables; TypeBinding[] substitutes = invocationSite.genericTypeArguments(); InferenceContext inferenceContext = null; TypeBinding[] uncheckedArguments = null; computeSubstitutes: { if (substitutes != null) { // explicit type arguments got supplied if (substitutes.length != typeVariables.length) { // incompatible due to wrong arity return new ProblemMethodBinding(originalMethod, originalMethod.selector, substitutes, ProblemReasons.TypeParameterArityMismatch); } methodSubstitute = environment.createParameterizedGenericMethod(originalMethod, substitutes); break computeSubstitutes; } // perform type argument inference (15.12.2.7) // initializes the map of substitutes (var --> type[][]{ equal, extends, super} TypeBinding[] parameters = originalMethod.parameters; CompilerOptions compilerOptions = scope.compilerOptions(); if (compilerOptions.sourceLevel >= ClassFileConstants.JDK1_8) return computeCompatibleMethod18(originalMethod, arguments, scope, invocationSite); // 1.7- only. inferenceContext = new InferenceContext(originalMethod); methodSubstitute = inferFromArgumentTypes(scope, originalMethod, arguments, parameters, inferenceContext); if (methodSubstitute == null) return null; // substitutes may hold null to denote unresolved vars, but null arguments got replaced with respective original variable in param method // 15.12.2.8 - inferring unresolved type arguments if (inferenceContext.hasUnresolvedTypeArgument()) { if (inferenceContext.isUnchecked) { // only remember unchecked status post 15.12.2.7 int length = inferenceContext.substitutes.length; System.arraycopy(inferenceContext.substitutes, 0, uncheckedArguments = new TypeBinding[length], 0, length); } if (methodSubstitute.returnType != TypeBinding.VOID) { TypeBinding expectedType = invocationSite.invocationTargetType(); if (expectedType != null) { // record it was explicit from context, as opposed to assumed by default (see below) inferenceContext.hasExplicitExpectedType = true; } else { expectedType = scope.getJavaLangObject(); // assume Object by default } inferenceContext.expectedType = expectedType; } methodSubstitute = methodSubstitute.inferFromExpectedType(scope, inferenceContext); if (methodSubstitute == null) return null; } else if (compilerOptions.sourceLevel == ClassFileConstants.JDK1_7) { // bug 425203 - consider additional constraints to conform to buggy javac behavior if (methodSubstitute.returnType != TypeBinding.VOID) { TypeBinding expectedType = invocationSite.invocationTargetType(); // In case of a method like <T> List<T> foo(T arg), solution based on return type // should not be preferred vs solution based on parameter types, so do not attempt // to use return type based inference in this case if (expectedType != null && !originalMethod.returnType.mentionsAny(originalMethod.parameters, -1)) { TypeBinding uncaptured = methodSubstitute.returnType.uncapture(scope); if (!methodSubstitute.returnType.isCompatibleWith(expectedType) && expectedType.isCompatibleWith(uncaptured)) { InferenceContext oldContext = inferenceContext; inferenceContext = new InferenceContext(originalMethod); // Include additional constraint pertaining to the expected type originalMethod.returnType.collectSubstitutes(scope, expectedType, inferenceContext, TypeConstants.CONSTRAINT_EXTENDS); ParameterizedGenericMethodBinding substitute = inferFromArgumentTypes(scope, originalMethod, arguments, parameters, inferenceContext); if (substitute != null && substitute.returnType.isCompatibleWith(expectedType)) { // Do not use the new solution if it results in incompatibilities in parameter types if ((scope.parameterCompatibilityLevel(substitute, arguments, false)) > Scope.NOT_COMPATIBLE) { methodSubstitute = substitute; } else { inferenceContext = oldContext; } } else { inferenceContext = oldContext; } } } } } } Substitution substitution = null; if (inferenceContext != null) { substitution = new LingeringTypeVariableEliminator(typeVariables, inferenceContext.substitutes, scope); } else { substitution = methodSubstitute; } for (int i = 0, length = typeVariables.length; i < length; i++) { TypeVariableBinding typeVariable = typeVariables[i]; TypeBinding substitute = methodSubstitute.typeArguments[i]; // retain for diagnostics TypeBinding substituteForChecks; if (substitute instanceof TypeVariableBinding) { substituteForChecks = substitute; } else { substituteForChecks = Scope.substitute(new LingeringTypeVariableEliminator(typeVariables, null, scope), substitute); // while using this for bounds check } if (uncheckedArguments != null && uncheckedArguments[i] == null) continue; // only bound check if inferred through 15.12.2.6 switch (typeVariable.boundCheck(substitution, substituteForChecks, scope, null)) { case MISMATCH : // incompatible due to bound check int argLength = arguments.length; TypeBinding[] augmentedArguments = new TypeBinding[argLength + 2]; // append offending substitute and typeVariable System.arraycopy(arguments, 0, augmentedArguments, 0, argLength); augmentedArguments[argLength] = substitute; augmentedArguments[argLength+1] = typeVariable; return new ProblemMethodBinding(methodSubstitute, originalMethod.selector, augmentedArguments, ProblemReasons.ParameterBoundMismatch); case UNCHECKED : // tolerate unchecked bounds methodSubstitute.tagBits |= TagBits.HasUncheckedTypeArgumentForBoundCheck; break; default: break; } } // check presence of unchecked argument conversion a posteriori (15.12.2.6) return methodSubstitute; }
static MethodBinding function(MethodBinding originalMethod, TypeBinding[] arguments, Scope scope, InvocationSite invocationSite) { LookupEnvironment environment = scope.environment(); if(environment.globalOptions.isAnnotationBasedNullAnalysisEnabled) { ImplicitNullAnnotationVerifier.ensureNullnessIsKnown(originalMethod, scope); } ParameterizedGenericMethodBinding methodSubstitute; TypeVariableBinding[] typeVariables = originalMethod.typeVariables; TypeBinding[] substitutes = invocationSite.genericTypeArguments(); InferenceContext inferenceContext = null; TypeBinding[] uncheckedArguments = null; computeSubstitutes: { if (substitutes != null) { if (substitutes.length != typeVariables.length) { return new ProblemMethodBinding(originalMethod, originalMethod.selector, substitutes, ProblemReasons.TypeParameterArityMismatch); } methodSubstitute = environment.createParameterizedGenericMethod(originalMethod, substitutes); break computeSubstitutes; } TypeBinding[] parameters = originalMethod.parameters; CompilerOptions compilerOptions = scope.compilerOptions(); if (compilerOptions.sourceLevel >= ClassFileConstants.JDK1_8) return computeCompatibleMethod18(originalMethod, arguments, scope, invocationSite); inferenceContext = new InferenceContext(originalMethod); methodSubstitute = inferFromArgumentTypes(scope, originalMethod, arguments, parameters, inferenceContext); if (methodSubstitute == null) return null; if (inferenceContext.hasUnresolvedTypeArgument()) { if (inferenceContext.isUnchecked) { int length = inferenceContext.substitutes.length; System.arraycopy(inferenceContext.substitutes, 0, uncheckedArguments = new TypeBinding[length], 0, length); } if (methodSubstitute.returnType != TypeBinding.VOID) { TypeBinding expectedType = invocationSite.invocationTargetType(); if (expectedType != null) { inferenceContext.hasExplicitExpectedType = true; } else { expectedType = scope.getJavaLangObject(); } inferenceContext.expectedType = expectedType; } methodSubstitute = methodSubstitute.inferFromExpectedType(scope, inferenceContext); if (methodSubstitute == null) return null; } else if (compilerOptions.sourceLevel == ClassFileConstants.JDK1_7) { if (methodSubstitute.returnType != TypeBinding.VOID) { TypeBinding expectedType = invocationSite.invocationTargetType(); if (expectedType != null && !originalMethod.returnType.mentionsAny(originalMethod.parameters, -1)) { TypeBinding uncaptured = methodSubstitute.returnType.uncapture(scope); if (!methodSubstitute.returnType.isCompatibleWith(expectedType) && expectedType.isCompatibleWith(uncaptured)) { InferenceContext oldContext = inferenceContext; inferenceContext = new InferenceContext(originalMethod); originalMethod.returnType.collectSubstitutes(scope, expectedType, inferenceContext, TypeConstants.CONSTRAINT_EXTENDS); ParameterizedGenericMethodBinding substitute = inferFromArgumentTypes(scope, originalMethod, arguments, parameters, inferenceContext); if (substitute != null && substitute.returnType.isCompatibleWith(expectedType)) { if ((scope.parameterCompatibilityLevel(substitute, arguments, false)) > Scope.NOT_COMPATIBLE) { methodSubstitute = substitute; } else { inferenceContext = oldContext; } } else { inferenceContext = oldContext; } } } } } } Substitution substitution = null; if (inferenceContext != null) { substitution = new LingeringTypeVariableEliminator(typeVariables, inferenceContext.substitutes, scope); } else { substitution = methodSubstitute; } for (int i = 0, length = typeVariables.length; i < length; i++) { TypeVariableBinding typeVariable = typeVariables[i]; TypeBinding substitute = methodSubstitute.typeArguments[i]; TypeBinding substituteForChecks; if (substitute instanceof TypeVariableBinding) { substituteForChecks = substitute; } else { substituteForChecks = Scope.substitute(new LingeringTypeVariableEliminator(typeVariables, null, scope), substitute); } if (uncheckedArguments != null && uncheckedArguments[i] == null) continue; switch (typeVariable.boundCheck(substitution, substituteForChecks, scope, null)) { case MISMATCH : int argLength = arguments.length; TypeBinding[] augmentedArguments = new TypeBinding[argLength + 2]; System.arraycopy(arguments, 0, augmentedArguments, 0, argLength); augmentedArguments[argLength] = substitute; augmentedArguments[argLength+1] = typeVariable; return new ProblemMethodBinding(methodSubstitute, originalMethod.selector, augmentedArguments, ProblemReasons.ParameterBoundMismatch); case UNCHECKED : methodSubstitute.tagBits = TagBits.HasUncheckedTypeArgumentForBoundCheck; break; default: break; } } return methodSubstitute; }
/** * Perform inference of generic method type parameters and/or expected type * <p> * In 1.8+ if the expected type is not yet available due to this call being an argument to an outer call which is not overload-resolved yet, * the returned method binding will be a PolyParameterizedGenericMethodBinding. * </p> */
Perform inference of generic method type parameters and/or expected type In 1.8+ if the expected type is not yet available due to this call being an argument to an outer call which is not overload-resolved yet, the returned method binding will be a PolyParameterizedGenericMethodBinding.
computeCompatibleMethod
{ "repo_name": "Niky4000/UsefulUtils", "path": "projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/ParameterizedGenericMethodBinding.java", "license": "gpl-3.0", "size": 43691 }
[ "org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants", "org.eclipse.jdt.internal.compiler.impl.CompilerOptions" ]
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.classfmt.*; import org.eclipse.jdt.internal.compiler.impl.*;
[ "org.eclipse.jdt" ]
org.eclipse.jdt;
390,564
public int read (byte[] bytes, int offset, int count) throws KryoException { niobuffer.position(position); if (bytes == null) throw new IllegalArgumentException("bytes cannot be null."); int startingCount = count; int copyCount = Math.min(limit - position, count); while (true) { niobuffer.get(bytes, offset, copyCount); position += copyCount; count -= copyCount; if (count == 0) break; offset += copyCount; copyCount = optional(count); if (copyCount == -1) { // End of data. if (startingCount == count) return -1; break; } if (position == limit) break; } return startingCount - count; }
int function (byte[] bytes, int offset, int count) throws KryoException { niobuffer.position(position); if (bytes == null) throw new IllegalArgumentException(STR); int startingCount = count; int copyCount = Math.min(limit - position, count); while (true) { niobuffer.get(bytes, offset, copyCount); position += copyCount; count -= copyCount; if (count == 0) break; offset += copyCount; copyCount = optional(count); if (copyCount == -1) { if (startingCount == count) return -1; break; } if (position == limit) break; } return startingCount - count; }
/** Reads count bytes or less and writes them to the specified byte[], starting at offset, and returns the number of bytes read * or -1 if no more bytes are available. */
Reads count bytes or less and writes them to the specified byte[], starting at offset, and returns the number of bytes read
read
{ "repo_name": "xfrendx/kryo", "path": "src/com/esotericsoftware/kryo/io/ByteBufferInput.java", "license": "bsd-3-clause", "size": 29966 }
[ "com.esotericsoftware.kryo.KryoException" ]
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.*;
[ "com.esotericsoftware.kryo" ]
com.esotericsoftware.kryo;
2,335,015
public static int getYear(final Date date) { return getNumberOfGranularity(Calendar.YEAR, date); }
static int function(final Date date) { return getNumberOfGranularity(Calendar.YEAR, date); }
/** * Get the year by given date. * * @param date date to be handled. * @return the year by given date. */
Get the year by given date
getYear
{ "repo_name": "defei/codelogger-utils", "path": "src/main/java/org/codelogger/utils/DateUtils.java", "license": "apache-2.0", "size": 18800 }
[ "java.util.Calendar", "java.util.Date" ]
import java.util.Calendar; import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
1,096,302
@Deprecated @SuppressWarnings("deprecation") public void restore(StreamStateHandle snapshot) throws Exception { if (operator instanceof StreamCheckpointedOperator) { try (FSDataInputStream in = snapshot.openInputStream()) { ((StreamCheckpointedOperator) operator).restoreState(in); } } else { throw new RuntimeException("Operator is not StreamCheckpointedOperator"); } }
@SuppressWarnings(STR) void function(StreamStateHandle snapshot) throws Exception { if (operator instanceof StreamCheckpointedOperator) { try (FSDataInputStream in = snapshot.openInputStream()) { ((StreamCheckpointedOperator) operator).restoreState(in); } } else { throw new RuntimeException(STR); } }
/** * Calls {@link StreamCheckpointedOperator#restoreState(FSDataInputStream)} if * the operator implements this interface. */
Calls <code>StreamCheckpointedOperator#restoreState(FSDataInputStream)</code> if the operator implements this interface
restore
{ "repo_name": "Xpray/flink", "path": "flink-streaming-java/src/test/java/org/apache/flink/streaming/util/AbstractStreamOperatorTestHarness.java", "license": "apache-2.0", "size": 24250 }
[ "org.apache.flink.core.fs.FSDataInputStream", "org.apache.flink.runtime.state.StreamStateHandle", "org.apache.flink.streaming.api.operators.StreamCheckpointedOperator" ]
import org.apache.flink.core.fs.FSDataInputStream; import org.apache.flink.runtime.state.StreamStateHandle; import org.apache.flink.streaming.api.operators.StreamCheckpointedOperator;
import org.apache.flink.core.fs.*; import org.apache.flink.runtime.state.*; import org.apache.flink.streaming.api.operators.*;
[ "org.apache.flink" ]
org.apache.flink;
1,840,953
public ShardDeletionCheckResult canDeleteShardContent(ShardId shardId, IndexSettings indexSettings) { assert shardId.getIndex().equals(indexSettings.getIndex()); final IndexService indexService = indexService(shardId.getIndex()); if (nodeEnv.hasNodeFile()) { final boolean isAllocated = indexService != null && indexService.hasShard(shardId.id()); if (isAllocated) { return ShardDeletionCheckResult.STILL_ALLOCATED; // we are allocated - can't delete the shard } else if (indexSettings.hasCustomDataPath()) { // lets see if it's on a custom path (return false if the shared doesn't exist) // we don't need to delete anything that is not there return Files.exists(nodeEnv.resolveCustomLocation(indexSettings, shardId)) ? ShardDeletionCheckResult.FOLDER_FOUND_CAN_DELETE : ShardDeletionCheckResult.NO_FOLDER_FOUND; } else { // lets see if it's path is available (return false if the shared doesn't exist) // we don't need to delete anything that is not there return FileSystemUtils.exists(nodeEnv.availableShardPaths(shardId)) ? ShardDeletionCheckResult.FOLDER_FOUND_CAN_DELETE : ShardDeletionCheckResult.NO_FOLDER_FOUND; } } else { return ShardDeletionCheckResult.NO_LOCAL_STORAGE; } }
ShardDeletionCheckResult function(ShardId shardId, IndexSettings indexSettings) { assert shardId.getIndex().equals(indexSettings.getIndex()); final IndexService indexService = indexService(shardId.getIndex()); if (nodeEnv.hasNodeFile()) { final boolean isAllocated = indexService != null && indexService.hasShard(shardId.id()); if (isAllocated) { return ShardDeletionCheckResult.STILL_ALLOCATED; } else if (indexSettings.hasCustomDataPath()) { return Files.exists(nodeEnv.resolveCustomLocation(indexSettings, shardId)) ? ShardDeletionCheckResult.FOLDER_FOUND_CAN_DELETE : ShardDeletionCheckResult.NO_FOLDER_FOUND; } else { return FileSystemUtils.exists(nodeEnv.availableShardPaths(shardId)) ? ShardDeletionCheckResult.FOLDER_FOUND_CAN_DELETE : ShardDeletionCheckResult.NO_FOLDER_FOUND; } } else { return ShardDeletionCheckResult.NO_LOCAL_STORAGE; } }
/** * Returns <code>ShardDeletionCheckResult</code> signaling whether the shards content for the given shard can be deleted. * * @param shardId the shard to delete. * @param indexSettings the shards's relevant {@link IndexSettings}. This is required to access the indexes settings etc. */
Returns <code>ShardDeletionCheckResult</code> signaling whether the shards content for the given shard can be deleted
canDeleteShardContent
{ "repo_name": "pozhidaevak/elasticsearch", "path": "core/src/main/java/org/elasticsearch/indices/IndicesService.java", "license": "apache-2.0", "size": 63125 }
[ "java.nio.file.Files", "org.elasticsearch.common.io.FileSystemUtils", "org.elasticsearch.index.IndexService", "org.elasticsearch.index.IndexSettings", "org.elasticsearch.index.shard.ShardId" ]
import java.nio.file.Files; import org.elasticsearch.common.io.FileSystemUtils; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.shard.ShardId;
import java.nio.file.*; import org.elasticsearch.common.io.*; import org.elasticsearch.index.*; import org.elasticsearch.index.shard.*;
[ "java.nio", "org.elasticsearch.common", "org.elasticsearch.index" ]
java.nio; org.elasticsearch.common; org.elasticsearch.index;
2,488,706
public SqlLiteral unescapeUnicode(char unicodeEscapeChar) { if (unicodeEscapeChar == 0) { return this; } assert SqlTypeUtil.inCharFamily(getTypeName()); NlsString ns = (NlsString) value; String s = ns.getValue(); StringBuilder sb = new StringBuilder(); int n = s.length(); for (int i = 0; i < n; ++i) { char c = s.charAt(i); if (c == unicodeEscapeChar) { if (n > (i + 1)) { if (s.charAt(i + 1) == unicodeEscapeChar) { sb.append(unicodeEscapeChar); ++i; continue; } } if ((i + 5) > n) { throw SqlUtil.newContextException(getParserPosition(), RESOURCE.unicodeEscapeMalformed(i)); } final String u = s.substring(i + 1, i + 5); final int v; try { v = Integer.parseInt(u, 16); } catch (NumberFormatException ex) { throw SqlUtil.newContextException(getParserPosition(), RESOURCE.unicodeEscapeMalformed(i)); } sb.append((char) (v & 0xFFFF)); // skip hexits i += 4; } else { sb.append(c); } } ns = new NlsString( sb.toString(), ns.getCharsetName(), ns.getCollation()); return new SqlCharStringLiteral(ns, getParserPosition()); } //~ Inner Interfaces -------------------------------------------------------
SqlLiteral function(char unicodeEscapeChar) { if (unicodeEscapeChar == 0) { return this; } assert SqlTypeUtil.inCharFamily(getTypeName()); NlsString ns = (NlsString) value; String s = ns.getValue(); StringBuilder sb = new StringBuilder(); int n = s.length(); for (int i = 0; i < n; ++i) { char c = s.charAt(i); if (c == unicodeEscapeChar) { if (n > (i + 1)) { if (s.charAt(i + 1) == unicodeEscapeChar) { sb.append(unicodeEscapeChar); ++i; continue; } } if ((i + 5) > n) { throw SqlUtil.newContextException(getParserPosition(), RESOURCE.unicodeEscapeMalformed(i)); } final String u = s.substring(i + 1, i + 5); final int v; try { v = Integer.parseInt(u, 16); } catch (NumberFormatException ex) { throw SqlUtil.newContextException(getParserPosition(), RESOURCE.unicodeEscapeMalformed(i)); } sb.append((char) (v & 0xFFFF)); i += 4; } else { sb.append(c); } } ns = new NlsString( sb.toString(), ns.getCharsetName(), ns.getCollation()); return new SqlCharStringLiteral(ns, getParserPosition()); }
/** * Transforms this literal (which must be of type character) into a new one * in which 4-digit Unicode escape sequences have been replaced with the * corresponding Unicode characters. * * @param unicodeEscapeChar escape character (e.g. backslash) for Unicode * numeric sequences; 0 implies no transformation * @return transformed literal */
Transforms this literal (which must be of type character) into a new one in which 4-digit Unicode escape sequences have been replaced with the corresponding Unicode characters
unescapeUnicode
{ "repo_name": "yeongwei/incubator-calcite", "path": "core/src/main/java/org/apache/calcite/sql/SqlLiteral.java", "license": "apache-2.0", "size": 27925 }
[ "org.apache.calcite.sql.type.SqlTypeUtil", "org.apache.calcite.util.NlsString", "org.apache.calcite.util.Static" ]
import org.apache.calcite.sql.type.SqlTypeUtil; import org.apache.calcite.util.NlsString; import org.apache.calcite.util.Static;
import org.apache.calcite.sql.type.*; import org.apache.calcite.util.*;
[ "org.apache.calcite" ]
org.apache.calcite;
2,541,282
public static IterableInAppFragmentHTMLNotification getInstance() { return notification; } public IterableInAppFragmentHTMLNotification() { this.loaded = false; this.backgroundAlpha = 0; this.messageId = ""; insetPadding = new Rect(); this.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.Theme_AppCompat_NoActionBar); }
static IterableInAppFragmentHTMLNotification function() { return notification; } public IterableInAppFragmentHTMLNotification() { this.loaded = false; this.backgroundAlpha = 0; this.messageId = ""; insetPadding = new Rect(); this.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.Theme_AppCompat_NoActionBar); }
/** * Returns the notification instance currently being shown * @return notification instance */
Returns the notification instance currently being shown
getInstance
{ "repo_name": "Iterable/iterable-android-sdk", "path": "iterableapi/src/main/java/com/iterable/iterableapi/IterableInAppFragmentHTMLNotification.java", "license": "mit", "size": 20247 }
[ "android.graphics.Rect", "androidx.fragment.app.DialogFragment" ]
import android.graphics.Rect; import androidx.fragment.app.DialogFragment;
import android.graphics.*; import androidx.fragment.app.*;
[ "android.graphics", "androidx.fragment" ]
android.graphics; androidx.fragment;
2,773,378
@Test public void lockWriteAndCheckParent() throws Exception { InodeFile inode1 = createInodeFile(1); InodeDirectory dir1 = createInodeDirectory(); inode1.setParentId(dir1.getId()); inode1.lockWriteAndCheckParent(dir1); assertTrue(inode1.isWriteLocked()); inode1.unlockWrite(); }
void function() throws Exception { InodeFile inode1 = createInodeFile(1); InodeDirectory dir1 = createInodeDirectory(); inode1.setParentId(dir1.getId()); inode1.lockWriteAndCheckParent(dir1); assertTrue(inode1.isWriteLocked()); inode1.unlockWrite(); }
/** * Tests the {@link Inode#lockWriteAndCheckParent(InodeView)} method. */
Tests the <code>Inode#lockWriteAndCheckParent(InodeView)</code> method
lockWriteAndCheckParent
{ "repo_name": "PasaLab/tachyon", "path": "core/server/master/src/test/java/alluxio/master/file/meta/InodeFileTest.java", "license": "apache-2.0", "size": 11421 }
[ "org.junit.Assert" ]
import org.junit.Assert;
import org.junit.*;
[ "org.junit" ]
org.junit;
2,882,340
EAttribute getFBCLead_Target();
EAttribute getFBCLead_Target();
/** * Returns the meta object for the attribute '{@link org.etl.sparrow.FBCLead#getTarget <em>Target</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Target</em>'. * @see org.etl.sparrow.FBCLead#getTarget() * @see #getFBCLead() * @generated */
Returns the meta object for the attribute '<code>org.etl.sparrow.FBCLead#getTarget Target</code>'.
getFBCLead_Target
{ "repo_name": "jpvelsamy/sparrow", "path": "org.etl.dsl.etl.Sparrow/src-gen/org/etl/sparrow/SparrowPackage.java", "license": "apache-2.0", "size": 104623 }
[ "org.eclipse.emf.ecore.EAttribute" ]
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
2,143,307
public WanReplicationRef setName(@Nonnull String name) { checkNotNull(name, "Name must not be null"); this.name = name; return this; } /** * Returns the merge policy sent to the WAN replication target to merge * replicated entries with existing target entries. * The default merge policy is {@link #DEFAULT_MERGE_POLICY_CLASS_NAME}
WanReplicationRef function(@Nonnull String name) { checkNotNull(name, STR); this.name = name; return this; } /** * Returns the merge policy sent to the WAN replication target to merge * replicated entries with existing target entries. * The default merge policy is {@link #DEFAULT_MERGE_POLICY_CLASS_NAME}
/** * Sets the WAN replication reference name. * * @param name the reference name * @return this config */
Sets the WAN replication reference name
setName
{ "repo_name": "emre-aydin/hazelcast", "path": "hazelcast/src/main/java/com/hazelcast/config/WanReplicationRef.java", "license": "apache-2.0", "size": 7738 }
[ "com.hazelcast.internal.util.Preconditions", "javax.annotation.Nonnull" ]
import com.hazelcast.internal.util.Preconditions; import javax.annotation.Nonnull;
import com.hazelcast.internal.util.*; import javax.annotation.*;
[ "com.hazelcast.internal", "javax.annotation" ]
com.hazelcast.internal; javax.annotation;
1,097,398
public DensityDialog.DensityPart getDensityPart() { return densityPart; }
DensityDialog.DensityPart function() { return densityPart; }
/** * returns part of density * * @return the density part */
returns part of density
getDensityPart
{ "repo_name": "NeuroBox3D/NeuGen", "path": "NeuGen/src/org/neugen/datastructures/VoxelVolume.java", "license": "lgpl-3.0", "size": 21244 }
[ "org.neugen.gui.DensityDialog" ]
import org.neugen.gui.DensityDialog;
import org.neugen.gui.*;
[ "org.neugen.gui" ]
org.neugen.gui;
112,256
public ProjectBroker getProjectBroker(Long projectBrokerId);
ProjectBroker function(Long projectBrokerId);
/** * Returns a project-broker object for certain project-broker-ID. * @param projectBrokerId * @return */
Returns a project-broker object for certain project-broker-ID
getProjectBroker
{ "repo_name": "stevenhva/InfoLearn_OpenOLAT", "path": "src/main/java/org/olat/course/nodes/projectbroker/service/ProjectBrokerManager.java", "license": "apache-2.0", "size": 8643 }
[ "org.olat.course.nodes.projectbroker.datamodel.ProjectBroker" ]
import org.olat.course.nodes.projectbroker.datamodel.ProjectBroker;
import org.olat.course.nodes.projectbroker.datamodel.*;
[ "org.olat.course" ]
org.olat.course;
334,700
public void handleExceededBacklogQuota(PersistentTopic persistentTopic) { TopicName topicName = TopicName.get(persistentTopic.getName()); String namespace = topicName.getNamespace(); String policyPath = AdminResource.path(POLICIES, namespace); BacklogQuota quota = getBacklogQuota(namespace, policyPath); log.info("Backlog quota exceeded for topic [{}]. Applying [{}] policy", persistentTopic.getName(), quota.getPolicy()); switch (quota.getPolicy()) { case consumer_backlog_eviction: dropBacklog(persistentTopic, quota); break; case producer_exception: case producer_request_hold: disconnectProducers(persistentTopic); break; default: break; } }
void function(PersistentTopic persistentTopic) { TopicName topicName = TopicName.get(persistentTopic.getName()); String namespace = topicName.getNamespace(); String policyPath = AdminResource.path(POLICIES, namespace); BacklogQuota quota = getBacklogQuota(namespace, policyPath); log.info(STR, persistentTopic.getName(), quota.getPolicy()); switch (quota.getPolicy()) { case consumer_backlog_eviction: dropBacklog(persistentTopic, quota); break; case producer_exception: case producer_request_hold: disconnectProducers(persistentTopic); break; default: break; } }
/** * Handle exceeded backlog by using policies set in the zookeeper for given topic * * @param persistentTopic * Topic on which backlog has been exceeded */
Handle exceeded backlog by using policies set in the zookeeper for given topic
handleExceededBacklogQuota
{ "repo_name": "ArvinDevel/incubator-pulsar", "path": "pulsar-broker/src/main/java/org/apache/pulsar/broker/service/BacklogQuotaManager.java", "license": "apache-2.0", "size": 9288 }
[ "org.apache.pulsar.broker.admin.AdminResource", "org.apache.pulsar.broker.service.persistent.PersistentTopic", "org.apache.pulsar.common.naming.TopicName", "org.apache.pulsar.common.policies.data.BacklogQuota" ]
import org.apache.pulsar.broker.admin.AdminResource; import org.apache.pulsar.broker.service.persistent.PersistentTopic; import org.apache.pulsar.common.naming.TopicName; import org.apache.pulsar.common.policies.data.BacklogQuota;
import org.apache.pulsar.broker.admin.*; import org.apache.pulsar.broker.service.persistent.*; import org.apache.pulsar.common.naming.*; import org.apache.pulsar.common.policies.data.*;
[ "org.apache.pulsar" ]
org.apache.pulsar;
1,918,667
private void startImporterThread(File[] fa) { Thread importer = new FileImporter(fa, dcmieParam); importer.start(); }
void function(File[] fa) { Thread importer = new FileImporter(fa, dcmieParam); importer.start(); }
/** * Alle aktuell ausgewaehlten Files in einem neuen Thread bearbeiten. * Anderenfalls wuerde die Bearbeitung den event-dispatch Thread blockieren. * Es wuerden dann z.B. keine Updates der Swing-Komponeten mehr gezeichnet. * @param fa the array of files to import. */
Alle aktuell ausgewaehlten Files in einem neuen Thread bearbeiten. Anderenfalls wuerde die Bearbeitung den event-dispatch Thread blockieren. Es wuerden dann z.B. keine Updates der Swing-Komponeten mehr gezeichnet
startImporterThread
{ "repo_name": "ph73nt/dcmie", "path": "Dcm_Import.java", "license": "gpl-2.0", "size": 9771 }
[ "de.iftm.ij.plugins.dcmie.FileImporter", "java.io.File" ]
import de.iftm.ij.plugins.dcmie.FileImporter; import java.io.File;
import de.iftm.ij.plugins.dcmie.*; import java.io.*;
[ "de.iftm.ij", "java.io" ]
de.iftm.ij; java.io;
1,055,780
@SuppressWarnings("unchecked") public List<PlanDTO> findByAffectedItem(Integer affectedItemId) { Query query = getSession().getNamedQuery("PlanDTO.findByAffectedItem"); query.setParameter("affected_item_id", affectedItemId); return query.list(); }
@SuppressWarnings(STR) List<PlanDTO> function(Integer affectedItemId) { Query query = getSession().getNamedQuery(STR); query.setParameter(STR, affectedItemId); return query.list(); }
/** * Fetch all plans that affect the pricing of the given item id, or include * the item in a bundle. * * @param affectedItemId affected item id * @return list of plans, empty if none found */
Fetch all plans that affect the pricing of the given item id, or include the item in a bundle
findByAffectedItem
{ "repo_name": "maxdelo77/replyit-master-3.2-final", "path": "src/java/com/sapienter/jbilling/server/item/db/PlanDAS.java", "license": "agpl-3.0", "size": 3304 }
[ "java.util.List", "org.hibernate.Query" ]
import java.util.List; import org.hibernate.Query;
import java.util.*; import org.hibernate.*;
[ "java.util", "org.hibernate" ]
java.util; org.hibernate;
2,215,119