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
private static void testRootLoggerDefault() { Properties props= new Properties(); ByteArrayOutputStream out1= new ByteArrayOutputStream(); ByteArrayOutputStream err1= new ByteArrayOutputStream(); PrintStream out2= new PrintStream(out1); PrintStream err2= new PrintStream(err1); testInitialize(props, out2, err2); Logger strLogger= Logger.getLogger(String.class); strLogger.trace("trace should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.debug("debug should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.info("info should not appear"); Assert.assertEquals(out1.toString(), ""); Assert.assertEquals(err1.toString(), ""); strLogger.warn("warn should appear"); int outlength= out1.toString().length(); Assert.assertTrue(out1.toString().startsWith("[java.lang.String] [WARN] warn should appear")); Assert.assertEquals(err1.toString(), ""); strLogger.error("error should appear"); Assert.assertEquals(out1.toString().length(), outlength); Assert.assertTrue(err1.toString().startsWith("[java.lang.String] [ERROR] error should appear")); strLogger.fatal("fatal should appear"); Assert.assertEquals(out1.toString().length(), outlength); Assert.assertTrue(err1.toString().contains("[java.lang.String] [FATAL] fatal should appear")); }
static void function() { Properties props= new Properties(); ByteArrayOutputStream out1= new ByteArrayOutputStream(); ByteArrayOutputStream err1= new ByteArrayOutputStream(); PrintStream out2= new PrintStream(out1); PrintStream err2= new PrintStream(err1); testInitialize(props, out2, err2); Logger strLogger= Logger.getLogger(String.class); strLogger.trace(STR); Assert.assertEquals(out1.toString(), STRSTRdebug should not appear"); Assert.assertEquals(out1.toString(), STRSTRinfo should not appear"); Assert.assertEquals(out1.toString(), STRSTRwarn should appearSTR[java.lang.String] [WARN] warn should appearSTRSTRerror should appearSTR[java.lang.String] [ERROR] error should appearSTRfatal should appearSTR[java.lang.String] [FATAL] fatal should appear")); }
/** * Tests that the root logger's default level is WARN and that loggers do not * log bellow this level and do log in the correct stream for levels equal to * and above WARN. */
Tests that the root logger's default level is WARN and that loggers do not log bellow this level and do log in the correct stream for levels equal to and above WARN
testRootLoggerDefault
{ "repo_name": "virtix/testng", "path": "src/org/testng/log4testng/Logger.java", "license": "apache-2.0", "size": 25583 }
[ "java.io.ByteArrayOutputStream", "java.io.PrintStream", "java.util.Properties", "org.testng.Assert", "org.testng.log4testng.Logger" ]
import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Properties; import org.testng.Assert; import org.testng.log4testng.Logger;
import java.io.*; import java.util.*; import org.testng.*; import org.testng.log4testng.*;
[ "java.io", "java.util", "org.testng", "org.testng.log4testng" ]
java.io; java.util; org.testng; org.testng.log4testng;
2,295,387
@SuppressLint("LongLogTag") @DebugLog private void openCamera(final int width, final int height) { Log.d(TAG, "width "+width+"height "+height); setUpCameraOutputs(width, height); configureTransform(width, height); final Activity activity = getActivity(); final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException("Time out waiting to lock camera opening."); } if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { Timber.tag(TAG).w("checkSelfPermission CAMERA"); } manager.openCamera("1", stateCallback, backgroundHandler); Timber.tag(TAG).d("open Camera"); } catch (final CameraAccessException e) { Timber.tag(TAG).e("Exception!", e); } catch (final InterruptedException e) { throw new RuntimeException("Interrupted while trying to lock camera opening.", e); } }
@SuppressLint(STR) void function(final int width, final int height) { Log.d(TAG, STR+width+STR+height); setUpCameraOutputs(width, height); configureTransform(width, height); final Activity activity = getActivity(); final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); try { if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) { throw new RuntimeException(STR); } if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { Timber.tag(TAG).w(STR); } manager.openCamera("1", stateCallback, backgroundHandler); Timber.tag(TAG).d(STR); } catch (final CameraAccessException e) { Timber.tag(TAG).e(STR, e); } catch (final InterruptedException e) { throw new RuntimeException(STR, e); } }
/** * Opens the camera specified by {@link CameraConnectionFragment#cameraId}. */
Opens the camera specified by <code>CameraConnectionFragment#cameraId</code>
openCamera
{ "repo_name": "hgs6424/Customicon", "path": "app/src/main/java/com/tzutalin/customicon/CameraConnectionFragment.java", "license": "apache-2.0", "size": 27293 }
[ "android.annotation.SuppressLint", "android.app.Activity", "android.content.Context", "android.content.pm.PackageManager", "android.hardware.camera2.CameraAccessException", "android.hardware.camera2.CameraManager", "android.support.v4.app.ActivityCompat", "android.util.Log", "java.util.concurrent.TimeUnit" ]
import android.annotation.SuppressLint; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraManager; import android.support.v4.app.ActivityCompat; import android.util.Log; import java.util.concurrent.TimeUnit;
import android.annotation.*; import android.app.*; import android.content.*; import android.content.pm.*; import android.hardware.camera2.*; import android.support.v4.app.*; import android.util.*; import java.util.concurrent.*;
[ "android.annotation", "android.app", "android.content", "android.hardware", "android.support", "android.util", "java.util" ]
android.annotation; android.app; android.content; android.hardware; android.support; android.util; java.util;
277,921
@Override public boolean keyPressed(KeyEvent event) { if (acceptExpandDrawer(event)) { expandDrawer(); return true; } if (acceptCollapseDrawer(event)) { collapseDrawer(); return true; } if (acceptExpandStack(event)) { expandStack(); return true; } if (acceptCollapseStack(event)) { collapseStack(event); return true; } if (acceptIntoExpandedDrawer(event)) { if (navigateIntoExpandedDrawer(event)) return true; } if (super.keyPressed(event)) return true; if (acceptSetFocusOnDrawer(event)) { if (navigateToDrawer(event)) return true; } if (acceptNextContainer(event)) { if (navigateToNextContainer(event)) return true; } return false; }
boolean function(KeyEvent event) { if (acceptExpandDrawer(event)) { expandDrawer(); return true; } if (acceptCollapseDrawer(event)) { collapseDrawer(); return true; } if (acceptExpandStack(event)) { expandStack(); return true; } if (acceptCollapseStack(event)) { collapseStack(event); return true; } if (acceptIntoExpandedDrawer(event)) { if (navigateIntoExpandedDrawer(event)) return true; } if (super.keyPressed(event)) return true; if (acceptSetFocusOnDrawer(event)) { if (navigateToDrawer(event)) return true; } if (acceptNextContainer(event)) { if (navigateToNextContainer(event)) return true; } return false; }
/** * Extends keyPressed to look for palette navigation keys. * * @see org.eclipse.gef.KeyHandler#keyPressed(org.eclipse.swt.events.KeyEvent) */
Extends keyPressed to look for palette navigation keys
keyPressed
{ "repo_name": "archimatetool/archi", "path": "org.eclipse.gef/src/org/eclipse/gef/ui/parts/PaletteViewerKeyHandler.java", "license": "mit", "size": 12820 }
[ "org.eclipse.swt.events.KeyEvent" ]
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.*;
[ "org.eclipse.swt" ]
org.eclipse.swt;
846,947
@Test(timeOut = 5000) public void testRateLimitingMultipleConsumers() throws Exception { log.info("-- Starting {} test --", methodName); final String namespace = "my-property/throttling_ns"; final String topicName = "persistent://" + namespace + "/throttlingMultipleConsumers"; final String subName = "my-subscriber-name"; final int messageRate = 5; DispatchRate dispatchRate = new DispatchRate(messageRate, -1, 360); admin.namespaces().createNamespace(namespace, Sets.newHashSet("test")); admin.namespaces().setSubscriptionDispatchRate(namespace, dispatchRate); final int numProducedMessages = 500; final AtomicInteger totalReceived = new AtomicInteger(0); // enable throttling for nonBacklog consumers conf.setDispatchThrottlingOnNonBacklogConsumerEnabled(true); ConsumerBuilder<byte[]> consumerBuilder = pulsarClient.newConsumer().topic(topicName) .subscriptionName(subName).subscriptionType(SubscriptionType.Shared).messageListener((c1, msg) -> { Assert.assertNotNull(msg, "Message cannot be null"); String receivedMessage = new String(msg.getData()); log.debug("Received message [{}] in the listener", receivedMessage); totalReceived.incrementAndGet(); }); Consumer<byte[]> consumer1 = consumerBuilder.subscribe(); Consumer<byte[]> consumer2 = consumerBuilder.subscribe(); Consumer<byte[]> consumer3 = consumerBuilder.subscribe(); Consumer<byte[]> consumer4 = consumerBuilder.subscribe(); Consumer<byte[]> consumer5 = consumerBuilder.subscribe(); Producer<byte[]> producer = pulsarClient.newProducer().topic(topicName).create(); PersistentTopic topic = (PersistentTopic) pulsar.getBrokerService().getOrCreateTopic(topicName).get(); DispatchRateLimiter subRateLimiter = null; Dispatcher subDispatcher = topic.getSubscription(subName).getDispatcher(); if (subDispatcher instanceof PersistentDispatcherMultipleConsumers) { subRateLimiter = ((PersistentDispatcherMultipleConsumers) subDispatcher).getRateLimiter().get(); } else if (subDispatcher instanceof PersistentDispatcherSingleActiveConsumer) { subRateLimiter = ((PersistentDispatcherSingleActiveConsumer) subDispatcher).getRateLimiter().get(); } else { Assert.fail("Should only have PersistentDispatcher in this test"); } boolean isMessageRateUpdate = false; int retry = 5; for (int i = 0; i < retry; i++) { if (subRateLimiter.getDispatchRateOnMsg() > 0 || subRateLimiter.getDispatchRateOnByte() > 0) { isMessageRateUpdate = true; break; } else { if (i != retry - 1) { Thread.sleep(100); } } } Assert.assertTrue(isMessageRateUpdate); Assert.assertEquals(admin.namespaces().getSubscriptionDispatchRate(namespace), dispatchRate); // Asynchronously produce messages for (int i = 0; i < numProducedMessages; i++) { final String message = "my-message-" + i; producer.send(message.getBytes()); } // it can make sure that consumer had enough time to consume message but couldn't consume due to throttling Thread.sleep(500); // consumer should not have received all published message due to message-rate throttling Assert.assertNotEquals(totalReceived.get(), numProducedMessages); consumer1.close(); consumer2.close(); consumer3.close(); consumer4.close(); consumer5.close(); producer.close(); log.info("-- Exiting {} test --", methodName); }
@Test(timeOut = 5000) void function() throws Exception { log.info(STR, methodName); final String namespace = STR; final String topicName = STRmy-subscriber-nameSTRtestSTRMessage cannot be nullSTRReceived message [{}] in the listenerSTRShould only have PersistentDispatcher in this testSTRmy-message-STR-- Exiting {} test --", methodName); }
/** * verify message-rate on multiple consumers with shared-subscription * * @throws Exception */
verify message-rate on multiple consumers with shared-subscription
testRateLimitingMultipleConsumers
{ "repo_name": "merlimat/pulsar", "path": "pulsar-broker/src/test/java/org/apache/pulsar/client/api/SubscriptionMessageDispatchThrottlingTest.java", "license": "apache-2.0", "size": 28285 }
[ "org.testng.annotations.Test" ]
import org.testng.annotations.Test;
import org.testng.annotations.*;
[ "org.testng.annotations" ]
org.testng.annotations;
2,562,402
@SuppressWarnings("unchecked") public T logger(Logger value) { this.subresources.loggers.add(value); return (T) this; }
@SuppressWarnings(STR) T function(Logger value) { this.subresources.loggers.add(value); return (T) this; }
/** * Add the Logger object to the list of subresources * @param value The Logger to add * @return this */
Add the Logger object to the list of subresources
logger
{ "repo_name": "wildfly-swarm/wildfly-config-api", "path": "generator/src/test/java/org/wildfly/apigen/test/invocation/logging/Logging.java", "license": "apache-2.0", "size": 17694 }
[ "org.wildfly.apigen.test.invocation.logging.subsystem.logger.Logger" ]
import org.wildfly.apigen.test.invocation.logging.subsystem.logger.Logger;
import org.wildfly.apigen.test.invocation.logging.subsystem.logger.*;
[ "org.wildfly.apigen" ]
org.wildfly.apigen;
1,316,502
private void deleteEncryptionKey(String[] params) throws Exception { CommandLine args = parseCommandArgs(DELETE_KEY_OPTIONS, params); String keyName = args.getOptionValue("keyName"); try { encryptionShim.deleteKey(keyName); } catch (IOException e) { throw new Exception("Cannot delete encryption key: " + e.getMessage()); } writeTestOutput("Encryption key deleted: '" + keyName + "'"); }
void function(String[] params) throws Exception { CommandLine args = parseCommandArgs(DELETE_KEY_OPTIONS, params); String keyName = args.getOptionValue(STR); try { encryptionShim.deleteKey(keyName); } catch (IOException e) { throw new Exception(STR + e.getMessage()); } writeTestOutput(STR + keyName + "'"); }
/** * Deletes an encryption key using the parameters passed through the 'delete_key' action. * * @param params Parameters passed to the 'delete_key' command action. * @throws Exception If key deletion failed. */
Deletes an encryption key using the parameters passed through the 'delete_key' action
deleteEncryptionKey
{ "repo_name": "wisgood/hive", "path": "ql/src/java/org/apache/hadoop/hive/ql/processors/CryptoProcessor.java", "license": "apache-2.0", "size": 6687 }
[ "java.io.IOException", "org.apache.commons.cli.CommandLine" ]
import java.io.IOException; import org.apache.commons.cli.CommandLine;
import java.io.*; import org.apache.commons.cli.*;
[ "java.io", "org.apache.commons" ]
java.io; org.apache.commons;
2,540,417
public Map<CmsUUID, Map<String, CmsXmlContentProperty>> getDefaultProperties( List<CmsUUID> structureIds) throws CmsException { CmsObject cms = m_cms; Map<CmsUUID, Map<String, CmsXmlContentProperty>> result = Maps.newHashMap(); for (CmsUUID structureId : structureIds) { CmsResource resource = cms.readResource(structureId, CmsResourceFilter.ALL); String typeName = OpenCms.getResourceManager().getResourceType(resource).getTypeName(); Map<String, CmsXmlContentProperty> propertyConfig = getDefaultPropertiesForType(typeName); result.put(structureId, propertyConfig); } return result; }
Map<CmsUUID, Map<String, CmsXmlContentProperty>> function( List<CmsUUID> structureIds) throws CmsException { CmsObject cms = m_cms; Map<CmsUUID, Map<String, CmsXmlContentProperty>> result = Maps.newHashMap(); for (CmsUUID structureId : structureIds) { CmsResource resource = cms.readResource(structureId, CmsResourceFilter.ALL); String typeName = OpenCms.getResourceManager().getResourceType(resource).getTypeName(); Map<String, CmsXmlContentProperty> propertyConfig = getDefaultPropertiesForType(typeName); result.put(structureId, propertyConfig); } return result; }
/** * Internal method for computing the default property configurations for a list of structure ids.<p> * * @param structureIds the structure ids for which we want the default property configurations * @return a map from the given structure ids to their default property configurations * * @throws CmsException if something goes wrong */
Internal method for computing the default property configurations for a list of structure ids
getDefaultProperties
{ "repo_name": "alkacon/opencms-core", "path": "src/org/opencms/gwt/CmsPropertyEditorHelper.java", "license": "lgpl-2.1", "size": 20369 }
[ "com.google.common.collect.Maps", "java.util.List", "java.util.Map", "org.opencms.file.CmsObject", "org.opencms.file.CmsResource", "org.opencms.file.CmsResourceFilter", "org.opencms.main.CmsException", "org.opencms.main.OpenCms", "org.opencms.util.CmsUUID", "org.opencms.xml.content.CmsXmlContentProperty" ]
import com.google.common.collect.Maps; import java.util.List; import java.util.Map; import org.opencms.file.CmsObject; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.main.CmsException; import org.opencms.main.OpenCms; import org.opencms.util.CmsUUID; import org.opencms.xml.content.CmsXmlContentProperty;
import com.google.common.collect.*; import java.util.*; import org.opencms.file.*; import org.opencms.main.*; import org.opencms.util.*; import org.opencms.xml.content.*;
[ "com.google.common", "java.util", "org.opencms.file", "org.opencms.main", "org.opencms.util", "org.opencms.xml" ]
com.google.common; java.util; org.opencms.file; org.opencms.main; org.opencms.util; org.opencms.xml;
1,557,138
public Function<Artifact, Artifact> collapseToFunction() { final HashMap<Artifact, Artifact> collapsed = new HashMap<>(); for (ImmutableMap<Artifact, Artifact> partialMapping : runtimeJars) { collapsed.putAll(partialMapping); } return jar -> { Artifact result = collapsed.get(jar); return result != null ? result : jar; // return null iff input == null }; }
Function<Artifact, Artifact> function() { final HashMap<Artifact, Artifact> collapsed = new HashMap<>(); for (ImmutableMap<Artifact, Artifact> partialMapping : runtimeJars) { collapsed.putAll(partialMapping); } return jar -> { Artifact result = collapsed.get(jar); return result != null ? result : jar; }; }
/** * Returns function that maps Jars to desugaring results if available and returns the given Jar * otherwise. */
Returns function that maps Jars to desugaring results if available and returns the given Jar otherwise
collapseToFunction
{ "repo_name": "dropbox/bazel", "path": "src/main/java/com/google/devtools/build/lib/rules/android/AndroidRuntimeJarProvider.java", "license": "apache-2.0", "size": 3754 }
[ "com.google.common.base.Function", "com.google.common.collect.ImmutableMap", "com.google.devtools.build.lib.actions.Artifact", "java.util.HashMap" ]
import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.devtools.build.lib.actions.Artifact; import java.util.HashMap;
import com.google.common.base.*; import com.google.common.collect.*; import com.google.devtools.build.lib.actions.*; import java.util.*;
[ "com.google.common", "com.google.devtools", "java.util" ]
com.google.common; com.google.devtools; java.util;
182,858
@DELETE("/deleterequest/{id}") public String deleteRequest(@PathParam("id") String id);
@DELETE(STR) String function(@PathParam("id") String id);
/** * <p>A mock request which uses the HTTP method DELETE.</p> * * @param id * the id of the entity to delete * * @return the textual content of the {@link HttpResponse} body * * @since 1.3.0 */
A mock request which uses the HTTP method DELETE
deleteRequest
{ "repo_name": "sahan/ZombieLink", "path": "zombielink/src/test/java/com/lonepulse/zombielink/processor/HttpMethodEndpoint.java", "license": "apache-2.0", "size": 4301 }
[ "com.lonepulse.zombielink.annotation.PathParam" ]
import com.lonepulse.zombielink.annotation.PathParam;
import com.lonepulse.zombielink.annotation.*;
[ "com.lonepulse.zombielink" ]
com.lonepulse.zombielink;
1,627,232
void setResults(List<ItemStack> results);
void setResults(List<ItemStack> results);
/** * Sets the results for this event. * * @param results The new result */
Sets the results for this event
setResults
{ "repo_name": "joshgarde/SpongeAPI", "path": "src/main/java/org/spongepowered/api/event/inventory/BulkItemResultEvent.java", "license": "mit", "size": 1843 }
[ "java.util.List", "org.spongepowered.api.item.inventory.ItemStack" ]
import java.util.List; import org.spongepowered.api.item.inventory.ItemStack;
import java.util.*; import org.spongepowered.api.item.inventory.*;
[ "java.util", "org.spongepowered.api" ]
java.util; org.spongepowered.api;
2,515,566
private void releaseIndexSearcher() { if (indexSearcher != null) { try { indexSearcher.close(); } catch (IOException ioe) { // ignore it } indexSearcher = null; } }
void function() { if (indexSearcher != null) { try { indexSearcher.close(); } catch (IOException ioe) { } indexSearcher = null; } }
/** * Release the index searcher. * */
Release the index searcher
releaseIndexSearcher
{ "repo_name": "apache/cocoon", "path": "blocks/cocoon-lucene/cocoon-lucene-impl/src/main/java/org/apache/cocoon/components/search/SimpleLuceneCocoonSearcherImpl.java", "license": "apache-2.0", "size": 13071 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
382,854
@Test public void getServiceDeactivatedReturnsNull() { ConcurrentServiceReferenceSetMap<String, String> map = new ConcurrentServiceReferenceSetMap<String, String>("refName"); map.putReference("key1", mockServiceReference1); map.activate(mockComponentContext); context.checking(new Expectations() { { one(mockComponentContext).locateService("refName", mockServiceReference1); } }); Iterator<String> services = map.getServices("key1"); assertNotNull("a. getServices should never return null", services); assertTrue("b. The service should be resolved as activate and a valid reference exist", services.hasNext()); assertNotNull("c. The service should be resolved as activate and a valid reference exist", services.next()); context.assertIsSatisfied(); map.deactivate(mockComponentContext); assertNull("After deactivate, services should be null", map.getServices("key1")); } //TODO: test cases for getServicesWithReferences
void function() { ConcurrentServiceReferenceSetMap<String, String> map = new ConcurrentServiceReferenceSetMap<String, String>(STR); map.putReference("key1", mockServiceReference1); map.activate(mockComponentContext); context.checking(new Expectations() { { one(mockComponentContext).locateService(STR, mockServiceReference1); } }); Iterator<String> services = map.getServices("key1"); assertNotNull(STR, services); assertTrue(STR, services.hasNext()); assertNotNull(STR, services.next()); context.assertIsSatisfied(); map.deactivate(mockComponentContext); assertNull(STR, map.getServices("key1")); }
/** * Test method for {@link com.ibm.wsspi.kernel.service.utils.ConcurrentServiceReferenceSetMap#getService(java.lang.Object)}. */
Test method for <code>com.ibm.wsspi.kernel.service.utils.ConcurrentServiceReferenceSetMap#getService(java.lang.Object)</code>
getServiceDeactivatedReturnsNull
{ "repo_name": "OpenLiberty/open-liberty", "path": "dev/com.ibm.ws.kernel.service/test/com/ibm/wsspi/kernel/service/utils/ConcurrentServiceReferenceSetMapTest.java", "license": "epl-1.0", "size": 16540 }
[ "java.util.Iterator", "org.jmock.Expectations", "org.junit.Assert" ]
import java.util.Iterator; import org.jmock.Expectations; import org.junit.Assert;
import java.util.*; import org.jmock.*; import org.junit.*;
[ "java.util", "org.jmock", "org.junit" ]
java.util; org.jmock; org.junit;
1,586,720
@Override public void transform(double[] srcPts, int srcOff, final double[] dstPts, int dstOff, int numPts) throws TransformException { int inc = dimension; if (srcPts == dstPts) { switch (IterationStrategy.suggest(srcOff, inc, dstOff, inc, numPts)) { case ASCENDING: { break; } case DESCENDING: { srcOff += (numPts-1) * inc; dstOff += (numPts-1) * inc; inc = -inc; break; } default: { // BUFFER_SOURCE, but also a reasonable default for any case. srcPts = Arrays.copyOfRange(srcPts, srcOff, srcOff + numPts*inc); srcOff = 0; break; } } } final double[] vector = new double[dimension]; while (--numPts >= 0) { final double x = srcPts[srcOff ]; final double y = srcPts[srcOff+1]; grid.interpolateInCell(x, y, vector); if (dimension > GRID_DIMENSION) { System.arraycopy(srcPts, srcOff + GRID_DIMENSION, dstPts, dstOff + GRID_DIMENSION, dimension - GRID_DIMENSION); int i = dimension; do dstPts[dstOff + --i] += vector[i]; while (i > GRID_DIMENSION); } dstPts[dstOff+1] = y + vector[1]; dstPts[dstOff ] = x + vector[0]; // Shall not be done before above loop. dstOff += inc; srcOff += inc; } }
void function(double[] srcPts, int srcOff, final double[] dstPts, int dstOff, int numPts) throws TransformException { int inc = dimension; if (srcPts == dstPts) { switch (IterationStrategy.suggest(srcOff, inc, dstOff, inc, numPts)) { case ASCENDING: { break; } case DESCENDING: { srcOff += (numPts-1) * inc; dstOff += (numPts-1) * inc; inc = -inc; break; } default: { srcPts = Arrays.copyOfRange(srcPts, srcOff, srcOff + numPts*inc); srcOff = 0; break; } } } final double[] vector = new double[dimension]; while (--numPts >= 0) { final double x = srcPts[srcOff ]; final double y = srcPts[srcOff+1]; grid.interpolateInCell(x, y, vector); if (dimension > GRID_DIMENSION) { System.arraycopy(srcPts, srcOff + GRID_DIMENSION, dstPts, dstOff + GRID_DIMENSION, dimension - GRID_DIMENSION); int i = dimension; do dstPts[dstOff + --i] += vector[i]; while (i > GRID_DIMENSION); } dstPts[dstOff+1] = y + vector[1]; dstPts[dstOff ] = x + vector[0]; dstOff += inc; srcOff += inc; } }
/** * Transforms an arbitrary amount of coordinates. * * @throws TransformException if a point can not be transformed. */
Transforms an arbitrary amount of coordinates
transform
{ "repo_name": "Geomatys/sis", "path": "core/sis-referencing/src/main/java/org/apache/sis/referencing/operation/transform/InterpolatedTransform.java", "license": "apache-2.0", "size": 26476 }
[ "java.util.Arrays", "org.opengis.referencing.operation.TransformException" ]
import java.util.Arrays; import org.opengis.referencing.operation.TransformException;
import java.util.*; import org.opengis.referencing.operation.*;
[ "java.util", "org.opengis.referencing" ]
java.util; org.opengis.referencing;
2,050,550
public MethodInfo getMethod(String name) { ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); if (minfo.getName().equals(name)) return minfo; } return null; }
MethodInfo function(String name) { ArrayList list = methods; int n = list.size(); for (int i = 0; i < n; ++i) { MethodInfo minfo = (MethodInfo)list.get(i); if (minfo.getName().equals(name)) return minfo; } return null; }
/** * Returns the method with the specified name. If there are multiple methods * with that name, this method returns one of them. * * @return null if no such method is found. */
Returns the method with the specified name. If there are multiple methods with that name, this method returns one of them
getMethod
{ "repo_name": "s20121035/rk3288_android5.1_repo", "path": "external/javassist/src/main/javassist/bytecode/ClassFile.java", "license": "gpl-3.0", "size": 26395 }
[ "java.util.ArrayList" ]
import java.util.ArrayList;
import java.util.*;
[ "java.util" ]
java.util;
174,960
protected URL doPost(Path path, Object value) throws QueryException { throw new QueryException(Query.Status.METHOD_NOT_ALLOWED); }
URL function(Path path, Object value) throws QueryException { throw new QueryException(Query.Status.METHOD_NOT_ALLOWED); }
/** * Handles an HTTP POST request. The default implementation throws an HTTP * 405 query exception. * * @param path * @param value * * @return * A URL containing the location of the created resource, or <tt>null</tt> if * operation did not result in the creation of a resource. * * @throws QueryException */
Handles an HTTP POST request. The default implementation throws an HTTP 405 query exception
doPost
{ "repo_name": "andrescabrera/gwt-dojo-toolkit", "path": "src/org/apache/pivot/web/server/QueryServlet.java", "license": "apache-2.0", "size": 20154 }
[ "org.apache.pivot.web.Query", "org.apache.pivot.web.QueryException" ]
import org.apache.pivot.web.Query; import org.apache.pivot.web.QueryException;
import org.apache.pivot.web.*;
[ "org.apache.pivot" ]
org.apache.pivot;
1,940,840
public ActionForward deleteSummarizedDetailLine(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CertificationReportForm certificationReportForm = (CertificationReportForm) form; // remove the selected summary line List<EffortCertificationDetail> summarizedDetailLines = certificationReportForm.getSummarizedDetailLines(); int lineToRecalculateIndex = this.getSelectedLine(request); EffortCertificationDetail lineToDelete = summarizedDetailLines.get(lineToRecalculateIndex); summarizedDetailLines.remove(lineToDelete); String groupId = lineToDelete.getGroupId(); List<EffortCertificationDetail> detailLines = certificationReportForm.getDetailLines(); List<EffortCertificationDetail> detailLinesToDelete = this.findDetailLinesInGroup(detailLines, groupId); detailLines.removeAll(detailLinesToDelete); return mapping.findForward(KFSConstants.MAPPING_BASIC); }
ActionForward function(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { CertificationReportForm certificationReportForm = (CertificationReportForm) form; List<EffortCertificationDetail> summarizedDetailLines = certificationReportForm.getSummarizedDetailLines(); int lineToRecalculateIndex = this.getSelectedLine(request); EffortCertificationDetail lineToDelete = summarizedDetailLines.get(lineToRecalculateIndex); summarizedDetailLines.remove(lineToDelete); String groupId = lineToDelete.getGroupId(); List<EffortCertificationDetail> detailLines = certificationReportForm.getDetailLines(); List<EffortCertificationDetail> detailLinesToDelete = this.findDetailLinesInGroup(detailLines, groupId); detailLines.removeAll(detailLinesToDelete); return mapping.findForward(KFSConstants.MAPPING_BASIC); }
/** * delete a detail line from summarized detail lines and make a corresponding update on the underlying detail lines */
delete a detail line from summarized detail lines and make a corresponding update on the underlying detail lines
deleteSummarizedDetailLine
{ "repo_name": "quikkian-ua-devops/will-financials", "path": "kfs-ec/src/main/java/org/kuali/kfs/module/ec/document/web/struts/CertificationReportAction.java", "license": "agpl-3.0", "size": 34115 }
[ "java.util.List", "javax.servlet.http.HttpServletRequest", "javax.servlet.http.HttpServletResponse", "org.apache.struts.action.ActionForm", "org.apache.struts.action.ActionForward", "org.apache.struts.action.ActionMapping", "org.kuali.kfs.module.ec.businessobject.EffortCertificationDetail", "org.kuali.kfs.sys.KFSConstants" ]
import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.kuali.kfs.module.ec.businessobject.EffortCertificationDetail; import org.kuali.kfs.sys.KFSConstants;
import java.util.*; import javax.servlet.http.*; import org.apache.struts.action.*; import org.kuali.kfs.module.ec.businessobject.*; import org.kuali.kfs.sys.*;
[ "java.util", "javax.servlet", "org.apache.struts", "org.kuali.kfs" ]
java.util; javax.servlet; org.apache.struts; org.kuali.kfs;
2,867,215
public void call(String name, Object value, @DelegatesTo(StreamingJsonDelegate.class) Closure callable) throws IOException { if (generator.isExcludingFieldsNamed(name)) { return; } writeName(name); verifyValue(); writeObject(writer, value, callable, generator); }
void function(String name, Object value, @DelegatesTo(StreamingJsonDelegate.class) Closure callable) throws IOException { if (generator.isExcludingFieldsNamed(name)) { return; } writeName(name); verifyValue(); writeObject(writer, value, callable, generator); }
/** * Writes the name and value of a JSON attribute * * @param name The attribute name * @param value The value * @throws IOException */
Writes the name and value of a JSON attribute
call
{ "repo_name": "avafanasiev/groovy", "path": "subprojects/groovy-json/src/main/java/groovy/json/StreamingJsonBuilder.java", "license": "apache-2.0", "size": 31409 }
[ "groovy.lang.Closure", "groovy.lang.DelegatesTo", "java.io.IOException" ]
import groovy.lang.Closure; import groovy.lang.DelegatesTo; import java.io.IOException;
import groovy.lang.*; import java.io.*;
[ "groovy.lang", "java.io" ]
groovy.lang; java.io;
1,198,697
public HandlerRegistration addScrollHandler(ScrollHandler handler) { return addHandler(handler, ScrollEvent.TYPE); }
HandlerRegistration function(ScrollHandler handler) { return addHandler(handler, ScrollEvent.TYPE); }
/** * Adds a scroll handler to this grid * * @param handler * the scroll handler to add * @return a handler registration for the registered scroll handler */
Adds a scroll handler to this grid
addScrollHandler
{ "repo_name": "travisfw/vaadin", "path": "client/src/com/vaadin/client/widgets/Grid.java", "license": "apache-2.0", "size": 285859 }
[ "com.google.gwt.event.shared.HandlerRegistration", "com.vaadin.client.widget.grid.events.ScrollEvent", "com.vaadin.client.widget.grid.events.ScrollHandler" ]
import com.google.gwt.event.shared.HandlerRegistration; import com.vaadin.client.widget.grid.events.ScrollEvent; import com.vaadin.client.widget.grid.events.ScrollHandler;
import com.google.gwt.event.shared.*; import com.vaadin.client.widget.grid.events.*;
[ "com.google.gwt", "com.vaadin.client" ]
com.google.gwt; com.vaadin.client;
2,033,172
@Override public void enterEval_input(@NotNull Python3Parser.Eval_inputContext ctx) { }
@Override public void enterEval_input(@NotNull Python3Parser.Eval_inputContext ctx) { }
/** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */
The default implementation does nothing
exitNonlocal_stmt
{ "repo_name": "IsThisThePayneResidence/intellidots", "path": "src/main/java/ua/edu/hneu/ast/parsers/Python3BaseListener.java", "license": "gpl-3.0", "size": 30027 }
[ "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;
985,931
Paint.FontMetrics metrics = paint.getFontMetrics(); return (-metrics.ascent) + metrics.descent; //return (-metrics.top) + metrics.bottom; }
Paint.FontMetrics metrics = paint.getFontMetrics(); return (-metrics.ascent) + metrics.descent; }
/** * Determines the height of the tallest character that can be drawn by paint. * @param paint * @return */
Determines the height of the tallest character that can be drawn by paint
getFontHeight
{ "repo_name": "sayan801/Android-Chart-Graph-Samples", "path": "ChartPrototypeAndroidplot/app/libs/AndroidPlot-Core/src/main/java/com/androidplot/util/FontUtils.java", "license": "apache-2.0", "size": 2165 }
[ "android.graphics.Paint" ]
import android.graphics.Paint;
import android.graphics.*;
[ "android.graphics" ]
android.graphics;
616,572
public Integer getValueFromText(String text) { String found = new String(""); Iterator<String> keys = map.keySet().iterator(); while (found.length() == 0 && keys.hasNext()) { String cur = (String) keys.next(); if (cur.compareTo(text) == 0) { found = (String) map.get(cur); } } return new Integer((String) found); }
Integer function(String text) { String found = new String(""); Iterator<String> keys = map.keySet().iterator(); while (found.length() == 0 && keys.hasNext()) { String cur = (String) keys.next(); if (cur.compareTo(text) == 0) { found = (String) map.get(cur); } } return new Integer((String) found); }
/** * Resolve value of widget from full text. * * @param text * @return */
Resolve value of widget from full text
getValueFromText
{ "repo_name": "freemed/freemed", "path": "ui/gwt/src/main/java/org/freemedsoftware/gwt/client/widget/PatientTagWidget.java", "license": "gpl-2.0", "size": 10250 }
[ "java.util.Iterator" ]
import java.util.Iterator;
import java.util.*;
[ "java.util" ]
java.util;
1,785,146
public void add(Mat descriptors) { add_0(nativeObj, descriptors.nativeObj); } // // C++: void cv::BOWTrainer::clear() //
void function(Mat descriptors) { add_0(nativeObj, descriptors.nativeObj); } //
/** * Adds descriptors to a training set. * * @param descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a * descriptor. * * The training set is clustered using clustermethod to construct the vocabulary. */
Adds descriptors to a training set
add
{ "repo_name": "HuTianQi/QQ", "path": "openCVLibrary411/src/main/java/org/opencv/features2d/BOWTrainer.java", "license": "mit", "size": 3893 }
[ "org.opencv.core.Mat" ]
import org.opencv.core.Mat;
import org.opencv.core.*;
[ "org.opencv.core" ]
org.opencv.core;
1,445,976
public List<NameValuePair> details() { return this.details; }
List<NameValuePair> function() { return this.details; }
/** * Get the details value. * * @return the details value */
Get the details value
details
{ "repo_name": "hovsepm/azure-sdk-for-java", "path": "batchai/resource-manager/v2017_09_01_preview/src/main/java/com/microsoft/azure/management/batchai/v2017_09_01_preview/BatchAIError.java", "license": "mit", "size": 2219 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,376,338
public PlatformClusterNodeFilter createClusterNodeFilter(Object filter);
PlatformClusterNodeFilter function(Object filter);
/** * Create cluster node filter. * * @param filter Native filter. * @return Cluster node filter. */
Create cluster node filter
createClusterNodeFilter
{ "repo_name": "agoncharuk/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/platform/PlatformContext.java", "license": "apache-2.0", "size": 8172 }
[ "org.apache.ignite.internal.processors.platform.cluster.PlatformClusterNodeFilter" ]
import org.apache.ignite.internal.processors.platform.cluster.PlatformClusterNodeFilter;
import org.apache.ignite.internal.processors.platform.cluster.*;
[ "org.apache.ignite" ]
org.apache.ignite;
858,531
public static Edge edgeFromJson( final String json, final Vertex out, final Vertex in, final ElementFactory factory, final GraphSONMode mode, final Set<String> propertyKeys) throws IOException { final OGraphSONUtility graphson = new OGraphSONUtility(mode, factory, null, propertyKeys); return graphson.edgeFromJson(json, out, in); }
static Edge function( final String json, final Vertex out, final Vertex in, final ElementFactory factory, final GraphSONMode mode, final Set<String> propertyKeys) throws IOException { final OGraphSONUtility graphson = new OGraphSONUtility(mode, factory, null, propertyKeys); return graphson.edgeFromJson(json, out, in); }
/** * Reads an individual Edge from JSON. The edge must match the accepted GraphSON format. * * @param json a single edge in GraphSON format as a String * @param factory the factory responsible for constructing graph elements * @param mode the mode of the GraphSON * @param propertyKeys a list of keys to include when reading of element properties */
Reads an individual Edge from JSON. The edge must match the accepted GraphSON format
edgeFromJson
{ "repo_name": "orientechnologies/orientdb", "path": "graphdb/src/main/java/com/orientechnologies/orient/graph/graphml/OGraphSONUtility.java", "license": "apache-2.0", "size": 33157 }
[ "com.tinkerpop.blueprints.Edge", "com.tinkerpop.blueprints.Vertex", "com.tinkerpop.blueprints.util.io.graphson.ElementFactory", "com.tinkerpop.blueprints.util.io.graphson.GraphSONMode", "java.io.IOException", "java.util.Set" ]
import com.tinkerpop.blueprints.Edge; import com.tinkerpop.blueprints.Vertex; import com.tinkerpop.blueprints.util.io.graphson.ElementFactory; import com.tinkerpop.blueprints.util.io.graphson.GraphSONMode; import java.io.IOException; import java.util.Set;
import com.tinkerpop.blueprints.*; import com.tinkerpop.blueprints.util.io.graphson.*; import java.io.*; import java.util.*;
[ "com.tinkerpop.blueprints", "java.io", "java.util" ]
com.tinkerpop.blueprints; java.io; java.util;
810,188
public Collection<String> getAllCoreNames() { return solrCores.getAllCoreNames(); }
Collection<String> function() { return solrCores.getAllCoreNames(); }
/** * get a list of all the cores that are currently loaded * @return a list of al lthe available core names in either permanent or transient core lists. */
get a list of all the cores that are currently loaded
getAllCoreNames
{ "repo_name": "cscorley/solr-only-mirror", "path": "core/src/java/org/apache/solr/core/CoreContainer.java", "license": "apache-2.0", "size": 30849 }
[ "java.util.Collection" ]
import java.util.Collection;
import java.util.*;
[ "java.util" ]
java.util;
291,415
@Test public final void testHttpErrors() throws Exception { // set up web service ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(HttpErrorServlet.class, "/*"); // create the service TestServer server = new TestServer(); server.addHandler(handler); try { server.startServer(); HttpErrorServlet servlet = (HttpErrorServlet) handler.getServlets()[0].getServlet(); String destination = server.getUrl(); this.controller = TestRunners.newTestRunner(GetHTTP.class); this.controller.setProperty(GetHTTP.CONNECTION_TIMEOUT, "5 secs"); this.controller.setProperty(GetHTTP.URL, destination+"/test_${literal(1)}.pdf"); this.controller.setProperty(GetHTTP.FILENAME, "test_${now():format('yyyy/MM/dd_HH:mm:ss')}"); this.controller.setProperty(GetHTTP.ACCEPT_CONTENT_TYPE, "application/json"); this.controller.setProperty(GetHTTP.USER_AGENT, "testUserAgent"); // 204 - NO CONTENT servlet.setErrorToReturn(HttpServletResponse.SC_NO_CONTENT); this.controller.run(); this.controller.assertTransferCount(GetHTTP.REL_SUCCESS, 0); // 404 - NOT FOUND servlet.setErrorToReturn(HttpServletResponse.SC_NOT_FOUND); this.controller.run(); this.controller.assertTransferCount(GetHTTP.REL_SUCCESS, 0); // 500 - INTERNAL SERVER ERROR servlet.setErrorToReturn(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); this.controller.run(); this.controller.assertTransferCount(GetHTTP.REL_SUCCESS, 0); } finally { // shutdown web service server.shutdownServer(); } }
final void function() throws Exception { ServletHandler handler = new ServletHandler(); handler.addServletWithMapping(HttpErrorServlet.class, "/*"); TestServer server = new TestServer(); server.addHandler(handler); try { server.startServer(); HttpErrorServlet servlet = (HttpErrorServlet) handler.getServlets()[0].getServlet(); String destination = server.getUrl(); this.controller = TestRunners.newTestRunner(GetHTTP.class); this.controller.setProperty(GetHTTP.CONNECTION_TIMEOUT, STR); this.controller.setProperty(GetHTTP.URL, destination+STR); this.controller.setProperty(GetHTTP.FILENAME, STR); this.controller.setProperty(GetHTTP.ACCEPT_CONTENT_TYPE, STR); this.controller.setProperty(GetHTTP.USER_AGENT, STR); servlet.setErrorToReturn(HttpServletResponse.SC_NO_CONTENT); this.controller.run(); this.controller.assertTransferCount(GetHTTP.REL_SUCCESS, 0); servlet.setErrorToReturn(HttpServletResponse.SC_NOT_FOUND); this.controller.run(); this.controller.assertTransferCount(GetHTTP.REL_SUCCESS, 0); servlet.setErrorToReturn(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); this.controller.run(); this.controller.assertTransferCount(GetHTTP.REL_SUCCESS, 0); } finally { server.shutdownServer(); } }
/** * Test for HTTP errors * @throws Exception exception */
Test for HTTP errors
testHttpErrors
{ "repo_name": "Xsixteen/nifi", "path": "nifi-nar-bundles/nifi-standard-bundle/nifi-standard-processors/src/test/java/org/apache/nifi/processors/standard/TestGetHTTP.java", "license": "apache-2.0", "size": 23138 }
[ "javax.servlet.http.HttpServletResponse", "org.apache.nifi.util.TestRunners", "org.eclipse.jetty.servlet.ServletHandler" ]
import javax.servlet.http.HttpServletResponse; import org.apache.nifi.util.TestRunners; import org.eclipse.jetty.servlet.ServletHandler;
import javax.servlet.http.*; import org.apache.nifi.util.*; import org.eclipse.jetty.servlet.*;
[ "javax.servlet", "org.apache.nifi", "org.eclipse.jetty" ]
javax.servlet; org.apache.nifi; org.eclipse.jetty;
2,517,984
public boolean hasTitles() { return Base.has(this.model, this.getResource(), TITLE); }
boolean function() { return Base.has(this.model, this.getResource(), TITLE); }
/** * Check if org.ontoware.rdfreactor.generator.java.JProperty@5bbe2ed3 has at * least one value set * * @return true if this property has at least one value [Generated from * RDFReactor template rule #get0has-dynamic] */
Check if org.ontoware.rdfreactor.generator.java.JProperty@5bbe2ed3 has at least one value set
hasTitles
{ "repo_name": "m0ep/master-thesis", "path": "source/apis/rdf2go/rdf2go-foaf/src/main/java/com/xmlns/foaf/Thing.java", "license": "mit", "size": 274766 }
[ "org.ontoware.rdfreactor.runtime.Base" ]
import org.ontoware.rdfreactor.runtime.Base;
import org.ontoware.rdfreactor.runtime.*;
[ "org.ontoware.rdfreactor" ]
org.ontoware.rdfreactor;
2,809,770
public boolean containsRange(byte[] rangeStartKey, byte[] rangeEndKey) { if (Bytes.compareTo(rangeStartKey, rangeEndKey) > 0) { throw new IllegalArgumentException( "Invalid range: " + Bytes.toStringBinary(rangeStartKey) + " > " + Bytes.toStringBinary(rangeEndKey)); } boolean firstKeyInRange = Bytes.compareTo(rangeStartKey, startKey) >= 0; boolean lastKeyInRange = Bytes.compareTo(rangeEndKey, endKey) < 0 || Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY); return firstKeyInRange && lastKeyInRange; }
boolean function(byte[] rangeStartKey, byte[] rangeEndKey) { if (Bytes.compareTo(rangeStartKey, rangeEndKey) > 0) { throw new IllegalArgumentException( STR + Bytes.toStringBinary(rangeStartKey) + STR + Bytes.toStringBinary(rangeEndKey)); } boolean firstKeyInRange = Bytes.compareTo(rangeStartKey, startKey) >= 0; boolean lastKeyInRange = Bytes.compareTo(rangeEndKey, endKey) < 0 Bytes.equals(endKey, HConstants.EMPTY_BYTE_ARRAY); return firstKeyInRange && lastKeyInRange; }
/** * Returns true if the given inclusive range of rows is fully contained * by this region. For example, if the region is foo,a,g and this is * passed ["b","c"] or ["a","c"] it will return true, but if this is passed * ["b","z"] it will return false. * @throws IllegalArgumentException if the range passed is invalid (ie end < start) */
Returns true if the given inclusive range of rows is fully contained by this region. For example, if the region is foo,a,g and this is passed ["b","c"] or ["a","c"] it will return true, but if this is passed ["b","z"] it will return false
containsRange
{ "repo_name": "bcopeland/hbase-thrift", "path": "src/main/java/org/apache/hadoop/hbase/HRegionInfo.java", "license": "apache-2.0", "size": 23939 }
[ "org.apache.hadoop.hbase.util.Bytes" ]
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
1,488,780
public static Object unwrapAlways(TemplateModel templateModel) throws TemplateModelException { return DeepUnwrap.unwrap(templateModel); // will throw exception if improper type }
static Object function(TemplateModel templateModel) throws TemplateModelException { return DeepUnwrap.unwrap(templateModel); }
/** * Unwraps template model; if cannot, throws exception. * <p> * Interpretation of null depends on the ObjectWrapper. * <p> * NOTE: This automatically bypasses the auto-escaping done by wrappers implementing the <code>EscapingModel</code> interface * (such as Ofbiz special widget wrappers). */
Unwraps template model; if cannot, throws exception. Interpretation of null depends on the ObjectWrapper. (such as Ofbiz special widget wrappers)
unwrapAlways
{ "repo_name": "ilscipio/scipio-erp", "path": "framework/webapp/src/com/ilscipio/scipio/ce/webapp/ftl/lang/LangFtlUtil.java", "license": "apache-2.0", "size": 88244 }
[ "freemarker.template.TemplateModel", "freemarker.template.TemplateModelException", "freemarker.template.utility.DeepUnwrap" ]
import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; import freemarker.template.utility.DeepUnwrap;
import freemarker.template.*; import freemarker.template.utility.*;
[ "freemarker.template", "freemarker.template.utility" ]
freemarker.template; freemarker.template.utility;
1,629,890
public static void changeGetViewModel(String viewName, TypeDeclaration type) throws JavaModelException { JavaAstModelProducer jamp = JavaAstModelProducer.getInstance(); JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance(); // select method getViewModel() JavaAstMethodSignature signature = new JavaAstMethodSignature(GET_VIEW_MODEL); MethodDeclaration getViewModel = (MethodDeclaration) javaFactory.getJavaAstType().getMethod(type, signature); // change returnType TypeReference typeReference = jamp.createTypeReference(viewName + MODEL, false); getViewModel.returnType = typeReference; }
static void function(String viewName, TypeDeclaration type) throws JavaModelException { JavaAstModelProducer jamp = JavaAstModelProducer.getInstance(); JavaAstElementFactory javaFactory = JavaAstElementFactory.getInstance(); JavaAstMethodSignature signature = new JavaAstMethodSignature(GET_VIEW_MODEL); MethodDeclaration getViewModel = (MethodDeclaration) javaFactory.getJavaAstType().getMethod(type, signature); TypeReference typeReference = jamp.createTypeReference(viewName + MODEL, false); getViewModel.returnType = typeReference; }
/** * Changes the method getViewModel(). * * @param datatype * the name of the datatype. * @param type * the type declaration. * @throws JavaModelException * if an error occurred transforming the model. */
Changes the method getViewModel()
changeGetViewModel
{ "repo_name": "NABUCCO/org.nabucco.framework.generator", "path": "org.nabucco.framework.generator.compiler/src/main/org/nabucco/framework/generator/compiler/transformation/java/view/browsersupport/BrowserElementSupport.java", "license": "epl-1.0", "size": 18796 }
[ "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.TypeReference", "org.nabucco.framework.mda.model.java.JavaModelException", "org.nabucco.framework.mda.model.java.ast.element.JavaAstElementFactory", "org.nabucco.framework.mda.model.java.ast.element.method.JavaAstMethodSignature", "org.nabucco.framework.mda.model.java.ast.produce.JavaAstModelProducer" ]
import org.eclipse.jdt.internal.compiler.ast.MethodDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeDeclaration; import org.eclipse.jdt.internal.compiler.ast.TypeReference; import org.nabucco.framework.mda.model.java.JavaModelException; import org.nabucco.framework.mda.model.java.ast.element.JavaAstElementFactory; import org.nabucco.framework.mda.model.java.ast.element.method.JavaAstMethodSignature; import org.nabucco.framework.mda.model.java.ast.produce.JavaAstModelProducer;
import org.eclipse.jdt.internal.compiler.ast.*; import org.nabucco.framework.mda.model.java.*; import org.nabucco.framework.mda.model.java.ast.element.*; import org.nabucco.framework.mda.model.java.ast.element.method.*; import org.nabucco.framework.mda.model.java.ast.produce.*;
[ "org.eclipse.jdt", "org.nabucco.framework" ]
org.eclipse.jdt; org.nabucco.framework;
236,577
public void addViews(List<View> views) { addViews(views, false); }
void function(List<View> views) { addViews(views, false); }
/** * Adds a list of views to the roster of things to appear in the aggregate * list. * * @param views List of views to add */
Adds a list of views to the roster of things to appear in the aggregate list
addViews
{ "repo_name": "moreus/vMail", "path": "src/com/wii/vmail/ui/adapter/MergeAdapter.java", "license": "mit", "size": 9933 }
[ "android.view.View", "java.util.List" ]
import android.view.View; import java.util.List;
import android.view.*; import java.util.*;
[ "android.view", "java.util" ]
android.view; java.util;
1,693,500
public Expression and(String variable, BigDecimal value) { return setVariable(variable, value); }
Expression function(String variable, BigDecimal value) { return setVariable(variable, value); }
/** * Sets a variable value. * * @param variable * The variable to set. * @param value * The variable value. * @return The expression, allows to chain methods. */
Sets a variable value
and
{ "repo_name": "guanghaofan/SapphireProgramReader", "path": "SapphireProgramReader/src/sapphireprogramreader/com/udojava/evalex/Expression.java", "license": "gpl-2.0", "size": 33686 }
[ "java.math.BigDecimal" ]
import java.math.BigDecimal;
import java.math.*;
[ "java.math" ]
java.math;
2,221,064
public EditSelectedIndexAction getEditIndexAction() { return editIndexAction; }
EditSelectedIndexAction function() { return editIndexAction; }
/** * Returns the action that edits the index which is currently selected in * the DBTree. For PlayPen purposes, see {@link EditSpecificIndexAction}. */
Returns the action that edits the index which is currently selected in the DBTree. For PlayPen purposes, see <code>EditSpecificIndexAction</code>
getEditIndexAction
{ "repo_name": "SQLPower/power-architect", "path": "src/main/java/ca/sqlpower/architect/swingui/ArchitectFrame.java", "license": "gpl-3.0", "size": 75470 }
[ "ca.sqlpower.architect.swingui.action.EditSelectedIndexAction" ]
import ca.sqlpower.architect.swingui.action.EditSelectedIndexAction;
import ca.sqlpower.architect.swingui.action.*;
[ "ca.sqlpower.architect" ]
ca.sqlpower.architect;
1,465,269
public PutAllPRMessage createPRMessagesNotifyOnly(int bucketId) { final EntryEventImpl event = getEvent(); PutAllPRMessage prMsg = new PutAllPRMessage(bucketId, putAllDataSize, true, event.isPossibleDuplicate(), !event.isGenerateCallbacks(), this.txState, false, false ); if (event.getContext() != null) { prMsg.setBridgeContext(event.getContext()); } // will not recover event id here for (int i=0; i<putAllDataSize; i++) { prMsg.addEntry(putAllData[i]); } return prMsg; }
PutAllPRMessage function(int bucketId) { final EntryEventImpl event = getEvent(); PutAllPRMessage prMsg = new PutAllPRMessage(bucketId, putAllDataSize, true, event.isPossibleDuplicate(), !event.isGenerateCallbacks(), this.txState, false, false ); if (event.getContext() != null) { prMsg.setBridgeContext(event.getContext()); } for (int i=0; i<putAllDataSize; i++) { prMsg.addEntry(putAllData[i]); } return prMsg; }
/** * Create PutAllPRMessage for notify only (to adjunct nodes) * * @param bucketId * create message to send to this bucket * @return PutAllPRMessage */
Create PutAllPRMessage for notify only (to adjunct nodes)
createPRMessagesNotifyOnly
{ "repo_name": "papicella/snappy-store", "path": "gemfire-core/src/main/java/com/gemstone/gemfire/internal/cache/DistributedPutAllOperation.java", "license": "apache-2.0", "size": 48618 }
[ "com.gemstone.gemfire.internal.cache.partitioned.PutAllPRMessage" ]
import com.gemstone.gemfire.internal.cache.partitioned.PutAllPRMessage;
import com.gemstone.gemfire.internal.cache.partitioned.*;
[ "com.gemstone.gemfire" ]
com.gemstone.gemfire;
1,669,222
public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals(SAVE_DATA)) { if (saveDataCheckBox.isSelected()) { // they want to save data, so open a data file createFileWriter(); } else { // They don't want to save data anymore, so close the file. // The synchronized keyword prevents accidental access elsewhere // in the code while the file is being closed. Otherwise, other // code might try to write to the file while it is being closed. synchronized (this) { if (fileWriter != null) { fileWriter.close(); fileWriter = null; } } } } else if (command.equals(PLOT_ZERO_STATE)) { if (priceList != null && plotZeroStateCheckBox.isSelected()) { // they want the zero state to be plotted plotZeroState = true; priceList.addFirst((new Point2D.Double(0, marketValue[0]))); } else { // they don't want the zero state to be plotted plotZeroState = false; if (priceList.size() > 0) { priceList.removeFirst(); } } plotData(); } }
void function(ActionEvent e) { String command = e.getActionCommand(); if (command.equals(SAVE_DATA)) { if (saveDataCheckBox.isSelected()) { createFileWriter(); } else { synchronized (this) { if (fileWriter != null) { fileWriter.close(); fileWriter = null; } } } } else if (command.equals(PLOT_ZERO_STATE)) { if (priceList != null && plotZeroStateCheckBox.isSelected()) { plotZeroState = true; priceList.addFirst((new Point2D.Double(0, marketValue[0]))); } else { plotZeroState = false; if (priceList.size() > 0) { priceList.removeFirst(); } } plotData(); } }
/** * Reacts to the "save data" check box. */
Reacts to the "save data" check box
actionPerformed
{ "repo_name": "KEOpenSource/CAExplorer", "path": "cellularAutomata/analysis/PricingWealthAnalysis.java", "license": "apache-2.0", "size": 41038 }
[ "java.awt.event.ActionEvent", "java.awt.geom.Point2D" ]
import java.awt.event.ActionEvent; import java.awt.geom.Point2D;
import java.awt.event.*; import java.awt.geom.*;
[ "java.awt" ]
java.awt;
209,294
private void finishField(Field field) { if (field == null) return; switch (field.type) { case Field.FIELD_STRING: field.finalValue = field.textField.getText(); break; case Field.FIELD_SELECT: field.finalValue = field.combo.getSelectedItem(); break; case Field.FIELD_COLOR: Color newColor = parseColor(field); if (newColor == null) break; field.finalValue = newColor; break; } }
void function(Field field) { if (field == null) return; switch (field.type) { case Field.FIELD_STRING: field.finalValue = field.textField.getText(); break; case Field.FIELD_SELECT: field.finalValue = field.combo.getSelectedItem(); break; case Field.FIELD_COLOR: Color newColor = parseColor(field); if (newColor == null) break; field.finalValue = newColor; break; } }
/** * Method called to complete a field when the dialog closes. * @param field the field to process. */
Method called to complete a field when the dialog closes
finishField
{ "repo_name": "imr/Electric8", "path": "com/sun/electric/tool/user/dialogs/PromptAt.java", "license": "gpl-3.0", "size": 19002 }
[ "java.awt.Color" ]
import java.awt.Color;
import java.awt.*;
[ "java.awt" ]
java.awt;
1,622,867
public BufferedImage getEdgesImage() { return edgesImage; }
BufferedImage function() { return edgesImage; }
/** * Obtains an image containing the edges detected during the last call to * the process method. The buffered image is an opaque image of type * BufferedImage.TYPE_INT_ARGB in which edge pixels are white and all other * pixels are black. * * @return an image containing the detected edges, or null if the process * method has not yet been called. */
Obtains an image containing the edges detected during the last call to the process method. The buffered image is an opaque image of type BufferedImage.TYPE_INT_ARGB in which edge pixels are white and all other pixels are black
getEdgesImage
{ "repo_name": "tesseract4java/tesseract-gui", "path": "tools/src/main/java/de/vorb/tesseract/tools/preprocessing/CannyEdgeDetector.java", "license": "gpl-3.0", "size": 21839 }
[ "java.awt.image.BufferedImage" ]
import java.awt.image.BufferedImage;
import java.awt.image.*;
[ "java.awt" ]
java.awt;
973,060
public SingPType newInstance(Map<Integer,String> classIndexToValue);
SingPType function(Map<Integer,String> classIndexToValue);
/** * Generate a new instance of single run * performances. * * @param classIndexToValue map index to class value * @return new single run performances instance. */
Generate a new instance of single run performances
newInstance
{ "repo_name": "dcodecasa/CTBNCToolkit", "path": "CTBNCToolkit/performances/ISingleRunPerformancesFactory.java", "license": "bsd-3-clause", "size": 1237 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
148,975
public void addParkingSpot(Point center) { ParkingSpot spot = new ParkingSpot(center, this); this.parkingSpots.add(spot); }
void function(Point center) { ParkingSpot spot = new ParkingSpot(center, this); this.parkingSpots.add(spot); }
/** * Adds parking spot to parking region. * @param center */
Adds parking spot to parking region
addParkingSpot
{ "repo_name": "MUG-CSAIL/DeckViewer", "path": "src/edu/mit/kacquah/deckviewer/environment/ParkingRegion.java", "license": "mit", "size": 6965 }
[ "java.awt.Point" ]
import java.awt.Point;
import java.awt.*;
[ "java.awt" ]
java.awt;
828,761
protected void sequence_Optional(ISerializationContext context, Optional semanticObject) { genericSequencer.createSequence(context, semanticObject); }
void function(ISerializationContext context, Optional semanticObject) { genericSequencer.createSequence(context, semanticObject); }
/** * Contexts: * Optional returns Optional * * Constraint: * (int0=INT (int1=INT int2=INT)?) */
Contexts: Optional returns Optional Constraint: (int0=INT (int1=INT int2=INT)?)
sequence_Optional
{ "repo_name": "miklossy/xtext-core", "path": "org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/serializer/SequencerTestLanguageSemanticSequencer.java", "license": "epl-1.0", "size": 39304 }
[ "org.eclipse.xtext.serializer.ISerializationContext", "org.eclipse.xtext.serializer.sequencertest.Optional" ]
import org.eclipse.xtext.serializer.ISerializationContext; import org.eclipse.xtext.serializer.sequencertest.Optional;
import org.eclipse.xtext.serializer.*; import org.eclipse.xtext.serializer.sequencertest.*;
[ "org.eclipse.xtext" ]
org.eclipse.xtext;
1,688,688
void sendEmail( @NotBlank(message = "Cannot send email to blank address.") final String toEmail, @NotBlank(message = "Subject cannot be empty") final String subject, final String body ) throws GenieException;
void sendEmail( @NotBlank(message = STR) final String toEmail, @NotBlank(message = STR) final String subject, final String body ) throws GenieException;
/** * Method to send emails. * * @param toEmail The email address to send the email to. * @param subject The subject of the email. * @param body The body of the email * * @throws GenieException If there is any problem */
Method to send emails
sendEmail
{ "repo_name": "irontable/genie", "path": "genie-core/src/main/java/com/netflix/genie/core/services/MailService.java", "license": "apache-2.0", "size": 1505 }
[ "com.netflix.genie.common.exceptions.GenieException", "org.hibernate.validator.constraints.NotBlank" ]
import com.netflix.genie.common.exceptions.GenieException; import org.hibernate.validator.constraints.NotBlank;
import com.netflix.genie.common.exceptions.*; import org.hibernate.validator.constraints.*;
[ "com.netflix.genie", "org.hibernate.validator" ]
com.netflix.genie; org.hibernate.validator;
1,335,834
@Override public GatewayDiagnosticsStatus getDiagnosticsV2(String gatewayId) throws IOException, ServiceException, ParserConfigurationException, SAXException { // Validate if (gatewayId == null) { throw new NullPointerException("gatewayId"); } // Tracing boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put("gatewayId", gatewayId); CloudTracing.enter(invocationId, this, "getDiagnosticsV2Async", tracingParameters); } // Construct URL String url = ""; url = url + "/"; if (this.getClient().getCredentials().getSubscriptionId() != null) { url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8"); } url = url + "/services/networking/virtualnetworkgateways/"; url = url + URLEncoder.encode(gatewayId, "UTF-8"); url = url + "/publicdiagnostics"; String baseUrl = this.getClient().getBaseUri().toString(); // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl.charAt(baseUrl.length() - 1) == '/') { baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0); } if (url.charAt(0) == '/') { url = url.substring(1); } url = baseUrl + "/" + url; url = url.replace(" ", "%20"); // Create HTTP transport objects HttpGet httpRequest = new HttpGet(url); // Set Headers httpRequest.setHeader("x-ms-version", "2015-04-01"); // Send Request HttpResponse httpResponse = null; try { if (shouldTrace) { CloudTracing.sendRequest(invocationId, httpRequest); } httpResponse = this.getClient().getHttpClient().execute(httpRequest); if (shouldTrace) { CloudTracing.receiveResponse(invocationId, httpResponse); } int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse, httpResponse.getEntity()); if (shouldTrace) { CloudTracing.error(invocationId, ex); } throw ex; } // Create Result GatewayDiagnosticsStatus result = null; // Deserialize Response if (statusCode == HttpStatus.SC_OK) { InputStream responseContent = httpResponse.getEntity().getContent(); result = new GatewayDiagnosticsStatus(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent)); Element gatewayPublicDiagnosticsStatusElement = XmlUtility.getElementByTagNameNS(responseDoc, "http://schemas.microsoft.com/windowsazure", "GatewayPublicDiagnosticsStatus"); if (gatewayPublicDiagnosticsStatusElement != null) { Element stateElement = XmlUtility.getElementByTagNameNS(gatewayPublicDiagnosticsStatusElement, "http://schemas.microsoft.com/windowsazure", "State"); if (stateElement != null && stateElement.getTextContent() != null && !stateElement.getTextContent().isEmpty()) { GatewayDiagnosticsState stateInstance; stateInstance = GatewayDiagnosticsState.valueOf(stateElement.getTextContent().toUpperCase()); result.setState(stateInstance); } Element publicDiagnosticsUrlElement = XmlUtility.getElementByTagNameNS(gatewayPublicDiagnosticsStatusElement, "http://schemas.microsoft.com/windowsazure", "PublicDiagnosticsUrl"); if (publicDiagnosticsUrlElement != null) { String publicDiagnosticsUrlInstance; publicDiagnosticsUrlInstance = publicDiagnosticsUrlElement.getTextContent(); result.setDiagnosticsUrl(publicDiagnosticsUrlInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders("x-ms-request-id").length > 0) { result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
GatewayDiagnosticsStatus function(String gatewayId) throws IOException, ServiceException, ParserConfigurationException, SAXException { if (gatewayId == null) { throw new NullPointerException(STR); } boolean shouldTrace = CloudTracing.getIsEnabled(); String invocationId = null; if (shouldTrace) { invocationId = Long.toString(CloudTracing.getNextInvocationId()); HashMap<String, Object> tracingParameters = new HashMap<String, Object>(); tracingParameters.put(STR, gatewayId); CloudTracing.enter(invocationId, this, STR, tracingParameters); } String url = STR/STRUTF-8STR/services/networking/virtualnetworkgateways/STRUTF-8STR/publicdiagnosticsSTR/STR STR%20STRx-ms-versionSTR2015-04-01STRhttp: if (gatewayPublicDiagnosticsStatusElement != null) { Element stateElement = XmlUtility.getElementByTagNameNS(gatewayPublicDiagnosticsStatusElement, STRhttp: if (publicDiagnosticsUrlElement != null) { String publicDiagnosticsUrlInstance; publicDiagnosticsUrlInstance = publicDiagnosticsUrlElement.getTextContent(); result.setDiagnosticsUrl(publicDiagnosticsUrlInstance); } } } result.setStatusCode(statusCode); if (httpResponse.getHeaders(STR).length > 0) { result.setRequestId(httpResponse.getFirstHeader(STR).getValue()); } if (shouldTrace) { CloudTracing.exit(invocationId, result); } return result; } finally { if (httpResponse != null && httpResponse.getEntity() != null) { httpResponse.getEntity().getContent().close(); } } }
/** * The Get Diagnostics V2 operation gets information about the current * virtual network gateway diagnostics session * * @param gatewayId Required. The virtual network gateway Id. * @throws IOException Signals that an I/O exception of some sort has * occurred. This class is the general class of exceptions produced by * failed or interrupted I/O operations. * @throws ServiceException Thrown if an unexpected response is found. * @throws ParserConfigurationException Thrown if there was a serious * configuration error with the document parser. * @throws SAXException Thrown if there was an error parsing the XML * response. * @return The status of a gateway diagnostics operation. */
The Get Diagnostics V2 operation gets information about the current virtual network gateway diagnostics session
getDiagnosticsV2
{ "repo_name": "flydream2046/azure-sdk-for-java", "path": "service-management/azure-svc-mgmt-network/src/main/java/com/microsoft/windowsazure/management/network/GatewayOperationsImpl.java", "license": "apache-2.0", "size": 573643 }
[ "com.microsoft.windowsazure.core.utils.XmlUtility", "com.microsoft.windowsazure.exception.ServiceException", "com.microsoft.windowsazure.management.network.models.GatewayDiagnosticsStatus", "com.microsoft.windowsazure.tracing.CloudTracing", "java.io.IOException", "java.util.HashMap", "javax.xml.parsers.ParserConfigurationException", "org.w3c.dom.Element", "org.xml.sax.SAXException" ]
import com.microsoft.windowsazure.core.utils.XmlUtility; import com.microsoft.windowsazure.exception.ServiceException; import com.microsoft.windowsazure.management.network.models.GatewayDiagnosticsStatus; import com.microsoft.windowsazure.tracing.CloudTracing; import java.io.IOException; import java.util.HashMap; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Element; import org.xml.sax.SAXException;
import com.microsoft.windowsazure.core.utils.*; import com.microsoft.windowsazure.exception.*; import com.microsoft.windowsazure.management.network.models.*; import com.microsoft.windowsazure.tracing.*; import java.io.*; import java.util.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*;
[ "com.microsoft.windowsazure", "java.io", "java.util", "javax.xml", "org.w3c.dom", "org.xml.sax" ]
com.microsoft.windowsazure; java.io; java.util; javax.xml; org.w3c.dom; org.xml.sax;
1,499,593
public void setSoundOn(boolean on) { SoundStore.get().setSoundsOn(on); }
void function(boolean on) { SoundStore.get().setSoundsOn(on); }
/** * Indicate whether sound effects should be enabled * * @param on True if sound effects should be enabled */
Indicate whether sound effects should be enabled
setSoundOn
{ "repo_name": "yugecin/opsu", "path": "src/org/newdawn/slick/GameContainer.java", "license": "gpl-3.0", "size": 24426 }
[ "org.newdawn.slick.openal.SoundStore" ]
import org.newdawn.slick.openal.SoundStore;
import org.newdawn.slick.openal.*;
[ "org.newdawn.slick" ]
org.newdawn.slick;
1,501,931
public int getDecade() { if (this.fdoy > 360) { throw new ChronoException( "Complementary days (sansculottides) do not represent any decade: " + this.toString()); } return (((this.fdoy - 1) % 30) / 10) + 1; }
int function() { if (this.fdoy > 360) { throw new ChronoException( STR + this.toString()); } return (((this.fdoy - 1) % 30) / 10) + 1; }
/** * <p>Yields the decade of current republican month if available. </p> * * @return int (1, 2 or 3) * @throws ChronoException if this date is a complementary day * @see #DECADE_OF_MONTH * @see #hasSansculottides() * @see #hasMonth() */
Yields the decade of current republican month if available.
getDecade
{ "repo_name": "MenoData/Time4J", "path": "base/src/main/java/net/time4j/calendar/frenchrev/FrenchRepublicanCalendar.java", "license": "lgpl-2.1", "size": 89634 }
[ "net.time4j.engine.ChronoException" ]
import net.time4j.engine.ChronoException;
import net.time4j.engine.*;
[ "net.time4j.engine" ]
net.time4j.engine;
2,668,499
FeatureMap getMixed();
FeatureMap getMixed();
/** * Returns the value of the '<em><b>Mixed</b></em>' attribute list. * The list contents are of type {@link org.eclipse.emf.ecore.util.FeatureMap.Entry}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Mixed</em>' attribute list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Mixed</em>' attribute list. * @see org.oasis.xAL.XALPackage#getAddressLongitudeType_Mixed() * @model unique="false" dataType="org.eclipse.emf.ecore.EFeatureMapEntry" many="true" * extendedMetaData="kind='elementWildcard' name=':mixed'" * @generated */
Returns the value of the 'Mixed' attribute list. The list contents are of type <code>org.eclipse.emf.ecore.util.FeatureMap.Entry</code>. If the meaning of the 'Mixed' attribute list isn't clear, there really should be more of a description here...
getMixed
{ "repo_name": "markus1978/citygml4emf", "path": "de.hub.citygml.emf.ecore/src/org/oasis/xAL/AddressLongitudeType.java", "license": "apache-2.0", "size": 4067 }
[ "org.eclipse.emf.ecore.util.FeatureMap" ]
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
1,264,925
protected static void combineElementAnnotations(BasicElementConfig cfg, DefaultAnnotations.Builder builder) { if (cfg.name() != null) { builder.set(AnnotationKeys.NAME, cfg.name()); } if (cfg.uiType() != null) { builder.set(AnnotationKeys.UI_TYPE, cfg.uiType()); } if (cfg.locType() != null) { builder.set(AnnotationKeys.LOC_TYPE, cfg.locType()); } if (cfg.geoCoordsSet()) { builder.set(AnnotationKeys.LATITUDE, Double.toString(cfg.latitude())); builder.set(AnnotationKeys.LONGITUDE, Double.toString(cfg.longitude())); } else if (cfg.gridCoordsSet()) { builder.set(AnnotationKeys.GRID_Y, Double.toString(cfg.gridY())); builder.set(AnnotationKeys.GRID_X, Double.toString(cfg.gridX())); } if (cfg.rackAddress() != null) { builder.set(AnnotationKeys.RACK_ADDRESS, cfg.rackAddress()); } if (cfg.owner() != null) { builder.set(AnnotationKeys.OWNER, cfg.owner()); } }
static void function(BasicElementConfig cfg, DefaultAnnotations.Builder builder) { if (cfg.name() != null) { builder.set(AnnotationKeys.NAME, cfg.name()); } if (cfg.uiType() != null) { builder.set(AnnotationKeys.UI_TYPE, cfg.uiType()); } if (cfg.locType() != null) { builder.set(AnnotationKeys.LOC_TYPE, cfg.locType()); } if (cfg.geoCoordsSet()) { builder.set(AnnotationKeys.LATITUDE, Double.toString(cfg.latitude())); builder.set(AnnotationKeys.LONGITUDE, Double.toString(cfg.longitude())); } else if (cfg.gridCoordsSet()) { builder.set(AnnotationKeys.GRID_Y, Double.toString(cfg.gridY())); builder.set(AnnotationKeys.GRID_X, Double.toString(cfg.gridX())); } if (cfg.rackAddress() != null) { builder.set(AnnotationKeys.RACK_ADDRESS, cfg.rackAddress()); } if (cfg.owner() != null) { builder.set(AnnotationKeys.OWNER, cfg.owner()); } }
/** * Sets all defined values from the element config on the supplied * annotations builder. * * @param cfg element configuration * @param builder annotations builder */
Sets all defined values from the element config on the supplied annotations builder
combineElementAnnotations
{ "repo_name": "LorenzReinhart/ONOSnew", "path": "core/net/src/main/java/org/onosproject/net/device/impl/BasicElementOperator.java", "license": "apache-2.0", "size": 2345 }
[ "org.onosproject.net.AnnotationKeys", "org.onosproject.net.DefaultAnnotations", "org.onosproject.net.config.basics.BasicElementConfig" ]
import org.onosproject.net.AnnotationKeys; import org.onosproject.net.DefaultAnnotations; import org.onosproject.net.config.basics.BasicElementConfig;
import org.onosproject.net.*; import org.onosproject.net.config.basics.*;
[ "org.onosproject.net" ]
org.onosproject.net;
184,782
@SuppressWarnings("unchecked") public void showTextPopup(int x, int y) { final int pos = this.textArea.getCaretPosition(); this.textPopup.removeAll(); JMenuItem item = new JMenuItem("Position: " + pos); item.setEnabled(false); this.textPopup.add(item); FSNode posAnnot; if (this.isAnnotationIndex) { List<FSNode> annots = ((FSTreeModel) this.fsTree.getModel()).getFSs(); ArrayList<FSNode> selAnnots = getAnnotationsAtPos(pos, annots); for (int i = 0; i < selAnnots.size(); i++) { posAnnot = selAnnots.get(i); item = new JMenuItem("[" + posAnnot.getArrayPos() + "] = " + posAnnot.getType().getName()); item.addActionListener(new PopupHandler(this, posAnnot.getArrayPos())); this.textPopup.add(item); } } this.textPopup.show(this.textArea, x, y); }
@SuppressWarnings(STR) void function(int x, int y) { final int pos = this.textArea.getCaretPosition(); this.textPopup.removeAll(); JMenuItem item = new JMenuItem(STR + pos); item.setEnabled(false); this.textPopup.add(item); FSNode posAnnot; if (this.isAnnotationIndex) { List<FSNode> annots = ((FSTreeModel) this.fsTree.getModel()).getFSs(); ArrayList<FSNode> selAnnots = getAnnotationsAtPos(pos, annots); for (int i = 0; i < selAnnots.size(); i++) { posAnnot = selAnnots.get(i); item = new JMenuItem("[" + posAnnot.getArrayPos() + STR + posAnnot.getType().getName()); item.addActionListener(new PopupHandler(this, posAnnot.getArrayPos())); this.textPopup.add(item); } } this.textPopup.show(this.textArea, x, y); }
/** * Show text popup. * * @param x * the x * @param y * the y */
Show text popup
showTextPopup
{ "repo_name": "apache/uima-uimaj", "path": "uimaj-tools/src/main/java/org/apache/uima/tools/cvd/MainFrame.java", "license": "apache-2.0", "size": 89935 }
[ "java.util.ArrayList", "java.util.List", "javax.swing.JMenuItem", "org.apache.uima.tools.cvd.control.PopupHandler" ]
import java.util.ArrayList; import java.util.List; import javax.swing.JMenuItem; import org.apache.uima.tools.cvd.control.PopupHandler;
import java.util.*; import javax.swing.*; import org.apache.uima.tools.cvd.control.*;
[ "java.util", "javax.swing", "org.apache.uima" ]
java.util; javax.swing; org.apache.uima;
1,858,848
public List<URL> scanBundlesInClassSpace(String directory, String filePattern, boolean recursive) { Set<Bundle> bundlesInClassSpace = ClassPathUtil.getBundlesInClassSpace( bundleClassLoader.getBundle(), new HashSet<>()); List<URL> matching = new ArrayList<>(); for (Bundle bundle : bundlesInClassSpace) { @SuppressWarnings("rawtypes") Enumeration e = bundle.findEntries(directory, filePattern, recursive); if (e == null) { continue; } while (e.hasMoreElements()) { URL u = (URL) e.nextElement(); matching.add(u); } } return matching; }
List<URL> function(String directory, String filePattern, boolean recursive) { Set<Bundle> bundlesInClassSpace = ClassPathUtil.getBundlesInClassSpace( bundleClassLoader.getBundle(), new HashSet<>()); List<URL> matching = new ArrayList<>(); for (Bundle bundle : bundlesInClassSpace) { @SuppressWarnings(STR) Enumeration e = bundle.findEntries(directory, filePattern, recursive); if (e == null) { continue; } while (e.hasMoreElements()) { URL u = (URL) e.nextElement(); matching.add(u); } } return matching; }
/** * Scans the imported and required bundles for matching resources. Can be * used to obtain references to TLD files, XML definition files, etc. * * @param directory the directory within the imported/required bundle where to * perform the lookup (e.g. "META-INF/") * @param filePattern the file pattern to lookup (e.g. "*.tld") * @param recursive indicates whether the lookup should be recursive, i.e. if it * will drill into child directories * @return list of matching resources, URLs as returned by the framework's * {@link Bundle#findEntries(String, String, boolean)} method */
Scans the imported and required bundles for matching resources. Can be used to obtain references to TLD files, XML definition files, etc
scanBundlesInClassSpace
{ "repo_name": "lostiniceland/org.ops4j.pax.web", "path": "pax-web-jsp/src/main/java/org/ops4j/pax/web/jsp/JasperClassLoader.java", "license": "apache-2.0", "size": 7633 }
[ "java.util.ArrayList", "java.util.Enumeration", "java.util.HashSet", "java.util.List", "java.util.Set", "org.ops4j.pax.web.utils.ClassPathUtil", "org.osgi.framework.Bundle" ]
import java.util.ArrayList; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import org.ops4j.pax.web.utils.ClassPathUtil; import org.osgi.framework.Bundle;
import java.util.*; import org.ops4j.pax.web.utils.*; import org.osgi.framework.*;
[ "java.util", "org.ops4j.pax", "org.osgi.framework" ]
java.util; org.ops4j.pax; org.osgi.framework;
2,623,015
private List<SourceFile> findJavaScriptFiles(ResourceCollection rc) { List<SourceFile> files = Lists.newLinkedList(); Iterator<Resource> iter = rc.iterator(); while (iter.hasNext()) { FileResource fr = (FileResource) iter.next().as(FileResource.class); // Construct path to file, relative to current working directory. File file = Paths.get("") .toAbsolutePath() .relativize(fr.getFile().toPath()) .toFile(); files.add(SourceFile.fromFile(file, Charset.forName(encoding))); } return files; }
List<SourceFile> function(ResourceCollection rc) { List<SourceFile> files = Lists.newLinkedList(); Iterator<Resource> iter = rc.iterator(); while (iter.hasNext()) { FileResource fr = (FileResource) iter.next().as(FileResource.class); File file = Paths.get("") .toAbsolutePath() .relativize(fr.getFile().toPath()) .toFile(); files.add(SourceFile.fromFile(file, Charset.forName(encoding))); } return files; }
/** * Translates an Ant resource collection into the file list format that * the compiler expects. */
Translates an Ant resource collection into the file list format that the compiler expects
findJavaScriptFiles
{ "repo_name": "robbert/closure-compiler", "path": "src/com/google/javascript/jscomp/ant/CompileTask.java", "license": "apache-2.0", "size": 22384 }
[ "com.google.common.collect.Lists", "com.google.javascript.jscomp.SourceFile", "java.io.File", "java.nio.charset.Charset", "java.nio.file.Paths", "java.util.Iterator", "java.util.List", "org.apache.tools.ant.types.Resource", "org.apache.tools.ant.types.ResourceCollection", "org.apache.tools.ant.types.resources.FileResource" ]
import com.google.common.collect.Lists; import com.google.javascript.jscomp.SourceFile; import java.io.File; import java.nio.charset.Charset; import java.nio.file.Paths; import java.util.Iterator; import java.util.List; import org.apache.tools.ant.types.Resource; import org.apache.tools.ant.types.ResourceCollection; import org.apache.tools.ant.types.resources.FileResource;
import com.google.common.collect.*; import com.google.javascript.jscomp.*; import java.io.*; import java.nio.charset.*; import java.nio.file.*; import java.util.*; import org.apache.tools.ant.types.*; import org.apache.tools.ant.types.resources.*;
[ "com.google.common", "com.google.javascript", "java.io", "java.nio", "java.util", "org.apache.tools" ]
com.google.common; com.google.javascript; java.io; java.nio; java.util; org.apache.tools;
2,492,129
public void notifyClients() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyClients"); // We'll only fire events if eventing is enabled or depths are being monitored // (510343) if (isThresholdNotificationRequired()) { long totalItems = getTotalMsgCount(); synchronized (this) { if (wlmRemoved && ((_destLowMsgs == -1) || (totalItems <= _destLowMsgs))) { wlmRemoved = false; // Fire event fireDepthThresholdReachedEvent(getControlAdapter(), false, totalItems, _destLowMsgs); // Reached low } else if (!wlmRemoved && (_destHighMsgs != -1) && (_destLowMsgs != -1) && (totalItems >= _destHighMsgs)) { wlmRemoved = true; // Fire event fireDepthThresholdReachedEvent(getControlAdapter(), true, totalItems, _destHighMsgs); // Reached High } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyClients"); }
void function() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, STR); if (isThresholdNotificationRequired()) { long totalItems = getTotalMsgCount(); synchronized (this) { if (wlmRemoved && ((_destLowMsgs == -1) (totalItems <= _destLowMsgs))) { wlmRemoved = false; fireDepthThresholdReachedEvent(getControlAdapter(), false, totalItems, _destLowMsgs); } else if (!wlmRemoved && (_destHighMsgs != -1) && (_destLowMsgs != -1) && (totalItems >= _destHighMsgs)) { wlmRemoved = true; fireDepthThresholdReachedEvent(getControlAdapter(), true, totalItems, _destHighMsgs); } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, STR); }
/** * <p>This method fires an appropriate event if Notification * eventing is enabled. * * @return true if destination is advertised on WLM */
This method fires an appropriate event if Notification eventing is enabled
notifyClients
{ "repo_name": "OpenLiberty/open-liberty", "path": "dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/store/itemstreams/BaseMessageItemStream.java", "license": "epl-1.0", "size": 30744 }
[ "com.ibm.websphere.ras.TraceComponent", "com.ibm.ws.sib.utils.ras.SibTr" ]
import com.ibm.websphere.ras.TraceComponent; import com.ibm.ws.sib.utils.ras.SibTr;
import com.ibm.websphere.ras.*; import com.ibm.ws.sib.utils.ras.*;
[ "com.ibm.websphere", "com.ibm.ws" ]
com.ibm.websphere; com.ibm.ws;
664,661
public void setAdeCacheSettings(CmsADECacheSettings settings) { m_adeCacheSettings = settings; }
void function(CmsADECacheSettings settings) { m_adeCacheSettings = settings; }
/** * Sets the cache settings for ADE.<p> * * @param settings the cache settings for ADE */
Sets the cache settings for ADE
setAdeCacheSettings
{ "repo_name": "victos/opencms-core", "path": "src/org/opencms/configuration/CmsSystemConfiguration.java", "license": "lgpl-2.1", "size": 113156 }
[ "org.opencms.xml.containerpage.CmsADECacheSettings" ]
import org.opencms.xml.containerpage.CmsADECacheSettings;
import org.opencms.xml.containerpage.*;
[ "org.opencms.xml" ]
org.opencms.xml;
1,251,235
private long maybeResyncToNextLevel1Element(ExtractorInput input) throws EOFException, IOException, InterruptedException { while (true) { input.resetPeekPosition(); input.peekFully(scratch, 0, MAX_ID_BYTES); int varintLength = VarintReader.parseUnsignedVarintLength(scratch[0]); if (varintLength != -1 && varintLength <= MAX_ID_BYTES) { int potentialId = (int) VarintReader.assembleVarint(scratch, varintLength, false); if (output.isLevel1Element(potentialId)) { input.skipFully(varintLength); input.resetPeekPosition(); return potentialId; } } input.skipFully(1); } }
long function(ExtractorInput input) throws EOFException, IOException, InterruptedException { while (true) { input.resetPeekPosition(); input.peekFully(scratch, 0, MAX_ID_BYTES); int varintLength = VarintReader.parseUnsignedVarintLength(scratch[0]); if (varintLength != -1 && varintLength <= MAX_ID_BYTES) { int potentialId = (int) VarintReader.assembleVarint(scratch, varintLength, false); if (output.isLevel1Element(potentialId)) { input.skipFully(varintLength); input.resetPeekPosition(); return potentialId; } } input.skipFully(1); } }
/** * Does a byte by byte search to try and find the next level 1 element. This method is called if * some invalid data is encountered in the parser. * * @param input The {@link ExtractorInput} from which data has to be read. * @return id of the next level 1 element that has been found. * @throws EOFException If the end of input was encountered when searching for the next level 1 * element. * @throws IOException If an error occurs reading from the input. * @throws InterruptedException If the thread is interrupted. */
Does a byte by byte search to try and find the next level 1 element. This method is called if some invalid data is encountered in the parser
maybeResyncToNextLevel1Element
{ "repo_name": "ppamorim/ExoPlayer", "path": "library/src/main/java/com/google/android/exoplayer/extractor/webm/DefaultEbmlReader.java", "license": "apache-2.0", "size": 9212 }
[ "com.google.android.exoplayer.extractor.ExtractorInput", "java.io.EOFException", "java.io.IOException" ]
import com.google.android.exoplayer.extractor.ExtractorInput; import java.io.EOFException; import java.io.IOException;
import com.google.android.exoplayer.extractor.*; import java.io.*;
[ "com.google.android", "java.io" ]
com.google.android; java.io;
2,599,471
public NetworkProfile networkProfile() { return this.networkProfile; }
NetworkProfile function() { return this.networkProfile; }
/** * Get the networkProfile property: Specifies the network interfaces of the virtual machine. * * @return the networkProfile value. */
Get the networkProfile property: Specifies the network interfaces of the virtual machine
networkProfile
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanager/azure-resourcemanager-compute/src/main/java/com/azure/resourcemanager/compute/fluent/models/VirtualMachineScaleSetVMPropertiesInner.java", "license": "mit", "size": 20785 }
[ "com.azure.resourcemanager.compute.models.NetworkProfile" ]
import com.azure.resourcemanager.compute.models.NetworkProfile;
import com.azure.resourcemanager.compute.models.*;
[ "com.azure.resourcemanager" ]
com.azure.resourcemanager;
894,990
@Nullable public QueryIndexDescriptorImpl index(String name) { synchronized (idxMux) { return idxs.get(name); } }
@Nullable QueryIndexDescriptorImpl function(String name) { synchronized (idxMux) { return idxs.get(name); } }
/** * Get index by name. * * @param name Name. * @return Index. */
Get index by name
index
{ "repo_name": "mcherkasov/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/query/QueryTypeDescriptorImpl.java", "license": "apache-2.0", "size": 11181 }
[ "org.jetbrains.annotations.Nullable" ]
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.*;
[ "org.jetbrains.annotations" ]
org.jetbrains.annotations;
1,675,573
public static int generateRandomInteger(int aStart, int aEnd, Random aRandom) { if (aStart > aEnd) { throw new IllegalArgumentException("Start cannot exceed End."); } // get the range, casting to long to avoid overflow problems long range = (long) aEnd - (long) aStart + 1; // compute a fraction of the range, 0 <= frac < range long fraction = (long) (range * aRandom.nextDouble()); int randomNumber = (int) (fraction + aStart); return randomNumber; }
static int function(int aStart, int aEnd, Random aRandom) { if (aStart > aEnd) { throw new IllegalArgumentException(STR); } long range = (long) aEnd - (long) aStart + 1; long fraction = (long) (range * aRandom.nextDouble()); int randomNumber = (int) (fraction + aStart); return randomNumber; }
/** * Erzeugt eine Zufallszahl * * @param aStart * @param aEnd * @param aRandom * @return */
Erzeugt eine Zufallszahl
generateRandomInteger
{ "repo_name": "schakko/zabos", "path": "src/zabos/src/main/java/de/ecw/zabos/util/StringUtils.java", "license": "gpl-3.0", "size": 14285 }
[ "java.util.Random" ]
import java.util.Random;
import java.util.*;
[ "java.util" ]
java.util;
2,785,283
protected String getSqlFrom(final SelectFirstStatement stmt) { StringBuilder result = new StringBuilder("SELECT "); // Start by adding the field result.append(getSqlFrom(stmt.getFields().get(0))); appendFrom(result, stmt); appendJoins(result, stmt, innerJoinKeyword(stmt)); appendWhere(result, stmt); appendOrderBy(result, stmt); result.append(" LIMIT 0,1"); return result.toString().trim(); } /** * appends joins clauses to the result * * @param result joins will be appended here * @param stmt statement with joins clauses * @param innerJoinKeyword The keyword for INNER JOIN * @param <T> The type of {@link AbstractSelectStatement}
String function(final SelectFirstStatement stmt) { StringBuilder result = new StringBuilder(STR); result.append(getSqlFrom(stmt.getFields().get(0))); appendFrom(result, stmt); appendJoins(result, stmt, innerJoinKeyword(stmt)); appendWhere(result, stmt); appendOrderBy(result, stmt); result.append(STR); return result.toString().trim(); } /** * appends joins clauses to the result * * @param result joins will be appended here * @param stmt statement with joins clauses * @param innerJoinKeyword The keyword for INNER JOIN * @param <T> The type of {@link AbstractSelectStatement}
/** * Convert a {@link SelectFirstStatement} into SQL. This is the same format * used for H2, MySQL. Oracle and SqlServer implementation override this * function. * * @param stmt the select statement to generate SQL for * @return SQL string specific for database platform */
Convert a <code>SelectFirstStatement</code> into SQL. This is the same format used for H2, MySQL. Oracle and SqlServer implementation override this function
getSqlFrom
{ "repo_name": "badgerwithagun/morf", "path": "morf-core/src/main/java/org/alfasoftware/morf/jdbc/SqlDialect.java", "license": "apache-2.0", "size": 128834 }
[ "org.alfasoftware.morf.sql.AbstractSelectStatement", "org.alfasoftware.morf.sql.SelectFirstStatement" ]
import org.alfasoftware.morf.sql.AbstractSelectStatement; import org.alfasoftware.morf.sql.SelectFirstStatement;
import org.alfasoftware.morf.sql.*;
[ "org.alfasoftware.morf" ]
org.alfasoftware.morf;
75,027
protected double calculateHostAvgCpuUtilization(HostData host) { double avgCpuInUse = 0; int count = 0; for (HostStatus status : host.getHistory()) { // Only consider times when the host is powered ON. if (status.getState() == Host.HostState.ON) { avgCpuInUse += status.getResourcesInUse().getCpu(); ++count; } else break; } if (count != 0) { avgCpuInUse = avgCpuInUse / count; } return Utility.roundDouble(avgCpuInUse / host.getHostDescription().getResourceCapacity().getCpu()); }
double function(HostData host) { double avgCpuInUse = 0; int count = 0; for (HostStatus status : host.getHistory()) { if (status.getState() == Host.HostState.ON) { avgCpuInUse += status.getResourcesInUse().getCpu(); ++count; } else break; } if (count != 0) { avgCpuInUse = avgCpuInUse / count; } return Utility.roundDouble(avgCpuInUse / host.getHostDescription().getResourceCapacity().getCpu()); }
/** * Calculates Host's average CPU utilization over the last window of time. * * @return value in range [0,1] (i.e., percentage) */
Calculates Host's average CPU utilization over the last window of time
calculateHostAvgCpuUtilization
{ "repo_name": "digs-uwo/dcsim-projects", "path": "src/edu/uwo/csd/dcsim/projects/hierarchical/policies/RelocationPolicyLevel1.java", "license": "gpl-3.0", "size": 61150 }
[ "edu.uwo.csd.dcsim.common.Utility", "edu.uwo.csd.dcsim.host.Host", "edu.uwo.csd.dcsim.management.HostData", "edu.uwo.csd.dcsim.management.HostStatus" ]
import edu.uwo.csd.dcsim.common.Utility; import edu.uwo.csd.dcsim.host.Host; import edu.uwo.csd.dcsim.management.HostData; import edu.uwo.csd.dcsim.management.HostStatus;
import edu.uwo.csd.dcsim.common.*; import edu.uwo.csd.dcsim.host.*; import edu.uwo.csd.dcsim.management.*;
[ "edu.uwo.csd" ]
edu.uwo.csd;
2,399,968
@Override public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; }
List<IItemPropertyDescriptor> function(Object object) { if (itemPropertyDescriptors == null) { super.getPropertyDescriptors(object); } return itemPropertyDescriptors; }
/** * This returns the property descriptors for the adapted class. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */
This returns the property descriptors for the adapted class.
getPropertyDescriptors
{ "repo_name": "aciancone/klapersuite", "path": "klapersuite.metamodel.lqn.edit/src/lqn/provider/PrecedenceItemProvider.java", "license": "epl-1.0", "size": 7132 }
[ "java.util.List", "org.eclipse.emf.edit.provider.IItemPropertyDescriptor" ]
import java.util.List; import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import java.util.*; import org.eclipse.emf.edit.provider.*;
[ "java.util", "org.eclipse.emf" ]
java.util; org.eclipse.emf;
2,122,199
public void translate(ClassGenerator classGen, MethodGenerator methodGen) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); // Returns the string value for a node in the DOM final int getNamespace = cpg.addInterfaceMethodref(DOM_INTF, "getNamespaceName", "(I)"+STRING_SIG); super.translate(classGen, methodGen); il.append(new INVOKEINTERFACE(getNamespace, 2)); }
void function(ClassGenerator classGen, MethodGenerator methodGen) { final ConstantPoolGen cpg = classGen.getConstantPool(); final InstructionList il = methodGen.getInstructionList(); final int getNamespace = cpg.addInterfaceMethodref(DOM_INTF, STR, "(I)"+STRING_SIG); super.translate(classGen, methodGen); il.append(new INVOKEINTERFACE(getNamespace, 2)); }
/** * Translate code that leaves a node's namespace URI (as a String) * on the stack */
Translate code that leaves a node's namespace URI (as a String) on the stack
translate
{ "repo_name": "YouDiSN/OpenJDK-Research", "path": "jdk9/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/NamespaceUriCall.java", "license": "gpl-2.0", "size": 2474 }
[ "com.sun.org.apache.bcel.internal.generic.ConstantPoolGen", "com.sun.org.apache.bcel.internal.generic.InstructionList", "com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator", "com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator" ]
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen; import com.sun.org.apache.bcel.internal.generic.InstructionList; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.bcel.internal.generic.*; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.*;
[ "com.sun.org" ]
com.sun.org;
846,785
public PageImpl1<T> setItems(List<T> items) { this.items = items; return this; }
PageImpl1<T> function(List<T> items) { this.items = items; return this; }
/** * Sets the list of items. * * @param items the list of items in {@link List}. * @return this Page object itself. */
Sets the list of items
setItems
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/implementation/PageImpl1.java", "license": "mit", "size": 1752 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
1,484,509
protected T createResult() throws ContentCreationException { return createResult(resultType); }
T function() throws ContentCreationException { return createResult(resultType); }
/** * Creates a new result object instance using the result type passed to * the constructor. This form can be used by subclasses where the result * type is a concrete implementation class. * * @return result instance * @throws ContentCreationException */
Creates a new result object instance using the result type passed to the constructor. This form can be used by subclasses where the result type is a concrete implementation class
createResult
{ "repo_name": "simonrrr/gdata-java-client", "path": "java/src/com/google/gdata/wireformats/input/AbstractParser.java", "license": "apache-2.0", "size": 3313 }
[ "com.google.gdata.wireformats.ContentCreationException" ]
import com.google.gdata.wireformats.ContentCreationException;
import com.google.gdata.wireformats.*;
[ "com.google.gdata" ]
com.google.gdata;
482,368
@Override public int updateValue(Long key, Serializable value) { // Remove all entries for the root PropertyRootEntity entity = getPropertyRoot(key); if (entity == null) { throw new DataIntegrityViolationException("No property root exists for ID " + key); } // Remove all links using the root deletePropertyLinks(key); // Create the new properties and update the cache createPropertyImpl(key, 0L, 0L, null, value); // Update the property root to detect concurrent modification updatePropertyRoot(entity); // Done if (logger.isDebugEnabled()) { logger.debug( "Updated property: \n" + " ID: " + key + "\n" + " Value: " + value); } return 1; }
int function(Long key, Serializable value) { PropertyRootEntity entity = getPropertyRoot(key); if (entity == null) { throw new DataIntegrityViolationException(STR + key); } deletePropertyLinks(key); createPropertyImpl(key, 0L, 0L, null, value); updatePropertyRoot(entity); if (logger.isDebugEnabled()) { logger.debug( STR + STR + key + "\n" + STR + value); } return 1; }
/** * Updates a property. The <b>alf_prop_root</b> entity is updated * to ensure concurrent modification is detected. * * @return Returns 1 always */
Updates a property. The alf_prop_root entity is updated to ensure concurrent modification is detected
updateValue
{ "repo_name": "Alfresco/alfresco-repository", "path": "src/main/java/org/alfresco/repo/domain/propval/AbstractPropertyValueDAOImpl.java", "license": "lgpl-3.0", "size": 62653 }
[ "java.io.Serializable", "org.springframework.dao.DataIntegrityViolationException" ]
import java.io.Serializable; import org.springframework.dao.DataIntegrityViolationException;
import java.io.*; import org.springframework.dao.*;
[ "java.io", "org.springframework.dao" ]
java.io; org.springframework.dao;
220,823
public void tick() { if (Core.getServer().getThread().isServerThread() == false) { throw new RuntimeException("ActionQueue should only be ticked on the Server thread."); } synchronized (queue) { if (getOwner().isLoaded() == false) { //We should not process mobs which are not loaded. return; } if (getOwner().isDestroyed()) { //We cannot be processed, our owner is destroyed. return; } if (queue.isEmpty()) { getOwner().onIdle(); return; } Action w = queue.getFirst(); try { w.tick(); //W will end itself when its done. } catch (Exception e) { //Our task failed to work properly. queue.remove(w); //Threw an exception, don't trust it again. Log.warning("Error ticking ActionQueue for Mob " + owner + ". Action: " + w); e.printStackTrace(); } //We do not know if we will finish, so we queue again anyway. this.queue(); } }
void function() { if (Core.getServer().getThread().isServerThread() == false) { throw new RuntimeException(STR); } synchronized (queue) { if (getOwner().isLoaded() == false) { return; } if (getOwner().isDestroyed()) { return; } if (queue.isEmpty()) { getOwner().onIdle(); return; } Action w = queue.getFirst(); try { w.tick(); } catch (Exception e) { queue.remove(w); Log.warning(STR + owner + STR + w); e.printStackTrace(); } this.queue(); } }
/** * Ticks this ActionQueue, processing any elements required. * @return */
Ticks this ActionQueue, processing any elements required
tick
{ "repo_name": "tehnewb/Titan", "path": "src/org/maxgamer/rs/model/action/ActionQueue.java", "license": "gpl-3.0", "size": 13230 }
[ "org.maxgamer.rs.core.Core", "org.maxgamer.rs.lib.log.Log" ]
import org.maxgamer.rs.core.Core; import org.maxgamer.rs.lib.log.Log;
import org.maxgamer.rs.core.*; import org.maxgamer.rs.lib.log.*;
[ "org.maxgamer.rs" ]
org.maxgamer.rs;
2,409,083
public static final void shuffle(ArrayList arr) { Collections.shuffle(arr); }
static final void function(ArrayList arr) { Collections.shuffle(arr); }
/** * Java shuffle * @param arr */
Java shuffle
shuffle
{ "repo_name": "ffalchi/it.cnr.isti.vir", "path": "src/it/cnr/isti/vir/util/RandomOperations.java", "license": "bsd-2-clause", "size": 13191 }
[ "java.util.ArrayList", "java.util.Collections" ]
import java.util.ArrayList; import java.util.Collections;
import java.util.*;
[ "java.util" ]
java.util;
1,783,883
@Override public Future<String> echo2(String msg) { final FutureTask<String> futureTask = new FutureTask<String>(() -> msg); futureTask.run(); // can be submit to an Executor return futureTask; }
Future<String> function(String msg) { final FutureTask<String> futureTask = new FutureTask<String>(() -> msg); futureTask.run(); return futureTask; }
/** * But Java 1.4 Future interface can be used as well. */
But Java 1.4 Future interface can be used as well
echo2
{ "repo_name": "frankfenghua/asyncrmi", "path": "example/src/main/java/org/async/example/futures/FutureExampleServer.java", "license": "apache-2.0", "size": 2671 }
[ "java.util.concurrent.Future", "java.util.concurrent.FutureTask" ]
import java.util.concurrent.Future; import java.util.concurrent.FutureTask;
import java.util.concurrent.*;
[ "java.util" ]
java.util;
764,953
public void setFeedItemFlattrStatus(FeedItem feedItem) { ContentValues values = new ContentValues(); values.put(KEY_FLATTR_STATUS, feedItem.getFlattrStatus().toLong()); db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?", new String[]{String.valueOf(feedItem.getId())}); }
void function(FeedItem feedItem) { ContentValues values = new ContentValues(); values.put(KEY_FLATTR_STATUS, feedItem.getFlattrStatus().toLong()); db.update(TABLE_NAME_FEED_ITEMS, values, KEY_ID + "=?", new String[]{String.valueOf(feedItem.getId())}); }
/** * Update the flattr status of a FeedItem */
Update the flattr status of a FeedItem
setFeedItemFlattrStatus
{ "repo_name": "domingos86/AntennaPod", "path": "core/src/main/java/de/danoeh/antennapod/core/storage/PodDBAdapter.java", "license": "mit", "size": 89050 }
[ "android.content.ContentValues", "de.danoeh.antennapod.core.feed.FeedItem" ]
import android.content.ContentValues; import de.danoeh.antennapod.core.feed.FeedItem;
import android.content.*; import de.danoeh.antennapod.core.feed.*;
[ "android.content", "de.danoeh.antennapod" ]
android.content; de.danoeh.antennapod;
623,639
@Test public void testEmptyFileChecksums() throws Throwable { assumeNoDefaultEncryption(); final S3AFileSystem fs = getFileSystem(); Path file1 = touchFile("file1"); EtagChecksum checksum1 = fs.getFileChecksum(file1, 0); LOG.info("Checksum for {}: {}", file1, checksum1); assertHasPathCapabilities(fs, file1, CommonPathCapabilities.FS_CHECKSUMS); assertNotNull("Null file 1 checksum", checksum1); assertNotEquals("file 1 checksum", 0, checksum1.getLength()); assertEquals("checksums of empty files", checksum1, fs.getFileChecksum(touchFile("file2"), 0)); Assertions.assertThat(fs.getXAttr(file1, XA_ETAG)) .describedAs("etag from xattr") .isEqualTo(checksum1.getBytes()); }
void function() throws Throwable { assumeNoDefaultEncryption(); final S3AFileSystem fs = getFileSystem(); Path file1 = touchFile("file1"); EtagChecksum checksum1 = fs.getFileChecksum(file1, 0); LOG.info(STR, file1, checksum1); assertHasPathCapabilities(fs, file1, CommonPathCapabilities.FS_CHECKSUMS); assertNotNull(STR, checksum1); assertNotEquals(STR, 0, checksum1.getLength()); assertEquals(STR, checksum1, fs.getFileChecksum(touchFile("file2"), 0)); Assertions.assertThat(fs.getXAttr(file1, XA_ETAG)) .describedAs(STR) .isEqualTo(checksum1.getBytes()); }
/** * The assumption here is that 0-byte files uploaded in a single PUT * always have the same checksum, including stores with encryption. * This will be skipped if the bucket has S3 default encryption enabled. * @throws Throwable on a failure */
The assumption here is that 0-byte files uploaded in a single PUT always have the same checksum, including stores with encryption. This will be skipped if the bucket has S3 default encryption enabled
testEmptyFileChecksums
{ "repo_name": "nandakumar131/hadoop", "path": "hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestS3AMiscOperations.java", "license": "apache-2.0", "size": 15038 }
[ "org.apache.hadoop.fs.CommonPathCapabilities", "org.apache.hadoop.fs.Path", "org.apache.hadoop.fs.contract.ContractTestUtils", "org.apache.hadoop.fs.store.EtagChecksum", "org.assertj.core.api.Assertions" ]
import org.apache.hadoop.fs.CommonPathCapabilities; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.contract.ContractTestUtils; import org.apache.hadoop.fs.store.EtagChecksum; import org.assertj.core.api.Assertions;
import org.apache.hadoop.fs.*; import org.apache.hadoop.fs.contract.*; import org.apache.hadoop.fs.store.*; import org.assertj.core.api.*;
[ "org.apache.hadoop", "org.assertj.core" ]
org.apache.hadoop; org.assertj.core;
2,537,026
public Value link(DataHandler handler, int tableId) { return this; }
Value function(DataHandler handler, int tableId) { return this; }
/** * Link a large value to a given table. For values that are kept fully in * memory this method has no effect. * * @param handler the data handler * @param tableId the table to link to * @return the new value or itself */
Link a large value to a given table. For values that are kept fully in memory this method has no effect
link
{ "repo_name": "vdr007/ThriftyPaxos", "path": "src/applications/h2/src/main/org/h2/value/Value.java", "license": "apache-2.0", "size": 36344 }
[ "org.h2.store.DataHandler" ]
import org.h2.store.DataHandler;
import org.h2.store.*;
[ "org.h2.store" ]
org.h2.store;
322,913
public void narediCsv(String naslovDirektorija, List<String> zbirke) throws IOException{ String osName = System.getProperty("os.name"); for (String zbirka : zbirke){ String fileName = null; if (osName.equals("Linux") || osName.equals("Mac OS X")){ fileName = naslovDirektorija+"/"+zbirka+".csv"; } else if (osName.equals("Windows")){ fileName = naslovDirektorija+"\\"+zbirka+".csv"; } File f = new File(fileName); if (f.exists() && !f.isDirectory()){ f.delete(); } FileWriter writer = new FileWriter(fileName); Map<Integer, Map<String, String>> izbranaZbirka = SqlManager.beriZbirkoPodatki(zbirka); int stevilo_stolpcev = SqlManager.beriZbirkoStolpci(zbirka).size(); int n = 0; for (String stolpec : SqlManager.beriZbirkoStolpci(zbirka)){ writer.append(stolpec); n++; if (n < stevilo_stolpcev){ writer.append(","); } } writer.append("\n"); n = 0; for (int i : izbranaZbirka.keySet()){ Map<String, String> element = izbranaZbirka.get(i); for (String stolpec : SqlManager.beriZbirkoStolpci(zbirka)){ writer.append(element.get(stolpec)); n++; if (n < stevilo_stolpcev){ writer.append(","); } } writer.append("\n"); n = 0; } writer.flush(); writer.close(); } }
void function(String naslovDirektorija, List<String> zbirke) throws IOException{ String osName = System.getProperty(STR); for (String zbirka : zbirke){ String fileName = null; if (osName.equals("Linux") osName.equals(STR)){ fileName = naslovDirektorija+"/"+zbirka+".csv"; } else if (osName.equals(STR)){ fileName = naslovDirektorija+"\\"+zbirka+".csv"; } File f = new File(fileName); if (f.exists() && !f.isDirectory()){ f.delete(); } FileWriter writer = new FileWriter(fileName); Map<Integer, Map<String, String>> izbranaZbirka = SqlManager.beriZbirkoPodatki(zbirka); int stevilo_stolpcev = SqlManager.beriZbirkoStolpci(zbirka).size(); int n = 0; for (String stolpec : SqlManager.beriZbirkoStolpci(zbirka)){ writer.append(stolpec); n++; if (n < stevilo_stolpcev){ writer.append(","); } } writer.append("\n"); n = 0; for (int i : izbranaZbirka.keySet()){ Map<String, String> element = izbranaZbirka.get(i); for (String stolpec : SqlManager.beriZbirkoStolpci(zbirka)){ writer.append(element.get(stolpec)); n++; if (n < stevilo_stolpcev){ writer.append(","); } } writer.append("\n"); n = 0; } writer.flush(); writer.close(); } }
/** * Naredi CSV datoteko izbrane zbirke v izbran direktorij. * @param naslovDirektorija * @param zbirke * @throws IOException */
Naredi CSV datoteko izbrane zbirke v izbran direktorij
narediCsv
{ "repo_name": "campovski/zbiratelj", "path": "Zbiratelj/src/io/CsvManager.java", "license": "mit", "size": 2784 }
[ "java.io.File", "java.io.FileWriter", "java.io.IOException", "java.util.List", "java.util.Map" ]
import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import java.util.Map;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
2,284,439
public ScriptNode cancelCheckout() { NodeRef original = this.services.getCheckOutCheckInService().cancelCheckout(this.nodeRef); return newInstance(original, this.services, this.scope); } // ------------------------------------------------------------------------------ // Transformation and Rendering API
ScriptNode function() { NodeRef original = this.services.getCheckOutCheckInService().cancelCheckout(this.nodeRef); return newInstance(original, this.services, this.scope); }
/** * Cancel the check-out of a working copy document. The working copy will be deleted and any changes made to it * are lost. Note that this method can only be called on a working copy Node. The reference to this working copy * Node should be discarded. * * @return the original Node that was checked out. */
Cancel the check-out of a working copy document. The working copy will be deleted and any changes made to it are lost. Note that this method can only be called on a working copy Node. The reference to this working copy Node should be discarded
cancelCheckout
{ "repo_name": "nguyentienlong/community-edition", "path": "projects/repository/source/java/org/alfresco/repo/jscript/ScriptNode.java", "license": "lgpl-3.0", "size": 153865 }
[ "org.alfresco.service.cmr.repository.NodeRef" ]
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.*;
[ "org.alfresco.service" ]
org.alfresco.service;
1,281,845
private void stopResources(boolean waitForShutdown) throws InterruptedException { emitter.stop(); emitterThread.interrupt(); executor.shutdown(); if (waitForShutdown) { try { if (!executor.awaitTermination(365L, TimeUnit.DAYS)) { executor.shutdownNow(); } } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); } if (Thread.holdsLock(checkpointingLock)) { while (emitterThread.isAlive()) { checkpointingLock.wait(100L); } } emitterThread.join(); } else { executor.shutdownNow(); } }
void function(boolean waitForShutdown) throws InterruptedException { emitter.stop(); emitterThread.interrupt(); executor.shutdown(); if (waitForShutdown) { try { if (!executor.awaitTermination(365L, TimeUnit.DAYS)) { executor.shutdownNow(); } } catch (InterruptedException e) { executor.shutdownNow(); Thread.currentThread().interrupt(); } if (Thread.holdsLock(checkpointingLock)) { while (emitterThread.isAlive()) { checkpointingLock.wait(100L); } } emitterThread.join(); } else { executor.shutdownNow(); } }
/** * Close the operator's resources. They include the emitter thread and the executor to run * the queue's complete operation. * * @param waitForShutdown is true if the method should wait for the resources to be freed; * otherwise false. * @throws InterruptedException if current thread has been interrupted */
Close the operator's resources. They include the emitter thread and the executor to run the queue's complete operation
stopResources
{ "repo_name": "DieBauer/flink", "path": "flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/async/AsyncWaitOperator.java", "license": "apache-2.0", "size": 14826 }
[ "java.util.concurrent.TimeUnit" ]
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
[ "java.util" ]
java.util;
2,460,373
boolean visit(ISigilBundle bundle);
boolean visit(ISigilBundle bundle);
/** * Visit the next bundle in the repository. * Return true if should continue visiting other bundles, false otherwise. * @param bundle * @return */
Visit the next bundle in the repository. Return true if should continue visiting other bundles, false otherwise
visit
{ "repo_name": "boneman1231/org.apache.felix", "path": "trunk/sigil/common/core/src/org/apache/felix/sigil/common/repository/IRepositoryVisitor.java", "license": "apache-2.0", "size": 1188 }
[ "org.apache.felix.sigil.common.model.eclipse.ISigilBundle" ]
import org.apache.felix.sigil.common.model.eclipse.ISigilBundle;
import org.apache.felix.sigil.common.model.eclipse.*;
[ "org.apache.felix" ]
org.apache.felix;
2,580,806
public static IgfsDirectoryInfo createDirectory(IgniteUuid id) { return createDirectory(id, null, null); }
static IgfsDirectoryInfo function(IgniteUuid id) { return createDirectory(id, null, null); }
/** * Create empty directory with the given ID. * * @param id ID. * @return File info. */
Create empty directory with the given ID
createDirectory
{ "repo_name": "f7753/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/processors/igfs/IgfsUtils.java", "license": "apache-2.0", "size": 25218 }
[ "org.apache.ignite.lang.IgniteUuid" ]
import org.apache.ignite.lang.IgniteUuid;
import org.apache.ignite.lang.*;
[ "org.apache.ignite" ]
org.apache.ignite;
2,451,985
public void execute() { try { executeCommand(); } catch (Throwable t) { handleFailure(t); final LinkedList<Command> oldSeq = seq; stripSubCommands(); seq = oldSeq; } for (Command cmd : seq) { try { cmd.execute(); } catch (Throwable t) { handleFailure(t); } } }
void function() { try { executeCommand(); } catch (Throwable t) { handleFailure(t); final LinkedList<Command> oldSeq = seq; stripSubCommands(); seq = oldSeq; } for (Command cmd : seq) { try { cmd.execute(); } catch (Throwable t) { handleFailure(t); } } }
/** * Execute this command by first invoking {@link #executeCommand}, then * invoking {@link #execute} recursively on all subcommands. */
Execute this command by first invoking <code>#executeCommand</code>, then invoking <code>#execute</code> recursively on all subcommands
execute
{ "repo_name": "caiusb/vassal", "path": "src/VASSAL/command/Command.java", "license": "lgpl-2.1", "size": 4659 }
[ "java.util.LinkedList" ]
import java.util.LinkedList;
import java.util.*;
[ "java.util" ]
java.util;
798,224
public int fileExists(SrvSession sess, TreeConnection tree, String name) { return LiferayStorage.fileExists(getLiferayFullPath(name)); }
int function(SrvSession sess, TreeConnection tree, String name) { return LiferayStorage.fileExists(getLiferayFullPath(name)); }
/** * Check if a file or directory exists in the Liferay-based share. * This method is called by JLAN when the SBM client checks file existance. * @param sess Session details * @param tree Tree connection * @param name Full file name starting with a backslash relative to share root * @return FileStatus.DirectoryExists if a directory with such a name exists, * FileStatus.FileExists if a file with such a name exists, * or FileStatus.NotExist otherwise */
Check if a file or directory exists in the Liferay-based share. This method is called by JLAN when the SBM client checks file existance
fileExists
{ "repo_name": "arcusys/Liferay-CIFS", "path": "source/java/com/arcusys/liferay/smb/DocumentLibraryDiskDriver.java", "license": "gpl-3.0", "size": 14719 }
[ "org.alfresco.jlan.server.SrvSession", "org.alfresco.jlan.server.filesys.TreeConnection" ]
import org.alfresco.jlan.server.SrvSession; import org.alfresco.jlan.server.filesys.TreeConnection;
import org.alfresco.jlan.server.*; import org.alfresco.jlan.server.filesys.*;
[ "org.alfresco.jlan" ]
org.alfresco.jlan;
1,787,700
protected ResourceLocation getEntityTexture(Entity par1Entity) { return loc; }
ResourceLocation function(Entity par1Entity) { return loc; }
/** * Returns the location of an entity's texture. Doesn't seem to be called * unless you call Render.bindEntityTexture. */
Returns the location of an entity's texture. Doesn't seem to be called unless you call Render.bindEntityTexture
getEntityTexture
{ "repo_name": "thvardhan/Youtuber-s-Lucky-Blocks", "path": "src/main/java/thvardhan/ytluckyblocks/entity/render/EntityStampylongheadRender.java", "license": "gpl-3.0", "size": 1760 }
[ "net.minecraft.entity.Entity", "net.minecraft.util.ResourceLocation" ]
import net.minecraft.entity.Entity; import net.minecraft.util.ResourceLocation;
import net.minecraft.entity.*; import net.minecraft.util.*;
[ "net.minecraft.entity", "net.minecraft.util" ]
net.minecraft.entity; net.minecraft.util;
2,446,294
@Test public void testMicroaggregationAdult() throws IOException { Data data = getDataObject("./data/adult.csv"); data.getDefinition().setAttributeType("age", MicroAggregationFunction.createArithmeticMean()); data.getDefinition().setDataType("age", DataType.INTEGER); final ARXAnonymizer anonymizer = new ARXAnonymizer(); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(5)); config.setMaxOutliers(1d); config.setMetric(Metric.createLossMetric(AggregateFunction.RANK)); ARXResult result = anonymizer.anonymize(data, config); DataHandle exptectedOutput = Data.create("./data/adult_age_microaggregated.csv", StandardCharsets.UTF_8, ';').getHandle(); DataHandle output = result.getOutput(); for (int i = 0; i < output.getNumRows(); i++) { for (int j = 0; j < output.getNumColumns(); j++) { assertEquals(exptectedOutput.getValue(i, j), output.getValue(i, j)); } } }
void function() throws IOException { Data data = getDataObject(STR); data.getDefinition().setAttributeType("age", MicroAggregationFunction.createArithmeticMean()); data.getDefinition().setDataType("age", DataType.INTEGER); final ARXAnonymizer anonymizer = new ARXAnonymizer(); final ARXConfiguration config = ARXConfiguration.create(); config.addCriterion(new KAnonymity(5)); config.setMaxOutliers(1d); config.setMetric(Metric.createLossMetric(AggregateFunction.RANK)); ARXResult result = anonymizer.anonymize(data, config); DataHandle exptectedOutput = Data.create(STR, StandardCharsets.UTF_8, ';').getHandle(); DataHandle output = result.getOutput(); for (int i = 0; i < output.getNumRows(); i++) { for (int j = 0; j < output.getNumColumns(); j++) { assertEquals(exptectedOutput.getValue(i, j), output.getValue(i, j)); } } }
/** * Test microaggregation arithmetic mean with larger dataset * @throws IOException */
Test microaggregation arithmetic mean with larger dataset
testMicroaggregationAdult
{ "repo_name": "fstahnke/arx", "path": "src/test/org/deidentifier/arx/test/TestMicroaggregation.java", "license": "apache-2.0", "size": 8203 }
[ "java.io.IOException", "java.nio.charset.StandardCharsets", "org.deidentifier.arx.ARXAnonymizer", "org.deidentifier.arx.ARXConfiguration", "org.deidentifier.arx.ARXResult", "org.deidentifier.arx.AttributeType", "org.deidentifier.arx.Data", "org.deidentifier.arx.DataHandle", "org.deidentifier.arx.DataType", "org.deidentifier.arx.criteria.KAnonymity", "org.deidentifier.arx.metric.Metric", "org.junit.Assert" ]
import java.io.IOException; import java.nio.charset.StandardCharsets; import org.deidentifier.arx.ARXAnonymizer; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.ARXResult; import org.deidentifier.arx.AttributeType; import org.deidentifier.arx.Data; import org.deidentifier.arx.DataHandle; import org.deidentifier.arx.DataType; import org.deidentifier.arx.criteria.KAnonymity; import org.deidentifier.arx.metric.Metric; import org.junit.Assert;
import java.io.*; import java.nio.charset.*; import org.deidentifier.arx.*; import org.deidentifier.arx.criteria.*; import org.deidentifier.arx.metric.*; import org.junit.*;
[ "java.io", "java.nio", "org.deidentifier.arx", "org.junit" ]
java.io; java.nio; org.deidentifier.arx; org.junit;
2,681,954
public BitSet prob1(DTMC dtmc, BitSet remain, BitSet target) { int n, iters; BitSet u, v, soln, unknown; boolean u_done, v_done; long timer; // Start precomputation timer = System.currentTimeMillis(); mainLog.println("Starting Prob1..."); // Special case: no target states if (target.cardinality() == 0) { return new BitSet(dtmc.getNumStates()); } // Initialise vectors n = dtmc.getNumStates(); u = new BitSet(n); v = new BitSet(n); soln = new BitSet(n); // Determine set of states actually need to perform computation for unknown = new BitSet(); unknown.set(0, n); unknown.andNot(target); if (remain != null) unknown.and(remain); // Nested fixed point loop iters = 0; u_done = false; // Greatest fixed point u.set(0, n); while (!u_done) { v_done = false; // Least fixed point - should start from 0 but we optimise by // starting from 'target', thus bypassing first iteration v.clear(); v.or(target); soln.clear(); soln.or(target); while (!v_done) { iters++; // Single step of Prob1 dtmc.prob1step(unknown, u, v, soln); // Check termination (inner) v_done = soln.equals(v); // v = soln v.clear(); v.or(soln); } // Check termination (outer) u_done = v.equals(u); // u = v u.clear(); u.or(v); } // Finished precomputation timer = System.currentTimeMillis() - timer; mainLog.print("Prob1"); mainLog.println(" took " + iters + " iterations and " + timer / 1000.0 + " seconds."); return u; }
BitSet function(DTMC dtmc, BitSet remain, BitSet target) { int n, iters; BitSet u, v, soln, unknown; boolean u_done, v_done; long timer; timer = System.currentTimeMillis(); mainLog.println(STR); if (target.cardinality() == 0) { return new BitSet(dtmc.getNumStates()); } n = dtmc.getNumStates(); u = new BitSet(n); v = new BitSet(n); soln = new BitSet(n); unknown = new BitSet(); unknown.set(0, n); unknown.andNot(target); if (remain != null) unknown.and(remain); iters = 0; u_done = false; u.set(0, n); while (!u_done) { v_done = false; v.clear(); v.or(target); soln.clear(); soln.or(target); while (!v_done) { iters++; dtmc.prob1step(unknown, u, v, soln); v_done = soln.equals(v); v.clear(); v.or(soln); } u_done = v.equals(u); u.clear(); u.or(v); } timer = System.currentTimeMillis() - timer; mainLog.print("Prob1"); mainLog.println(STR + iters + STR + timer / 1000.0 + STR); return u; }
/** * Prob1 precomputation algorithm. * i.e. determine the states of a DTMC which, with probability 1, * reach a state in {@code target}, while remaining in those in @{code remain}. * @param mdp The MDP * @param remain Remain in these states (optional: null means "all") * @param target Target states */
Prob1 precomputation algorithm. i.e. determine the states of a DTMC which, with probability 1, reach a state in target, while remaining in those in @{code remain}
prob1
{ "repo_name": "bharathk005/prism-4.2.1-src-teaser-patch", "path": "src/explicit/DTMCModelChecker.java", "license": "gpl-2.0", "size": 45690 }
[ "java.util.BitSet" ]
import java.util.BitSet;
import java.util.*;
[ "java.util" ]
java.util;
733,365
void setBrokerInstance(File directory);
void setBrokerInstance(File directory);
/** * Set the Artemis instance relative folder for data and stuff. */
Set the Artemis instance relative folder for data and stuff
setBrokerInstance
{ "repo_name": "rh-messaging/jboss-activemq-artemis", "path": "artemis-server/src/main/java/org/apache/activemq/artemis/core/config/Configuration.java", "license": "apache-2.0", "size": 37418 }
[ "java.io.File" ]
import java.io.File;
import java.io.*;
[ "java.io" ]
java.io;
2,154,658
public void setEntityParameter(Integer entityId, Integer preferenceId, String value) throws SessionInternalError;
void function(Integer entityId, Integer preferenceId, String value) throws SessionInternalError;
/** * This now only working with String parameters * * @param entityId entity id * @param preferenceId preference Id * @param value String parameter value (optional) * @throws SessionInternalError */
This now only working with String parameters
setEntityParameter
{ "repo_name": "tarique313/nBilling", "path": "src/java/com/sapienter/jbilling/server/user/IUserSessionBean.java", "license": "agpl-3.0", "size": 9998 }
[ "com.sapienter.jbilling.common.SessionInternalError" ]
import com.sapienter.jbilling.common.SessionInternalError;
import com.sapienter.jbilling.common.*;
[ "com.sapienter.jbilling" ]
com.sapienter.jbilling;
701,101
EReference getRequirement_ActiveAssignments();
EReference getRequirement_ActiveAssignments();
/** * Returns the meta object for the containment reference list '{@link org.obeonetwork.dsl.east_adl.requirements.Requirement#getActiveAssignments <em>Active Assignments</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the containment reference list '<em>Active Assignments</em>'. * @see org.obeonetwork.dsl.east_adl.requirements.Requirement#getActiveAssignments() * @see #getRequirement() * @generated */
Returns the meta object for the containment reference list '<code>org.obeonetwork.dsl.east_adl.requirements.Requirement#getActiveAssignments Active Assignments</code>'.
getRequirement_ActiveAssignments
{ "repo_name": "ObeoNetwork/EAST-ADL-Designer", "path": "plugins/org.obeonetwork.dsl.eastadl/src/org/obeonetwork/dsl/east_adl/requirements/RequirementsPackage.java", "license": "epl-1.0", "size": 122085 }
[ "org.eclipse.emf.ecore.EReference" ]
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
2,586,256
@ParametersAreNonnullByDefault @MethodsReturnNonnullByDefault public interface ICubicWorldInternal extends ICubicWorld { void tickCubicWorld(); /** * Returns the {@link ICubeProvider} for this world, or throws {@link NotCubicChunksWorldException}
interface ICubicWorldInternal extends ICubicWorld { void function(); /** * Returns the {@link ICubeProvider} for this world, or throws {@link NotCubicChunksWorldException}
/** * Updates the world */
Updates the world
tickCubicWorld
{ "repo_name": "OpenCubicChunks/CubicChunks", "path": "src/main/java/io/github/opencubicchunks/cubicchunks/core/asm/mixin/ICubicWorldInternal.java", "license": "mit", "size": 6392 }
[ "io.github.opencubicchunks.cubicchunks.api.util.NotCubicChunksWorldException", "io.github.opencubicchunks.cubicchunks.api.world.ICubeProvider", "io.github.opencubicchunks.cubicchunks.api.world.ICubicWorld" ]
import io.github.opencubicchunks.cubicchunks.api.util.NotCubicChunksWorldException; import io.github.opencubicchunks.cubicchunks.api.world.ICubeProvider; import io.github.opencubicchunks.cubicchunks.api.world.ICubicWorld;
import io.github.opencubicchunks.cubicchunks.api.util.*; import io.github.opencubicchunks.cubicchunks.api.world.*;
[ "io.github.opencubicchunks" ]
io.github.opencubicchunks;
563,454
//--------------------// // includeSampleSheet // //--------------------// public SampleSheet includeSampleSheet (SampleSheet extSheet) { // First, find out (or create) proper local SampleSheet final RunTable extImage = extSheet.getImage(); final Descriptor extDescriptor = extSheet.getDescriptor(); final SampleSheet localSheet = findSampleSheet(extDescriptor.getName(), null, extImage); // Copy external aliases final Descriptor localDescriptor = localSheet.getDescriptor(); localDescriptor.addAlias(extDescriptor.getName()); for (String alias : extDescriptor.getAliases()) { localDescriptor.addAlias(alias); } // Copy samples from external to local for (Sample sample : extSheet.getAllSamples()) { addSample(sample, localSheet); } // Copy tribes from external to local for (Tribe tribe : extSheet.getTribes()) { final Tribe localTribe = localSheet.getTribe(tribe.getHead()); for (Sample good : tribe.getGoods()) { localTribe.addGood(good); } for (Sample member : tribe.getMembers()) { localTribe.addOther(member); } } return localSheet; }
SampleSheet function (SampleSheet extSheet) { final RunTable extImage = extSheet.getImage(); final Descriptor extDescriptor = extSheet.getDescriptor(); final SampleSheet localSheet = findSampleSheet(extDescriptor.getName(), null, extImage); final Descriptor localDescriptor = localSheet.getDescriptor(); localDescriptor.addAlias(extDescriptor.getName()); for (String alias : extDescriptor.getAliases()) { localDescriptor.addAlias(alias); } for (Sample sample : extSheet.getAllSamples()) { addSample(sample, localSheet); } for (Tribe tribe : extSheet.getTribes()) { final Tribe localTribe = localSheet.getTribe(tribe.getHead()); for (Sample good : tribe.getGoods()) { localTribe.addGood(good); } for (Sample member : tribe.getMembers()) { localTribe.addOther(member); } } return localSheet; }
/** * Include the provided SampleSheet, with all its samples, into the repository. * <p> * The provided SampleSheet is meant to come from an external repository (typically from a * book-specific repository to the global repository). * * @param extSheet the provided (external) SampleSheet * @return the local SampleSheet (created or augmented) */
Include the provided SampleSheet, with all its samples, into the repository. The provided SampleSheet is meant to come from an external repository (typically from a book-specific repository to the global repository)
includeSampleSheet
{ "repo_name": "Audiveris/audiveris", "path": "src/main/org/audiveris/omr/classifier/SampleRepository.java", "license": "agpl-3.0", "size": 62382 }
[ "org.audiveris.omr.classifier.SheetContainer", "org.audiveris.omr.run.RunTable" ]
import org.audiveris.omr.classifier.SheetContainer; import org.audiveris.omr.run.RunTable;
import org.audiveris.omr.classifier.*; import org.audiveris.omr.run.*;
[ "org.audiveris.omr" ]
org.audiveris.omr;
2,019,510
public void acquire () { try { if (onResume_m != null) onResume_m.invoke (this); } catch (Throwable t) { } resumeTimers (); CookieSyncManager.getInstance ().startSync (); }
void function () { try { if (onResume_m != null) onResume_m.invoke (this); } catch (Throwable t) { } resumeTimers (); CookieSyncManager.getInstance ().startSync (); }
/** * Acquires all the resources previously released by {@link #release()}. * Should be called by enclosing activity in its own * {@link Activity#onResume} implementation. */
Acquires all the resources previously released by <code>#release()</code>. Should be called by enclosing activity in its own <code>Activity#onResume</code> implementation
acquire
{ "repo_name": "WaniKani/Android-Notification", "path": "src/com/wanikani/androidnotifier/FocusWebView.java", "license": "gpl-3.0", "size": 4957 }
[ "android.webkit.CookieSyncManager" ]
import android.webkit.CookieSyncManager;
import android.webkit.*;
[ "android.webkit" ]
android.webkit;
514,146
public static <T> Indexable<T> fromArray(T[] src) { return new IndexableArray<>(src); } private static final class IndexableList<T> implements Indexable<T> { private final List<T> source; public IndexableList(List<T> src) { this.source = Collections.unmodifiableList((src instanceof RandomAccess) ? src : new ArrayList<>(src)); }
static <T> Indexable<T> function(T[] src) { return new IndexableArray<>(src); } private static final class IndexableList<T> implements Indexable<T> { private final List<T> source; public IndexableList(List<T> src) { this.source = Collections.unmodifiableList((src instanceof RandomAccess) ? src : new ArrayList<>(src)); }
/** * Creates indexable from array. * * @param <T> Type. * @param src Source. * @return Indexable from given array. */
Creates indexable from array
fromArray
{ "repo_name": "nobullet/library", "path": "src/main/java/com/nobullet/list/Indexables.java", "license": "mit", "size": 2680 }
[ "java.util.ArrayList", "java.util.Collections", "java.util.List", "java.util.RandomAccess" ]
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.RandomAccess;
import java.util.*;
[ "java.util" ]
java.util;
980,606
@ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<ApiManagementServiceResourceInner>, ApiManagementServiceResourceInner> beginUpdate( String resourceGroupName, String serviceName, ApiManagementServiceUpdateParameters parameters) { return beginUpdateAsync(resourceGroupName, serviceName, parameters).getSyncPoller(); }
@ServiceMethod(returns = ReturnType.SINGLE) SyncPoller<PollResult<ApiManagementServiceResourceInner>, ApiManagementServiceResourceInner> function( String resourceGroupName, String serviceName, ApiManagementServiceUpdateParameters parameters) { return beginUpdateAsync(resourceGroupName, serviceName, parameters).getSyncPoller(); }
/** * Updates an existing API Management service. * * @param resourceGroupName The name of the resource group. * @param serviceName The name of the API Management service. * @param parameters Parameters supplied to the CreateOrUpdate API Management service operation. * @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 single API Management service resource in List or Get response. */
Updates an existing API Management service
beginUpdate
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/apimanagement/azure-resourcemanager-apimanagement/src/main/java/com/azure/resourcemanager/apimanagement/implementation/ApiManagementServicesClientImpl.java", "license": "mit", "size": 156165 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.management.polling.PollResult", "com.azure.core.util.polling.SyncPoller", "com.azure.resourcemanager.apimanagement.fluent.models.ApiManagementServiceResourceInner", "com.azure.resourcemanager.apimanagement.models.ApiManagementServiceUpdateParameters" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.management.polling.PollResult; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.apimanagement.fluent.models.ApiManagementServiceResourceInner; import com.azure.resourcemanager.apimanagement.models.ApiManagementServiceUpdateParameters;
import com.azure.core.annotation.*; import com.azure.core.management.polling.*; import com.azure.core.util.polling.*; import com.azure.resourcemanager.apimanagement.fluent.models.*; import com.azure.resourcemanager.apimanagement.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
89,481
@Override public void actionPerformed(ActionEvent e) { if (errorsOnly.isSelected()) { warningThresholdField.setEnabled(false); warningThresholdField.setEditable(false); } else { warningThresholdField.setEnabled(true); warningThresholdField.setEditable(true); } }
void function(ActionEvent e) { if (errorsOnly.isSelected()) { warningThresholdField.setEnabled(false); warningThresholdField.setEditable(false); } else { warningThresholdField.setEnabled(true); warningThresholdField.setEditable(true); } }
/** * This method is called from errors-only checkbox * * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */
This method is called from errors-only checkbox
actionPerformed
{ "repo_name": "yuyupapa/OpenSource", "path": "apache-jmeter-3.0/src/components/org/apache/jmeter/assertions/gui/HTMLAssertionGui.java", "license": "apache-2.0", "size": 13273 }
[ "java.awt.event.ActionEvent" ]
import java.awt.event.ActionEvent;
import java.awt.event.*;
[ "java.awt" ]
java.awt;
1,356,803
public List<FileItem> getMultiPartFileItems() { return m_multiPartFileItems; }
List<FileItem> function() { return m_multiPartFileItems; }
/** * Returns a list of FileItem instances parsed from the request, in the order that they were transmitted.<p> * * This list is automatically initialized from the createParameterMapFromMultiPart(HttpServletRequest) method.<p> * * @return list of FileItem instances parsed from the request, in the order that they were transmitted */
Returns a list of FileItem instances parsed from the request, in the order that they were transmitted. This list is automatically initialized from the createParameterMapFromMultiPart(HttpServletRequest) method
getMultiPartFileItems
{ "repo_name": "alkacon/opencms-core", "path": "src/org/opencms/workplace/CmsWorkplace.java", "license": "lgpl-2.1", "size": 95168 }
[ "java.util.List", "org.apache.commons.fileupload.FileItem" ]
import java.util.List; import org.apache.commons.fileupload.FileItem;
import java.util.*; import org.apache.commons.fileupload.*;
[ "java.util", "org.apache.commons" ]
java.util; org.apache.commons;
1,752,503
void sendMessages() throws IOException;
void sendMessages() throws IOException;
/** * Sends all messages on the transport queue. If a previous send attempt had * failed, the function will attempt to resend the messages in the previous * attempt. * * @throws IOException if the server could not be reached. */
Sends all messages on the transport queue. If a previous send attempt had failed, the function will attempt to resend the messages in the previous attempt
sendMessages
{ "repo_name": "fsautomata/azure-iot-sdks", "path": "java/device/iothub-java-client/src/main/java/com/microsoft/azure/iothub/transport/IotHubTransport.java", "license": "mit", "size": 2577 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
1,290,163
public ServiceFuture<Void> getMethodLocalValidAsync(final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(getMethodLocalValidWithServiceResponseAsync(), serviceCallback); }
ServiceFuture<Void> function(final ServiceCallback<Void> serviceCallback) { return ServiceFuture.fromResponse(getMethodLocalValidWithServiceResponseAsync(), serviceCallback); }
/** * Get method with api-version modeled in the method. pass in api-version = '2.0' to succeed. * * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the {@link ServiceFuture} object */
Get method with api-version modeled in the method. pass in api-version = '2.0' to succeed
getMethodLocalValidAsync
{ "repo_name": "lmazuel/autorest", "path": "src/generator/AutoRest.Java.Azure.Tests/src/main/java/fixtures/azurespecials/implementation/ApiVersionLocalsImpl.java", "license": "mit", "size": 19651 }
[ "com.microsoft.rest.ServiceCallback", "com.microsoft.rest.ServiceFuture" ]
import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.*;
[ "com.microsoft.rest" ]
com.microsoft.rest;
644,045
public static AjaxRequestTarget findOrCreateNewAjaxRequestTarget() { return findOrCreateNewAjaxRequestTarget(WebApplication.get(), getCurrentPage()); }
static AjaxRequestTarget function() { return findOrCreateNewAjaxRequestTarget(WebApplication.get(), getCurrentPage()); }
/** * Finds the current {@link AjaxRequestTarget} or creates a new ajax request target from the * given application and page if the current {@link AjaxRequestTarget} is null. * * @return an AjaxRequestTarget instance * * @see WebApplication#newAjaxRequestTarget(Page) */
Finds the current <code>AjaxRequestTarget</code> or creates a new ajax request target from the given application and page if the current <code>AjaxRequestTarget</code> is null
findOrCreateNewAjaxRequestTarget
{ "repo_name": "astrapi69/jaulp.wicket", "path": "jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/ComponentFinder.java", "license": "apache-2.0", "size": 6588 }
[ "org.apache.wicket.ajax.AjaxRequestTarget", "org.apache.wicket.protocol.http.WebApplication" ]
import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.ajax.*; import org.apache.wicket.protocol.http.*;
[ "org.apache.wicket" ]
org.apache.wicket;
2,241,849
public static <StateT extends State> StateTag<StateT> makeSystemTagInternal( StateTag<StateT> tag) { if (!(tag instanceof SystemStateTag)) { throw new IllegalArgumentException("Expected subclass of SimpleStateTag, got " + tag); } // Checked above @SuppressWarnings("unchecked") SystemStateTag<StateT> typedTag = (SystemStateTag<StateT>) tag; return typedTag.asKind(StateKind.SYSTEM); }
static <StateT extends State> StateTag<StateT> function( StateTag<StateT> tag) { if (!(tag instanceof SystemStateTag)) { throw new IllegalArgumentException(STR + tag); } @SuppressWarnings(STR) SystemStateTag<StateT> typedTag = (SystemStateTag<StateT>) tag; return typedTag.asKind(StateKind.SYSTEM); }
/** * Convert an arbitrary {@link StateTag} to a system-internal tag that is guaranteed not to * collide with any user tags. */
Convert an arbitrary <code>StateTag</code> to a system-internal tag that is guaranteed not to collide with any user tags
makeSystemTagInternal
{ "repo_name": "eljefe6a/incubator-beam", "path": "runners/core-java/src/main/java/org/apache/beam/runners/core/StateTags.java", "license": "apache-2.0", "size": 11802 }
[ "org.apache.beam.sdk.state.State" ]
import org.apache.beam.sdk.state.State;
import org.apache.beam.sdk.state.*;
[ "org.apache.beam" ]
org.apache.beam;
1,767,615
private SysSystemDto exportConnectorConfig(UUID systemId) { SysSystemDto system = systemService.get(systemId); if (system.getConnectorKey() != null) { IdmFormDefinitionDto definition = systemService.getConnectorFormDefinition(system); if (definition != null) { // Export EAV definition for connector formDefinitionService.export(definition.getId(), getBatch()); IdmFormInstanceDto connectorFormInstance = this.getFormService().getFormInstance(system, definition); if (connectorFormInstance != null) { // Beware, form instance doesn't have a ID, we generate random UUID. We need unique ID, because we save exported json with ID in file name. connectorFormInstance.setId(UUID.randomUUID()); this.getFormService().export(connectorFormInstance, getBatch()); } } } return system; }
SysSystemDto function(UUID systemId) { SysSystemDto system = systemService.get(systemId); if (system.getConnectorKey() != null) { IdmFormDefinitionDto definition = systemService.getConnectorFormDefinition(system); if (definition != null) { formDefinitionService.export(definition.getId(), getBatch()); IdmFormInstanceDto connectorFormInstance = this.getFormService().getFormInstance(system, definition); if (connectorFormInstance != null) { connectorFormInstance.setId(UUID.randomUUID()); this.getFormService().export(connectorFormInstance, getBatch()); } } } return system; }
/** * Export connector configuration * * @param systemId * @return */
Export connector configuration
exportConnectorConfig
{ "repo_name": "bcvsolutions/CzechIdMng", "path": "Realization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/bulk/action/impl/SystemExportBulkAction.java", "license": "mit", "size": 12904 }
[ "eu.bcvsolutions.idm.acc.dto.SysSystemDto", "eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto", "eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto", "java.util.UUID" ]
import eu.bcvsolutions.idm.acc.dto.SysSystemDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto; import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto; import java.util.UUID;
import eu.bcvsolutions.idm.acc.dto.*; import eu.bcvsolutions.idm.core.eav.api.dto.*; import java.util.*;
[ "eu.bcvsolutions.idm", "java.util" ]
eu.bcvsolutions.idm; java.util;
2,244,551
@org.junit.jupiter.api.Test public void test_signatureAlgorithms_signatures_hMACSignature() throws Exception { String filename = gregorsDir + "signatureAlgorithms/signatures/hMACSignature.xml"; ResourceResolverSpi resolver = new OfflineResolver(); boolean followManifests = false; byte[] hmacKey = "secret".getBytes(StandardCharsets.US_ASCII); boolean verify = false; try { verify = this.verifyHMAC(filename, resolver, followManifests, hmacKey); } catch (RuntimeException ex) { LOG.error("Verification crashed for " + filename); throw ex; } if (!verify) { LOG.error("Verification failed for " + filename); } assertTrue(verify, filename); }
@org.junit.jupiter.api.Test void function() throws Exception { String filename = gregorsDir + STR; ResourceResolverSpi resolver = new OfflineResolver(); boolean followManifests = false; byte[] hmacKey = STR.getBytes(StandardCharsets.US_ASCII); boolean verify = false; try { verify = this.verifyHMAC(filename, resolver, followManifests, hmacKey); } catch (RuntimeException ex) { LOG.error(STR + filename); throw ex; } if (!verify) { LOG.error(STR + filename); } assertTrue(verify, filename); }
/** * Method test_signatureAlgorithms_signatures_hMACSignature * * @throws Exception */
Method test_signatureAlgorithms_signatures_hMACSignature
test_signatureAlgorithms_signatures_hMACSignature
{ "repo_name": "apache/santuario-java", "path": "src/test/java/org/apache/xml/security/test/dom/interop/IAIKTest.java", "license": "apache-2.0", "size": 12567 }
[ "java.nio.charset.StandardCharsets", "org.apache.xml.security.test.dom.utils.resolver.OfflineResolver", "org.apache.xml.security.utils.resolver.ResourceResolverSpi", "org.junit.jupiter.api.Assertions" ]
import java.nio.charset.StandardCharsets; import org.apache.xml.security.test.dom.utils.resolver.OfflineResolver; import org.apache.xml.security.utils.resolver.ResourceResolverSpi; import org.junit.jupiter.api.Assertions;
import java.nio.charset.*; import org.apache.xml.security.test.dom.utils.resolver.*; import org.apache.xml.security.utils.resolver.*; import org.junit.jupiter.api.*;
[ "java.nio", "org.apache.xml", "org.junit.jupiter" ]
java.nio; org.apache.xml; org.junit.jupiter;
1,936,306
public void process(Reader ifile, String fileName) { String inputLine; int matches = 0; try (BufferedReader reader = new BufferedReader(ifile)) { while ((inputLine = reader.readLine()) != null) { matcher.reset(inputLine); if (matcher.find()) { if (listOnly) { // -l, print filename on first match, and we're done System.out.println(fileName); return; } if (countOnly) { matches++; } else { if (!dontPrintFileName) { System.out.print(fileName + ": "); } System.out.println(inputLine); } } else if (inVert) { System.out.println(inputLine); } } if (countOnly) System.out.println(matches + " matches in " + fileName); } catch (IOException e) { System.err.println(e); } } }
void function(Reader ifile, String fileName) { String inputLine; int matches = 0; try (BufferedReader reader = new BufferedReader(ifile)) { while ((inputLine = reader.readLine()) != null) { matcher.reset(inputLine); if (matcher.find()) { if (listOnly) { System.out.println(fileName); return; } if (countOnly) { matches++; } else { if (!dontPrintFileName) { System.out.print(fileName + STR); } System.out.println(inputLine); } } else if (inVert) { System.out.println(inputLine); } } if (countOnly) System.out.println(matches + STR + fileName); } catch (IOException e) { System.err.println(e); } } }
/** Do the work of scanning one file * @param ifile Reader Reader object already open * @param fileName String Name of the input file */
Do the work of scanning one file
process
{ "repo_name": "rickli/Java", "path": "Day2/com/darwinsys/regex/JGrep.java", "license": "gpl-2.0", "size": 6259 }
[ "java.io.BufferedReader", "java.io.IOException", "java.io.Reader" ]
import java.io.BufferedReader; import java.io.IOException; import java.io.Reader;
import java.io.*;
[ "java.io" ]
java.io;
1,901,300
private static MoveActionRequest buildActionRequest(JsonObject json, RequestInfo request) { String targetInstanceId = PATH_ID.get(request); String destinationId = json.getString("destination"); String userOperation = json.getString(JsonKeys.USER_OPERATION, ActionTypeConstants.MOVE); MoveActionRequest actionRequest = new MoveActionRequest(); actionRequest.setTargetId(targetInstanceId); actionRequest.setDestinationId(destinationId); actionRequest.setUserOperation(userOperation); return actionRequest; }
static MoveActionRequest function(JsonObject json, RequestInfo request) { String targetInstanceId = PATH_ID.get(request); String destinationId = json.getString(STR); String userOperation = json.getString(JsonKeys.USER_OPERATION, ActionTypeConstants.MOVE); MoveActionRequest actionRequest = new MoveActionRequest(); actionRequest.setTargetId(targetInstanceId); actionRequest.setDestinationId(destinationId); actionRequest.setUserOperation(userOperation); return actionRequest; }
/** * Build an action request from the provided json and request using the instance parser. * * @param json * the json containing the action request data * @param request * the request * @return the parsed move action request */
Build an action request from the provided json and request using the instance parser
buildActionRequest
{ "repo_name": "SirmaITT/conservation-space-1.7.0", "path": "docker/sirma-platform/platform/seip-parent/platform/domain-model/instance-core/src/main/java/com/sirma/itt/seip/instance/actions/move/InstanceMoveBodyReader.java", "license": "lgpl-3.0", "size": 2716 }
[ "com.sirma.itt.seip.domain.security.ActionTypeConstants", "com.sirma.itt.seip.rest.utils.JsonKeys", "com.sirma.itt.seip.rest.utils.request.RequestInfo", "javax.json.JsonObject" ]
import com.sirma.itt.seip.domain.security.ActionTypeConstants; import com.sirma.itt.seip.rest.utils.JsonKeys; import com.sirma.itt.seip.rest.utils.request.RequestInfo; import javax.json.JsonObject;
import com.sirma.itt.seip.domain.security.*; import com.sirma.itt.seip.rest.utils.*; import com.sirma.itt.seip.rest.utils.request.*; import javax.json.*;
[ "com.sirma.itt", "javax.json" ]
com.sirma.itt; javax.json;
1,332,606
private void verifyAndAssignRootWithRetries() throws IOException { int iTimes = this.server.getConfiguration().getInt( "hbase.catalog.verification.retries", 10); long waitTime = this.server.getConfiguration().getLong( "hbase.catalog.verification.timeout", 1000); int iFlag = 0; while (true) { try { verifyAndAssignRoot(); break; } catch (KeeperException e) { this.server.abort("In server shutdown processing, assigning root", e); throw new IOException("Aborting", e); } catch (Exception e) { if (iFlag >= iTimes) { this.server.abort("verifyAndAssignRoot failed after" + iTimes + " times retries, aborting", e); throw new IOException("Aborting", e); } try { Thread.sleep(waitTime); } catch (InterruptedException e1) { LOG.warn("Interrupted when is the thread sleep", e1); Thread.currentThread().interrupt(); throw new IOException("Interrupted", e1); } iFlag++; } } }
void function() throws IOException { int iTimes = this.server.getConfiguration().getInt( STR, 10); long waitTime = this.server.getConfiguration().getLong( STR, 1000); int iFlag = 0; while (true) { try { verifyAndAssignRoot(); break; } catch (KeeperException e) { this.server.abort(STR, e); throw new IOException(STR, e); } catch (Exception e) { if (iFlag >= iTimes) { this.server.abort(STR + iTimes + STR, e); throw new IOException(STR, e); } try { Thread.sleep(waitTime); } catch (InterruptedException e1) { LOG.warn(STR, e1); Thread.currentThread().interrupt(); throw new IOException(STR, e1); } iFlag++; } } }
/** * Failed many times, shutdown processing * @throws IOException */
Failed many times, shutdown processing
verifyAndAssignRootWithRetries
{ "repo_name": "ddraj/hbase-mttr", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/master/handler/ServerShutdownHandler.java", "license": "apache-2.0", "size": 21587 }
[ "java.io.IOException", "org.apache.zookeeper.KeeperException" ]
import java.io.IOException; import org.apache.zookeeper.KeeperException;
import java.io.*; import org.apache.zookeeper.*;
[ "java.io", "org.apache.zookeeper" ]
java.io; org.apache.zookeeper;
2,549,135
public static boolean isWritable() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; }
static boolean function() { String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { return true; } return false; }
/** * Checking if external storage is available for read and write */
Checking if external storage is available for read and write
isWritable
{ "repo_name": "AmericanRedCross/OpenMapKitAndroid", "path": "app/src/main/java/org/redcross/openmapkit/ExternalStorage.java", "license": "bsd-3-clause", "size": 18301 }
[ "android.os.Environment" ]
import android.os.Environment;
import android.os.*;
[ "android.os" ]
android.os;
2,372,147
public InterfacesConfig setInterfaces(final Collection<String> interfaces) { clear(); this.interfaceSet.addAll(interfaces); return this; }
InterfacesConfig function(final Collection<String> interfaces) { clear(); this.interfaceSet.addAll(interfaces); return this; }
/** * Adds a collection of interfaces. * Clears the current collection and then adds all entries of new collection. * * @param interfaces the interfaces to set */
Adds a collection of interfaces. Clears the current collection and then adds all entries of new collection
setInterfaces
{ "repo_name": "emre-aydin/hazelcast", "path": "hazelcast/src/main/java/com/hazelcast/config/InterfacesConfig.java", "license": "apache-2.0", "size": 2931 }
[ "java.util.Collection" ]
import java.util.Collection;
import java.util.*;
[ "java.util" ]
java.util;
1,683,525