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 list | imports_info stringlengths 19 34.8k | cluster_imports_info stringlengths 15 3.66k | libraries list | libraries_info stringlengths 6 661 | id int64 0 2.92M |
|---|---|---|---|---|---|---|---|---|---|---|---|
FedoraId getFedoraId(); | FedoraId getFedoraId(); | /**
* Get the FedoraId for this resource.
* @return the FedoraId identifier.
*/ | Get the FedoraId for this resource | getFedoraId | {
"repo_name": "peichman-umd/fcrepo4",
"path": "fcrepo-kernel-api/src/main/java/org/fcrepo/kernel/api/models/FedoraResource.java",
"license": "apache-2.0",
"size": 6701
} | [
"org.fcrepo.kernel.api.identifiers.FedoraId"
] | import org.fcrepo.kernel.api.identifiers.FedoraId; | import org.fcrepo.kernel.api.identifiers.*; | [
"org.fcrepo.kernel"
] | org.fcrepo.kernel; | 494,322 |
public Set<String> getSkipBuildPhrases() {
return new HashSet<String>(Arrays.asList(getTrigger().getSkipBuildPhrase().split("[\\r\\n]+")));
} | Set<String> function() { return new HashSet<String>(Arrays.asList(getTrigger().getSkipBuildPhrase().split(STR))); } | /**
* Returns skip build phrases from Jenkins global configuration
*
* @return skip build phrases
*/ | Returns skip build phrases from Jenkins global configuration | getSkipBuildPhrases | {
"repo_name": "jenkinsci/ghprb-plugin",
"path": "src/main/java/org/jenkinsci/plugins/ghprb/Ghprb.java",
"license": "mit",
"size": 24469
} | [
"java.util.Arrays",
"java.util.HashSet",
"java.util.Set"
] | import java.util.Arrays; import java.util.HashSet; import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 2,853,979 |
String listenPublisher(String mapName, String cacheName, ListenerAdapter listenerAdapter); | String listenPublisher(String mapName, String cacheName, ListenerAdapter listenerAdapter); | /**
* Adds the listener to listen underlying IMap on all nodes.
*
* @param mapName underlying map name of query cache.
* @param cacheName name of the query cache.
* @param listenerAdapter listener adapter for the query-cache.
* @return id of registered event listener
*/ | Adds the listener to listen underlying IMap on all nodes | listenPublisher | {
"repo_name": "lmjacksoniii/hazelcast",
"path": "hazelcast/src/main/java/com/hazelcast/map/impl/querycache/QueryCacheEventService.java",
"license": "apache-2.0",
"size": 4080
} | [
"com.hazelcast.map.impl.ListenerAdapter"
] | import com.hazelcast.map.impl.ListenerAdapter; | import com.hazelcast.map.impl.*; | [
"com.hazelcast.map"
] | com.hazelcast.map; | 353,522 |
public void eventCancelledByEventGateway(DelegateExecution execution) {
CommandContextUtil.getExecutionEntityManager().deleteExecutionAndRelatedData((ExecutionEntity) execution,
DeleteReason.EVENT_BASED_GATEWAY_CANCEL, false);
} | void function(DelegateExecution execution) { CommandContextUtil.getExecutionEntityManager().deleteExecutionAndRelatedData((ExecutionEntity) execution, DeleteReason.EVENT_BASED_GATEWAY_CANCEL, false); } | /**
* Should be subclassed by the more specific types. For an intermediate catch without type, it's simply leaving the event.
*/ | Should be subclassed by the more specific types. For an intermediate catch without type, it's simply leaving the event | eventCancelledByEventGateway | {
"repo_name": "yvoswillens/flowable-engine",
"path": "modules/flowable-engine/src/main/java/org/flowable/engine/impl/bpmn/behavior/IntermediateCatchEventActivityBehavior.java",
"license": "apache-2.0",
"size": 6460
} | [
"org.flowable.engine.delegate.DelegateExecution",
"org.flowable.engine.history.DeleteReason",
"org.flowable.engine.impl.persistence.entity.ExecutionEntity",
"org.flowable.engine.impl.util.CommandContextUtil"
] | import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.history.DeleteReason; import org.flowable.engine.impl.persistence.entity.ExecutionEntity; import org.flowable.engine.impl.util.CommandContextUtil; | import org.flowable.engine.delegate.*; import org.flowable.engine.history.*; import org.flowable.engine.impl.persistence.entity.*; import org.flowable.engine.impl.util.*; | [
"org.flowable.engine"
] | org.flowable.engine; | 2,540,211 |
private static byte[] xor(final byte[] input, final byte[] secret) {
final byte[] output = new byte[input.length];
if (secret.length == 0) {
System.arraycopy(input, 0, output, 0, input.length);
} else {
int spos = 0;
for (int pos = 0; pos < input.length; ++pos) {
output[pos] = (byte) (input[pos] ^ secret[spos]);
++spos;
if (spos >= secret.length) {
spos = 0;
}
}
}
return output;
}
public static final class DecryptionException extends Exception {
private static final long serialVersionUID = 0x7529FA781EDA1479L;
public DecryptionException(@NotNull final String cause) {
super(cause);
}
public DecryptionException(@NotNull final Throwable cause) {
super(cause);
}
} | static byte[] function(final byte[] input, final byte[] secret) { final byte[] output = new byte[input.length]; if (secret.length == 0) { System.arraycopy(input, 0, output, 0, input.length); } else { int spos = 0; for (int pos = 0; pos < input.length; ++pos) { output[pos] = (byte) (input[pos] ^ secret[spos]); ++spos; if (spos >= secret.length) { spos = 0; } } } return output; } public static final class DecryptionException extends Exception { private static final long serialVersionUID = 0x7529FA781EDA1479L; public DecryptionException(@NotNull final String cause) { super(cause); } public DecryptionException(@NotNull final Throwable cause) { super(cause); } } | /**
* XOR array of bytes.
* @param input The input to XOR
* @param secret Secret key
* @return Encrypted output
*/ | XOR array of bytes | xor | {
"repo_name": "yegor256/rexsl",
"path": "src/main/java/com/rexsl/page/auth/Encrypted.java",
"license": "bsd-3-clause",
"size": 9183
} | [
"javax.validation.constraints.NotNull"
] | import javax.validation.constraints.NotNull; | import javax.validation.constraints.*; | [
"javax.validation"
] | javax.validation; | 2,755,507 |
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.add(new Option("\tThe name of the data set.", "relation", 1,
"-relation <name>"));
result.add(new Option("\tThe seed value.", "seed", 1, "-seed <num>"));
result.add(new Option(
"\tThe number of instances in the datasets (default 20).",
"num-instances", 1, "-num-instances <num>"));
result.add(new Option(
"\tThe class type, see constants in weka.core.Attribute\n"
+ "\t(default 1=nominal).", "class-type", 1, "-class-type <num>"));
result.add(new Option(
"\tThe number of classes to generate (for nominal classes only)\n"
+ "\t(default 2).", "class-values", 1, "-class-values <num>"));
result.add(new Option("\tThe class index, with -1=last, (default -1).",
"class-index", 1, "-class-index <num>"));
result.add(new Option("\tDoesn't include a class attribute in the output.",
"no-class", 0, "-no-class"));
result.add(new Option("\tThe number of nominal attributes (default 1).",
"nominal", 1, "-nominal <num>"));
result.add(new Option(
"\tThe number of values for nominal attributes (default 2).",
"nominal-values", 1, "-nominal-values <num>"));
result.add(new Option("\tThe number of numeric attributes (default 0).",
"numeric", 1, "-numeric <num>"));
result.add(new Option("\tThe number of string attributes (default 0).",
"string", 1, "-string <num>"));
result.add(new Option("\tThe words to use in string attributes.", "words",
1, "-words <comma-separated-list>"));
result.add(new Option("\tThe word separators to use in string attributes.",
"word-separators", 1, "-word-separators <chars>"));
result.add(new Option("\tThe number of date attributes (default 0).",
"date", 1, "-date <num>"));
result.add(new Option("\tThe number of relational attributes (default 0).",
"relational", 1, "-relational <num>"));
result.add(new Option(
"\tThe number of nominal attributes in a rel. attribute (default 1).",
"relational-nominal", 1, "-relational-nominal <num>"));
result
.add(new Option(
"\tThe number of values for nominal attributes in a rel. attribute (default 2).",
"relational-nominal-values", 1, "-relational-nominal-values <num>"));
result.add(new Option(
"\tThe number of numeric attributes in a rel. attribute (default 0).",
"relational-numeric", 1, "-relational-numeric <num>"));
result.add(new Option(
"\tThe number of string attributes in a rel. attribute (default 0).",
"relational-string", 1, "-relational-string <num>"));
result.add(new Option(
"\tThe number of date attributes in a rel. attribute (default 0).",
"relational-date", 1, "-relational-date <num>"));
result.add(new Option(
"\tThe number of instances in relational/bag attributes (default 10).",
"num-instances-relational", 1, "-num-instances-relational <num>"));
result.add(new Option("\tGenerates multi-instance data.", "multi-instance",
0, "-multi-instance"));
result.add(new Option(
"\tThe Capabilities handler to base the dataset on.\n"
+ "\tThe other parameters can be used to override the ones\n"
+ "\tdetermined from the handler. Additional parameters for\n"
+ "\thandler can be passed on after the '--'.", "W", 1,
"-W <classname>"));
return result.elements();
} | Enumeration<Option> function() { Vector<Option> result = new Vector<Option>(); result.add(new Option(STR, STR, 1, STR)); result.add(new Option(STR, "seed", 1, STR)); result.add(new Option( STR, STR, 1, STR)); result.add(new Option( STR + STR, STR, 1, STR)); result.add(new Option( STR + STR, STR, 1, STR)); result.add(new Option(STR, STR, 1, STR)); result.add(new Option(STR, STR, 0, STR)); result.add(new Option(STR, STR, 1, STR)); result.add(new Option( STR, STR, 1, STR)); result.add(new Option(STR, STR, 1, STR)); result.add(new Option(STR, STR, 1, STR)); result.add(new Option(STR, "words", 1, STR)); result.add(new Option(STR, STR, 1, STR)); result.add(new Option(STR, "date", 1, STR)); result.add(new Option(STR, STR, 1, STR)); result.add(new Option( STR, STR, 1, STR)); result .add(new Option( STR, STR, 1, STR)); result.add(new Option( STR, STR, 1, STR)); result.add(new Option( STR, STR, 1, STR)); result.add(new Option( STR, STR, 1, STR)); result.add(new Option( STR, STR, 1, STR)); result.add(new Option(STR, STR, 0, STR)); result.add(new Option( STR + STR + STR + STR, "W", 1, STR)); return result.elements(); } | /**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/ | Returns an enumeration describing the available options | listOptions | {
"repo_name": "Scauser/j2ee",
"path": "Weka_Parallel_Test/weka/weka/core/TestInstances.java",
"license": "apache-2.0",
"size": 53138
} | [
"java.util.Enumeration",
"java.util.Vector"
] | import java.util.Enumeration; import java.util.Vector; | import java.util.*; | [
"java.util"
] | java.util; | 1,712,171 |
EAttribute getServiceGuarantee_ServiceRequirement(); | EAttribute getServiceGuarantee_ServiceRequirement(); | /**
* Returns the meta object for the attribute '{@link gluemodel.CIM.IEC61970.Informative.InfCustomers.ServiceGuarantee#getServiceRequirement <em>Service Requirement</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the attribute '<em>Service Requirement</em>'.
* @see gluemodel.CIM.IEC61970.Informative.InfCustomers.ServiceGuarantee#getServiceRequirement()
* @see #getServiceGuarantee()
* @generated
*/ | Returns the meta object for the attribute '<code>gluemodel.CIM.IEC61970.Informative.InfCustomers.ServiceGuarantee#getServiceRequirement Service Requirement</code>'. | getServiceGuarantee_ServiceRequirement | {
"repo_name": "georghinkel/ttc2017smartGrids",
"path": "solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/InfCustomers/InfCustomersPackage.java",
"license": "mit",
"size": 116381
} | [
"org.eclipse.emf.ecore.EAttribute"
] | import org.eclipse.emf.ecore.EAttribute; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,133,631 |
@ApiOperation(value = "Revoke security credentials from the corresponding credentials storage",
notes = "Launches an asynchronous process to terminate all active "
+ "sessions of the endpoint that uses these credentials. Only users with the "
+ "TENANT_ADMIN role are allowed to submit this request.")
@ApiResponses(value = {
@ApiResponse(code = 401, message = "The user is not authenticated or "
+ "invalid credentials were provided"),
@ApiResponse(code = 403, message = "The authenticated user does not have the required role "
+ "(TENANT_ADMIN)"),
@ApiResponse(code = 500, message = "An unexpected error occurred on the server side")})
@RequestMapping(value = "revokeCredentials",
params = {"applicationToken", "credentialsId"},
method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
public void revokeCredentials(
@ApiParam(name = "applicationToken",
value = "A unique auto-generated application identifier",
required = true)
@RequestParam String applicationToken,
@ApiParam(name = "credentialsId",
value = "A unique credentials identifier",
required = true)
@RequestParam String credentialsId) throws KaaAdminServiceException {
this.deviceManagementService.revokeCredentials(applicationToken, credentialsId);
} | @ApiOperation(value = STR, notes = STR + STR + STR) @ApiResponses(value = { @ApiResponse(code = 401, message = STR + STR), @ApiResponse(code = 403, message = STR + STR), @ApiResponse(code = 500, message = STR)}) @RequestMapping(value = STR, params = {STR, STR}, method = RequestMethod.POST) @ResponseStatus(HttpStatus.OK) void function( @ApiParam(name = STR, value = STR, required = true) @RequestParam String applicationToken, @ApiParam(name = STR, value = STR, required = true) @RequestParam String credentialsId) throws KaaAdminServiceException { this.deviceManagementService.revokeCredentials(applicationToken, credentialsId); } | /**
* Revokes security credentials from the corresponding credentials storage.
* Also launches an asynchronous process to terminate all active sessions of
* the endpoint that uses these credentials.
*
* @param applicationToken The application Token
* @param credentialsId The credentials ID
* @throws KaaAdminServiceException - if an exception occures.
*/ | Revokes security credentials from the corresponding credentials storage. Also launches an asynchronous process to terminate all active sessions of the endpoint that uses these credentials | revokeCredentials | {
"repo_name": "vtkhir/kaa",
"path": "server/node/src/main/java/org/kaaproject/kaa/server/admin/controller/DeviceManagementController.java",
"license": "apache-2.0",
"size": 11350
} | [
"io.swagger.annotations.ApiOperation",
"io.swagger.annotations.ApiParam",
"io.swagger.annotations.ApiResponse",
"io.swagger.annotations.ApiResponses",
"org.kaaproject.kaa.server.admin.shared.services.KaaAdminServiceException",
"org.springframework.http.HttpStatus",
"org.springframework.web.bind.annotati... | import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.kaaproject.kaa.server.admin.shared.services.KaaAdminServiceException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseStatus; | import io.swagger.annotations.*; import org.kaaproject.kaa.server.admin.shared.services.*; import org.springframework.http.*; import org.springframework.web.bind.annotation.*; | [
"io.swagger.annotations",
"org.kaaproject.kaa",
"org.springframework.http",
"org.springframework.web"
] | io.swagger.annotations; org.kaaproject.kaa; org.springframework.http; org.springframework.web; | 1,577,655 |
protected void addBusflagsPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_Substation_busflags_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_Substation_busflags_feature", "_UI_Substation_type"),
VisGridPackage.eINSTANCE.getSubstation_Busflags(),
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
} | void function(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString(STR), getString(STR, STR, STR), VisGridPackage.eINSTANCE.getSubstation_Busflags(), true, false, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } | /**
* This adds a property descriptor for the Busflags feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This adds a property descriptor for the Busflags feature. | addBusflagsPropertyDescriptor | {
"repo_name": "mikesligo/visGrid",
"path": "ie.tcd.gmf.visGrid.edit/src/visGrid/provider/SubstationItemProvider.java",
"license": "gpl-3.0",
"size": 29813
} | [
"org.eclipse.emf.edit.provider.ComposeableAdapterFactory",
"org.eclipse.emf.edit.provider.ItemPropertyDescriptor"
] | import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; | import org.eclipse.emf.edit.provider.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,354,136 |
@Override
public MovingObjectPosition collisionRayTrace(World par1World, int x, int y, int z, Vec3 par5Vec3, Vec3 par6Vec3)
{
final int var7 = par1World.getBlockMetadata(x, y, z) & 7;
float var8 = 0.3F;
if (var7 == 1)
{
this.setBlockBounds(0.0F, 0.2F, 0.5F - var8, var8 * 2.0F, 0.8F, 0.5F + var8);
}
else if (var7 == 2)
{
this.setBlockBounds(1.0F - var8 * 2.0F, 0.2F, 0.5F - var8, 1.0F, 0.8F, 0.5F + var8);
}
else if (var7 == 3)
{
this.setBlockBounds(0.5F - var8, 0.2F, 0.0F, 0.5F + var8, 0.8F, var8 * 2.0F);
}
else if (var7 == 4)
{
this.setBlockBounds(0.5F - var8, 0.2F, 1.0F - var8 * 2.0F, 0.5F + var8, 0.8F, 1.0F);
}
return super.collisionRayTrace(par1World, x, y, z, par5Vec3, par6Vec3);
} | MovingObjectPosition function(World par1World, int x, int y, int z, Vec3 par5Vec3, Vec3 par6Vec3) { final int var7 = par1World.getBlockMetadata(x, y, z) & 7; float var8 = 0.3F; if (var7 == 1) { this.setBlockBounds(0.0F, 0.2F, 0.5F - var8, var8 * 2.0F, 0.8F, 0.5F + var8); } else if (var7 == 2) { this.setBlockBounds(1.0F - var8 * 2.0F, 0.2F, 0.5F - var8, 1.0F, 0.8F, 0.5F + var8); } else if (var7 == 3) { this.setBlockBounds(0.5F - var8, 0.2F, 0.0F, 0.5F + var8, 0.8F, var8 * 2.0F); } else if (var7 == 4) { this.setBlockBounds(0.5F - var8, 0.2F, 1.0F - var8 * 2.0F, 0.5F + var8, 0.8F, 1.0F); } return super.collisionRayTrace(par1World, x, y, z, par5Vec3, par6Vec3); } | /**
* Ray traces through the blocks collision from start vector to end vector
* returning a ray trace hit. Args: world, x, y, z, startVec, endVec
*/ | Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. Args: world, x, y, z, startVec, endVec | collisionRayTrace | {
"repo_name": "4Space/4Space-5",
"path": "src/main/java/micdoodle8/mods/galacticraft/core/blocks/BlockSpinThruster.java",
"license": "gpl-3.0",
"size": 13093
} | [
"net.minecraft.util.MovingObjectPosition",
"net.minecraft.util.Vec3",
"net.minecraft.world.World"
] | import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.Vec3; import net.minecraft.world.World; | import net.minecraft.util.*; import net.minecraft.world.*; | [
"net.minecraft.util",
"net.minecraft.world"
] | net.minecraft.util; net.minecraft.world; | 2,740,521 |
//-----------------------------------------------------------------------
public static long checksumCRC32(File file) throws IOException {
CRC32 crc = new CRC32();
checksum(file, crc);
return crc.getValue();
} | static long function(File file) throws IOException { CRC32 crc = new CRC32(); checksum(file, crc); return crc.getValue(); } | /**
* Computes the checksum of a file using the CRC32 checksum routine.
* The value of the checksum is returned.
*
* @param file the file to checksum, must not be <code>null</code>
* @return the checksum value
* @throws NullPointerException if the file or checksum is <code>null</code>
* @throws IllegalArgumentException if the file is a directory
* @throws IOException if an IO error occurs reading the file
* @since Commons IO 1.3
*/ | Computes the checksum of a file using the CRC32 checksum routine. The value of the checksum is returned | checksumCRC32 | {
"repo_name": "copyliu/Spoutcraft_CJKPatch",
"path": "src/minecraft/org/apache/commons/io/FileUtils.java",
"license": "lgpl-3.0",
"size": 83439
} | [
"java.io.File",
"java.io.IOException"
] | import java.io.File; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,591,962 |
public static java.util.Set extractEmergencyEpisodeSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyEpisodeForEventHistoryVoCollection voCollection)
{
return extractEmergencyEpisodeSet(domainFactory, voCollection, null, new HashMap());
}
| static java.util.Set function(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EmergencyEpisodeForEventHistoryVoCollection voCollection) { return extractEmergencyEpisodeSet(domainFactory, voCollection, null, new HashMap()); } | /**
* Create the ims.core.admin.domain.objects.EmergencyEpisode set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/ | Create the ims.core.admin.domain.objects.EmergencyEpisode set from the value object collection | extractEmergencyEpisodeSet | {
"repo_name": "openhealthcare/openMAXIMS",
"path": "openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/EmergencyEpisodeForEventHistoryVoAssembler.java",
"license": "agpl-3.0",
"size": 22494
} | [
"java.util.HashMap"
] | import java.util.HashMap; | import java.util.*; | [
"java.util"
] | java.util; | 1,448,425 |
EReference getMarketer_HoldsTitleTo_EnergyProducts(); | EReference getMarketer_HoldsTitleTo_EnergyProducts(); | /**
* Returns the meta object for the reference list '{@link gluemodel.CIM.IEC61970.Informative.Financial.Marketer#getHoldsTitleTo_EnergyProducts <em>Holds Title To Energy Products</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the reference list '<em>Holds Title To Energy Products</em>'.
* @see gluemodel.CIM.IEC61970.Informative.Financial.Marketer#getHoldsTitleTo_EnergyProducts()
* @see #getMarketer()
* @generated
*/ | Returns the meta object for the reference list '<code>gluemodel.CIM.IEC61970.Informative.Financial.Marketer#getHoldsTitleTo_EnergyProducts Holds Title To Energy Products</code>'. | getMarketer_HoldsTitleTo_EnergyProducts | {
"repo_name": "georghinkel/ttc2017smartGrids",
"path": "solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/Financial/FinancialPackage.java",
"license": "mit",
"size": 116407
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,777,148 |
public void addSuggestionSource(QuerySuggestionSource suggestionSource) {
optionsHolder.getSuggestionSources().add(suggestionSource);
} | void function(QuerySuggestionSource suggestionSource) { optionsHolder.getSuggestionSources().add(suggestionSource); } | /**
* Add a suggestion source to the query options.
* @param suggestionSource The source.
*/ | Add a suggestion source to the query options | addSuggestionSource | {
"repo_name": "omkarudipi/java-client-api",
"path": "src/main/java/com/marklogic/client/io/QueryOptionsHandle.java",
"license": "apache-2.0",
"size": 37180
} | [
"com.marklogic.client.admin.config.QueryOptions"
] | import com.marklogic.client.admin.config.QueryOptions; | import com.marklogic.client.admin.config.*; | [
"com.marklogic.client"
] | com.marklogic.client; | 1,621,889 |
@ServiceMethod(returns = ReturnType.SINGLE)
private Mono<JobInner> createAsync(
String resourceGroupName, String accountName, String transformName, String jobName, JobInner parameters) {
return createWithResponseAsync(resourceGroupName, accountName, transformName, jobName, parameters)
.flatMap(
(Response<JobInner> res) -> {
if (res.getValue() != null) {
return Mono.just(res.getValue());
} else {
return Mono.empty();
}
});
} | @ServiceMethod(returns = ReturnType.SINGLE) Mono<JobInner> function( String resourceGroupName, String accountName, String transformName, String jobName, JobInner parameters) { return createWithResponseAsync(resourceGroupName, accountName, transformName, jobName, parameters) .flatMap( (Response<JobInner> res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); } | /**
* Creates a Job.
*
* @param resourceGroupName The name of the resource group within the Azure subscription.
* @param accountName The Media Services account name.
* @param transformName The Transform name.
* @param jobName The Job name.
* @param parameters The request parameters.
* @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 Job resource type.
*/ | Creates a Job | createAsync | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/mediaservices/azure-resourcemanager-mediaservices/src/main/java/com/azure/resourcemanager/mediaservices/implementation/JobsClientImpl.java",
"license": "mit",
"size": 66903
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.Response",
"com.azure.resourcemanager.mediaservices.fluent.models.JobInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.resourcemanager.mediaservices.fluent.models.JobInner; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.mediaservices.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 299,456 |
public static <T extends Diffable<T>> Diff<ImmutableMap<String, T>> diff(ImmutableMap<String, T> before, ImmutableMap<String, T> after) {
assert after != null && before != null;
return new ImmutableMapDiff<>(before, after);
} | static <T extends Diffable<T>> Diff<ImmutableMap<String, T>> function(ImmutableMap<String, T> before, ImmutableMap<String, T> after) { assert after != null && before != null; return new ImmutableMapDiff<>(before, after); } | /**
* Calculates diff between two ImmutableMaps of Diffable objects
*/ | Calculates diff between two ImmutableMaps of Diffable objects | diff | {
"repo_name": "slavau/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/cluster/DiffableUtils.java",
"license": "apache-2.0",
"size": 10504
} | [
"com.google.common.collect.ImmutableMap"
] | import com.google.common.collect.ImmutableMap; | import com.google.common.collect.*; | [
"com.google.common"
] | com.google.common; | 2,911,522 |
String[] getItemNamesByPlayerAndPlayerCommand(String playerId, PlayerCommandTypeMapping playerCommand); | String[] getItemNamesByPlayerAndPlayerCommand(String playerId, PlayerCommandTypeMapping playerCommand); | /**
* Returns all Items associated to <code>playerId</code> and <code>playerCommand</code>
*
* @param playerId the id of the player for which items should be returned
* @param playerCommand the player command for which items should be returned
*
* @return the name of all items which are associated to <code>playerId</code>
* and <code>playerComannd</code>
*/ | Returns all Items associated to <code>playerId</code> and <code>playerCommand</code> | getItemNamesByPlayerAndPlayerCommand | {
"repo_name": "noushadali/openhab",
"path": "bundles/binding/org.openhab.binding.mpd/src/main/java/org/openhab/binding/mpd/MpdBindingProvider.java",
"license": "gpl-3.0",
"size": 2740
} | [
"org.openhab.binding.mpd.internal.PlayerCommandTypeMapping"
] | import org.openhab.binding.mpd.internal.PlayerCommandTypeMapping; | import org.openhab.binding.mpd.internal.*; | [
"org.openhab.binding"
] | org.openhab.binding; | 1,069,600 |
public String getPublicKey() {
RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey();
if (key == null) {
return null;
}
byte[] encoded = Base64.getEncoder().encode(key.getEncoded());
int index = 0;
StringBuilder buf = new StringBuilder(encoded.length + 20);
while (index < encoded.length) {
int len = Math.min(64, encoded.length - index);
if (index > 0) {
buf.append("\n");
}
buf.append(new String(encoded, index, len, Charsets.UTF_8));
index += len;
}
return String.format("-----BEGIN PUBLIC KEY-----%n%s%n-----END PUBLIC KEY-----%n", buf.toString());
} | String function() { RSAPublicKey key = InstanceIdentityProvider.RSA.getPublicKey(); if (key == null) { return null; } byte[] encoded = Base64.getEncoder().encode(key.getEncoded()); int index = 0; StringBuilder buf = new StringBuilder(encoded.length + 20); while (index < encoded.length) { int len = Math.min(64, encoded.length - index); if (index > 0) { buf.append("\n"); } buf.append(new String(encoded, index, len, Charsets.UTF_8)); index += len; } return String.format(STR, buf.toString()); } | /**
* Returns the PEM encoded public key.
*
* @return the PEM encoded public key.
*/ | Returns the PEM encoded public key | getPublicKey | {
"repo_name": "viqueen/jenkins",
"path": "core/src/main/java/jenkins/model/identity/IdentityRootAction.java",
"license": "mit",
"size": 3077
} | [
"java.security.interfaces.RSAPublicKey",
"java.util.Base64",
"org.apache.commons.codec.Charsets"
] | import java.security.interfaces.RSAPublicKey; import java.util.Base64; import org.apache.commons.codec.Charsets; | import java.security.interfaces.*; import java.util.*; import org.apache.commons.codec.*; | [
"java.security",
"java.util",
"org.apache.commons"
] | java.security; java.util; org.apache.commons; | 87,297 |
SpringApplication.run(GRSFrontendApplication.class, args);
} | SpringApplication.run(GRSFrontendApplication.class, args); } | /**
* The main.
*
* @param args
* the arguments
*/ | The main | main | {
"repo_name": "elminsterjimmy/GRS",
"path": "frontend/src/main/java/com/elminster/grs/frontend/application/GRSFrontendApplication.java",
"license": "gpl-2.0",
"size": 564
} | [
"org.springframework.boot.SpringApplication"
] | import org.springframework.boot.SpringApplication; | import org.springframework.boot.*; | [
"org.springframework.boot"
] | org.springframework.boot; | 28,147 |
private static HashMap<String, Object> getClassItems(Class c, Object object) throws IllegalAccessException {
HashMap<String, Object> map = new HashMap<String, Object>();
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
Object value = f.get(object);
//TODO : we may use different strategy : eager for all, eager for Resource, just lazy (objects -> toString)
//TODO could be here value.toString() for immediate use, depending on params
map.put(f.getName(), value);
}
return map;
} | static HashMap<String, Object> function(Class c, Object object) throws IllegalAccessException { HashMap<String, Object> map = new HashMap<String, Object>(); Field[] fields = c.getDeclaredFields(); for (Field f : fields) { f.setAccessible(true); Object value = f.get(object); map.put(f.getName(), value); } return map; } | /**
* Any error will be written in the couples
*
* @param c
* @param object
* @return
*/ | Any error will be written in the couples | getClassItems | {
"repo_name": "robusta-code/rra",
"path": "src/main/java/io/robusta/rra/resource/ResourceSerializer.java",
"license": "apache-2.0",
"size": 4061
} | [
"java.lang.reflect.Field",
"java.util.HashMap"
] | import java.lang.reflect.Field; import java.util.HashMap; | import java.lang.reflect.*; import java.util.*; | [
"java.lang",
"java.util"
] | java.lang; java.util; | 1,262,644 |
private static @Nullable List<String> extractConstructorParameterNames(
Constructor<?> constructor, List<Field> fields) {
final Type[] parameterTypes = constructor.getGenericParameterTypes();
List<String> parameterNames = extractExecutableNames(constructor);
if (parameterNames == null) {
return null;
}
final Map<String, Field> fieldMap =
fields.stream()
.collect(
Collectors.toMap(
f -> normalizeAccessorName(f.getName()),
Function.identity()));
// check that all fields are represented in the parameters of the constructor
final List<String> fieldNames = new ArrayList<>();
for (int i = 0; i < parameterNames.size(); i++) {
final String parameterName = normalizeAccessorName(parameterNames.get(i));
final Field field = fieldMap.get(parameterName);
if (field == null) {
return null;
}
final Type fieldType = field.getGenericType();
final Type parameterType = parameterTypes[i];
// we are tolerant here because frameworks such as Avro accept a boxed type even though
// the field is primitive
if (!primitiveToWrapper(parameterType).equals(primitiveToWrapper(fieldType))) {
return null;
}
fieldNames.add(field.getName());
}
return fieldNames;
} | static @Nullable List<String> function( Constructor<?> constructor, List<Field> fields) { final Type[] parameterTypes = constructor.getGenericParameterTypes(); List<String> parameterNames = extractExecutableNames(constructor); if (parameterNames == null) { return null; } final Map<String, Field> fieldMap = fields.stream() .collect( Collectors.toMap( f -> normalizeAccessorName(f.getName()), Function.identity())); final List<String> fieldNames = new ArrayList<>(); for (int i = 0; i < parameterNames.size(); i++) { final String parameterName = normalizeAccessorName(parameterNames.get(i)); final Field field = fieldMap.get(parameterName); if (field == null) { return null; } final Type fieldType = field.getGenericType(); final Type parameterType = parameterTypes[i]; if (!primitiveToWrapper(parameterType).equals(primitiveToWrapper(fieldType))) { return null; } fieldNames.add(field.getName()); } return fieldNames; } | /**
* Extracts ordered parameter names from a constructor that takes all of the given fields with
* matching (possibly primitive and lenient) type and name.
*/ | Extracts ordered parameter names from a constructor that takes all of the given fields with matching (possibly primitive and lenient) type and name | extractConstructorParameterNames | {
"repo_name": "apache/flink",
"path": "flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/extraction/ExtractionUtils.java",
"license": "apache-2.0",
"size": 41774
} | [
"java.lang.reflect.Constructor",
"java.lang.reflect.Field",
"java.lang.reflect.Type",
"java.util.ArrayList",
"java.util.List",
"java.util.Map",
"java.util.function.Function",
"java.util.stream.Collectors",
"javax.annotation.Nullable"
] | import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.Nullable; | import java.lang.reflect.*; import java.util.*; import java.util.function.*; import java.util.stream.*; import javax.annotation.*; | [
"java.lang",
"java.util",
"javax.annotation"
] | java.lang; java.util; javax.annotation; | 1,852,664 |
public static final int getNrAtoms(Structure s){
int nrAtoms = 0;
Iterator<Group> iter = new GroupIterator(s);
while ( iter.hasNext()){
Group g = (Group) iter.next();
nrAtoms += g.size();
}
return nrAtoms;
} | static final int function(Structure s){ int nrAtoms = 0; Iterator<Group> iter = new GroupIterator(s); while ( iter.hasNext()){ Group g = (Group) iter.next(); nrAtoms += g.size(); } return nrAtoms; } | /** Count how many number of Atoms are contained within a Structure object.
*
* @param s the structure object
* @return the number of Atoms in this Structure
*/ | Count how many number of Atoms are contained within a Structure object | getNrAtoms | {
"repo_name": "kumar-physics/BioJava",
"path": "biojava3-structure/src/main/java/org/biojava/bio/structure/StructureTools.java",
"license": "lgpl-2.1",
"size": 38927
} | [
"java.util.Iterator"
] | import java.util.Iterator; | import java.util.*; | [
"java.util"
] | java.util; | 822,090 |
@Test
public void testAddMajority() throws Exception {
String volumeName = "testAddMajority";
String fileName = "/testfile";
SuspendableOSDRequestDispatcher[] suspOSDs = replaceWithSuspendableOSDs(0, 2);
// Create and open the volume and set a replication factor of 2.
client.createVolume(mrcAddress, auth, userCredentials, volumeName);
AdminVolume volume = client.openVolume(volumeName, null, options);
// Ensure the selected OSDs and replicas a sorted ascending by UUIDs.
volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 2, 0);
volume.setOSDSelectionPolicy(
userCredentials,
Helper.policiesToString(new OSDSelectionPolicyType[] {
OSDSelectionPolicyType.OSD_SELECTION_POLICY_FILTER_DEFAULT,
OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID }));
volume.setReplicaSelectionPolicy(
userCredentials,
Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID }));
// Create the testfile by writing some bytes to it.
AdminFileHandle file = volume.openFile(userCredentials, fileName,
Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDWR, SYSTEM_V_FCNTL_H_O_CREAT), 0777);
ReusableBuffer dataIn = SetupUtils.generateData(256 * 1024, (byte) 1);
file.write(userCredentials, dataIn.getData(), 256 * 1024, 0);
dataIn.clear();
file.close();
// Add another 3 replicas that form a majority by itself.
addReplicas(volume, fileName, 3);
// Ensure no primary can exist, by waiting until the lease timed out.
Thread.sleep(LEASE_TIMEOUT_MS + 500);
// Reverse the replica selection policy to ensure subsequent requests will be directed to the recently added
// replicas.
volume.setReplicaSelectionPolicy(
userCredentials,
Helper.policiesToString(new OSDSelectionPolicyType[] {
OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID,
OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_REVERSE }));
// Suspend the original 2 first OSDs to ensure only the recently added replicas can be accessed.
suspOSDs[0].suspend();
suspOSDs[1].suspend();
// Read from the file again and ensure the data is consistent.
file = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDWR));
byte[] dataOut = new byte[1];
file.read(userCredentials, dataOut, 1, 0);
file.close();
volume.close();
assertEquals(dataOut[0], (byte) 1);
resetSuspendableOSDs(suspOSDs, 0);
} | void function() throws Exception { String volumeName = STR; String fileName = STR; SuspendableOSDRequestDispatcher[] suspOSDs = replaceWithSuspendableOSDs(0, 2); client.createVolume(mrcAddress, auth, userCredentials, volumeName); AdminVolume volume = client.openVolume(volumeName, null, options); volume.setDefaultReplicationPolicy(userCredentials, "/", ReplicaUpdatePolicies.REPL_UPDATE_PC_WQRQ, 2, 0); volume.setOSDSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_FILTER_DEFAULT, OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID })); AdminFileHandle file = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDWR, SYSTEM_V_FCNTL_H_O_CREAT), 0777); ReusableBuffer dataIn = SetupUtils.generateData(256 * 1024, (byte) 1); file.write(userCredentials, dataIn.getData(), 256 * 1024, 0); dataIn.clear(); file.close(); addReplicas(volume, fileName, 3); Thread.sleep(LEASE_TIMEOUT_MS + 500); volume.setReplicaSelectionPolicy( userCredentials, Helper.policiesToString(new OSDSelectionPolicyType[] { OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_UUID, OSDSelectionPolicyType.OSD_SELECTION_POLICY_SORT_REVERSE })); suspOSDs[0].suspend(); suspOSDs[1].suspend(); file = volume.openFile(userCredentials, fileName, Helper.flagsToInt(SYSTEM_V_FCNTL_H_O_RDWR)); byte[] dataOut = new byte[1]; file.read(userCredentials, dataOut, 1, 0); file.close(); volume.close(); assertEquals(dataOut[0], (byte) 1); resetSuspendableOSDs(suspOSDs, 0); } | /**
* This test covers the case, that a number of replicas is added which will form a new majority. It has to be
* ensured that the correct data is returned, even if only new replicas are accessed.
*/ | This test covers the case, that a number of replicas is added which will form a new majority. It has to be ensured that the correct data is returned, even if only new replicas are accessed | testAddMajority | {
"repo_name": "kleingeist/xtreemfs",
"path": "java/servers/test/org/xtreemfs/test/mrc/VersionedXLocSetTest.java",
"license": "bsd-3-clause",
"size": 25211
} | [
"org.junit.Assert",
"org.xtreemfs.common.ReplicaUpdatePolicies",
"org.xtreemfs.common.libxtreemfs.AdminFileHandle",
"org.xtreemfs.common.libxtreemfs.AdminVolume",
"org.xtreemfs.common.libxtreemfs.Helper",
"org.xtreemfs.foundation.buffer.ReusableBuffer",
"org.xtreemfs.pbrpc.generatedinterfaces.GlobalType... | import org.junit.Assert; import org.xtreemfs.common.ReplicaUpdatePolicies; import org.xtreemfs.common.libxtreemfs.AdminFileHandle; import org.xtreemfs.common.libxtreemfs.AdminVolume; import org.xtreemfs.common.libxtreemfs.Helper; import org.xtreemfs.foundation.buffer.ReusableBuffer; import org.xtreemfs.pbrpc.generatedinterfaces.GlobalTypes; import org.xtreemfs.test.SetupUtils; | import org.junit.*; import org.xtreemfs.common.*; import org.xtreemfs.common.libxtreemfs.*; import org.xtreemfs.foundation.buffer.*; import org.xtreemfs.pbrpc.generatedinterfaces.*; import org.xtreemfs.test.*; | [
"org.junit",
"org.xtreemfs.common",
"org.xtreemfs.foundation",
"org.xtreemfs.pbrpc",
"org.xtreemfs.test"
] | org.junit; org.xtreemfs.common; org.xtreemfs.foundation; org.xtreemfs.pbrpc; org.xtreemfs.test; | 937,009 |
public String encrypt(String secret) throws Exception {
KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
keyStore.load(null);
KeyStore.PrivateKeyEntry privateKeyEntry =
(KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null);
Cipher inputCipher = Cipher.getInstance(RSA_ALGORITHM);
inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher);
cipherOutputStream.write(secret.getBytes());
cipherOutputStream.close();
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT);
} | String function(String secret) throws Exception { KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE); keyStore.load(null); KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null); Cipher inputCipher = Cipher.getInstance(RSA_ALGORITHM); inputCipher.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, inputCipher); cipherOutputStream.write(secret.getBytes()); cipherOutputStream.close(); return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT); } | /**
* Encrypt the secret with RSA.
*
* @param secret the secret.
* @return the encrypted secret.
* @throws Exception
*/ | Encrypt the secret with RSA | encrypt | {
"repo_name": "drakeet/rebase-android",
"path": "app/src/main/java/com/drakeet/rebase/tool/BlackBox.java",
"license": "gpl-3.0",
"size": 5115
} | [
"android.util.Base64",
"java.io.ByteArrayOutputStream",
"java.security.KeyStore",
"javax.crypto.Cipher",
"javax.crypto.CipherOutputStream"
] | import android.util.Base64; import java.io.ByteArrayOutputStream; import java.security.KeyStore; import javax.crypto.Cipher; import javax.crypto.CipherOutputStream; | import android.util.*; import java.io.*; import java.security.*; import javax.crypto.*; | [
"android.util",
"java.io",
"java.security",
"javax.crypto"
] | android.util; java.io; java.security; javax.crypto; | 2,874,222 |
@Test
public void testIllegalStorageFormatDuringTableScan()
{
SchemaTableName schemaTableName = temporaryTable("test_illegal_storage_format");
try (Transaction transaction = newTransaction()) {
ConnectorSession session = newSession();
List<Column> columns = ImmutableList.of(new Column("pk", HIVE_STRING, Optional.empty()));
String tableOwner = session.getUser();
String schemaName = schemaTableName.getSchemaName();
String tableName = schemaTableName.getTableName();
LocationHandle locationHandle = locationService.forNewTable(transaction.getMetastore(), session, schemaName, tableName, Optional.empty());
Path targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath();
//create table whose storage format is null
Table.Builder tableBuilder = Table.builder()
.setDatabaseName(schemaName)
.setTableName(tableName)
.setOwner(tableOwner)
.setTableType(TableType.MANAGED_TABLE.name())
.setParameters(ImmutableMap.of(
PRESTO_VERSION_NAME, TEST_SERVER_VERSION,
PRESTO_QUERY_ID_NAME, session.getQueryId()))
.setDataColumns(columns)
.withStorage(storage -> storage
.setLocation(targetPath.toString())
.setStorageFormat(StorageFormat.createNullable(null, null, null))
.setSerdeParameters(ImmutableMap.of()));
PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(tableOwner, session.getUser());
transaction.getMetastore().createTable(session, tableBuilder.build(), principalPrivileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS);
transaction.commit();
}
// We retrieve the table whose storageFormat has null serde/inputFormat/outputFormat
// to make sure it can still be retrieved instead of throwing exception.
try (Transaction transaction = newTransaction()) {
ConnectorMetadata metadata = transaction.getMetadata();
Map<SchemaTableName, List<ColumnMetadata>> allColumns = metadata.listTableColumns(newSession(), new SchemaTablePrefix(schemaTableName.getSchemaName()));
assertTrue(allColumns.containsKey(schemaTableName));
}
finally {
dropTable(schemaTableName);
}
} | void function() { SchemaTableName schemaTableName = temporaryTable(STR); try (Transaction transaction = newTransaction()) { ConnectorSession session = newSession(); List<Column> columns = ImmutableList.of(new Column("pk", HIVE_STRING, Optional.empty())); String tableOwner = session.getUser(); String schemaName = schemaTableName.getSchemaName(); String tableName = schemaTableName.getTableName(); LocationHandle locationHandle = locationService.forNewTable(transaction.getMetastore(), session, schemaName, tableName, Optional.empty()); Path targetPath = locationService.getQueryWriteInfo(locationHandle).getTargetPath(); Table.Builder tableBuilder = Table.builder() .setDatabaseName(schemaName) .setTableName(tableName) .setOwner(tableOwner) .setTableType(TableType.MANAGED_TABLE.name()) .setParameters(ImmutableMap.of( PRESTO_VERSION_NAME, TEST_SERVER_VERSION, PRESTO_QUERY_ID_NAME, session.getQueryId())) .setDataColumns(columns) .withStorage(storage -> storage .setLocation(targetPath.toString()) .setStorageFormat(StorageFormat.createNullable(null, null, null)) .setSerdeParameters(ImmutableMap.of())); PrincipalPrivileges principalPrivileges = testingPrincipalPrivilege(tableOwner, session.getUser()); transaction.getMetastore().createTable(session, tableBuilder.build(), principalPrivileges, Optional.empty(), true, EMPTY_TABLE_STATISTICS); transaction.commit(); } try (Transaction transaction = newTransaction()) { ConnectorMetadata metadata = transaction.getMetadata(); Map<SchemaTableName, List<ColumnMetadata>> allColumns = metadata.listTableColumns(newSession(), new SchemaTablePrefix(schemaTableName.getSchemaName())); assertTrue(allColumns.containsKey(schemaTableName)); } finally { dropTable(schemaTableName); } } | /**
* During table scan, the illegal storage format for some specific table should not fail the whole table scan
*/ | During table scan, the illegal storage format for some specific table should not fail the whole table scan | testIllegalStorageFormatDuringTableScan | {
"repo_name": "losipiuk/presto",
"path": "plugin/trino-hive/src/test/java/io/trino/plugin/hive/AbstractTestHive.java",
"license": "apache-2.0",
"size": 299467
} | [
"com.google.common.collect.ImmutableList",
"com.google.common.collect.ImmutableMap",
"io.trino.plugin.hive.metastore.Column",
"io.trino.plugin.hive.metastore.PrincipalPrivileges",
"io.trino.plugin.hive.metastore.StorageFormat",
"io.trino.plugin.hive.metastore.Table",
"io.trino.spi.connector.ColumnMetada... | import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.trino.plugin.hive.metastore.Column; import io.trino.plugin.hive.metastore.PrincipalPrivileges; import io.trino.plugin.hive.metastore.StorageFormat; import io.trino.plugin.hive.metastore.Table; import io.trino.spi.connector.ColumnMetadata; import io.trino.spi.connector.ConnectorMetadata; import io.trino.spi.connector.ConnectorSession; import io.trino.spi.connector.SchemaTableName; import io.trino.spi.connector.SchemaTablePrefix; import java.util.List; import java.util.Map; import java.util.Optional; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.metastore.TableType; import org.testng.Assert; | import com.google.common.collect.*; import io.trino.plugin.hive.metastore.*; import io.trino.spi.connector.*; import java.util.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hive.metastore.*; import org.testng.*; | [
"com.google.common",
"io.trino.plugin",
"io.trino.spi",
"java.util",
"org.apache.hadoop",
"org.testng"
] | com.google.common; io.trino.plugin; io.trino.spi; java.util; org.apache.hadoop; org.testng; | 1,911,009 |
public static TaskStatus getTaskStatus(Status status) {
return conversionMap.get(status);
}
/**
* {@inheritDoc} | static TaskStatus function(Status status) { return conversionMap.get(status); } /** * {@inheritDoc} | /**
* Converts the Drools status to this TaskStatus.
* @param status The status to convert
* @return The converted status.
*/ | Converts the Drools status to this TaskStatus | getTaskStatus | {
"repo_name": "NCIP/calims",
"path": "calims2-api/src/java/gov/nih/nci/calims2/business/workflow/taskclient/TaskStatus.java",
"license": "bsd-3-clause",
"size": 2093
} | [
"org.drools.task.Status"
] | import org.drools.task.Status; | import org.drools.task.*; | [
"org.drools.task"
] | org.drools.task; | 1,173,005 |
public void consumeHiddenToken(Token t); | void function(Token t); | /** An off-channel input token was consumed.
* Trigger after the token was matched by things like match(), matchAny().
* (unless of course the hidden token is first stuff in the input stream).
*/ | An off-channel input token was consumed. Trigger after the token was matched by things like match(), matchAny(). (unless of course the hidden token is first stuff in the input stream) | consumeHiddenToken | {
"repo_name": "sshrdp/mclab",
"path": "lib/antlr-3.0.1/runtime/Java/src/org/antlr/runtime/debug/DebugEventListener.java",
"license": "apache-2.0",
"size": 12067
} | [
"org.antlr.runtime.Token"
] | import org.antlr.runtime.Token; | import org.antlr.runtime.*; | [
"org.antlr.runtime"
] | org.antlr.runtime; | 1,371,081 |
public Workspace getOrCreateWorkspace(String name) {
checkNotNull("name",
name);
Workspace workspace = new WorkspaceImpl(name);
workspaces.computeIfAbsent(new WorkspaceImpl(name),
w -> this.createCache());
return this.getWorkspace(name);
} | Workspace function(String name) { checkNotNull("name", name); Workspace workspace = new WorkspaceImpl(name); workspaces.computeIfAbsent(new WorkspaceImpl(name), w -> this.createCache()); return this.getWorkspace(name); } | /**
* Returns a workspace, but if it does not exists, it creates a new one.
* @param name The name of the workspace.
* @return The existent or the new workspace.
*/ | Returns a workspace, but if it does not exists, it creates a new one | getOrCreateWorkspace | {
"repo_name": "mbiarnes/uberfire",
"path": "uberfire-backend/uberfire-backend-cdi/src/main/java/org/uberfire/backend/server/cdi/workspace/WorkspaceManager.java",
"license": "apache-2.0",
"size": 6165
} | [
"org.uberfire.backend.cdi.workspace.Workspace",
"org.uberfire.backend.server.cdi.model.WorkspaceImpl",
"org.uberfire.commons.validation.PortablePreconditions"
] | import org.uberfire.backend.cdi.workspace.Workspace; import org.uberfire.backend.server.cdi.model.WorkspaceImpl; import org.uberfire.commons.validation.PortablePreconditions; | import org.uberfire.backend.cdi.workspace.*; import org.uberfire.backend.server.cdi.model.*; import org.uberfire.commons.validation.*; | [
"org.uberfire.backend",
"org.uberfire.commons"
] | org.uberfire.backend; org.uberfire.commons; | 2,747,050 |
public BinarySchema getOrCreateSchema() {
BinarySchema schema = ctx.schemaRegistry(typeId).schema(schemaId);
if (schema == null) {
if (fieldIdLen != BinaryUtils.FIELD_ID_LEN) {
BinaryTypeImpl type = (BinaryTypeImpl)ctx.metadata(typeId);
if (type == null || type.metadata() == null)
throw new BinaryObjectException("Cannot find metadata for object with compact footer: " +
typeId);
for (BinarySchema typeSchema : type.metadata().schemas()) {
if (schemaId == typeSchema.schemaId()) {
schema = typeSchema;
break;
}
}
if (schema == null)
throw new BinaryObjectException("Cannot find schema for object with compact footer [" +
"typeId=" + typeId + ", schemaId=" + schemaId + ']');
}
else
schema = createSchema();
assert schema != null;
ctx.schemaRegistry(typeId).addSchema(schemaId, schema);
}
return schema;
} | BinarySchema function() { BinarySchema schema = ctx.schemaRegistry(typeId).schema(schemaId); if (schema == null) { if (fieldIdLen != BinaryUtils.FIELD_ID_LEN) { BinaryTypeImpl type = (BinaryTypeImpl)ctx.metadata(typeId); if (type == null type.metadata() == null) throw new BinaryObjectException(STR + typeId); for (BinarySchema typeSchema : type.metadata().schemas()) { if (schemaId == typeSchema.schemaId()) { schema = typeSchema; break; } } if (schema == null) throw new BinaryObjectException(STR + STR + typeId + STR + schemaId + ']'); } else schema = createSchema(); assert schema != null; ctx.schemaRegistry(typeId).addSchema(schemaId, schema); } return schema; } | /**
* Get or create object schema.
*
* @return Schema.
*/ | Get or create object schema | getOrCreateSchema | {
"repo_name": "ryanzz/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/binary/BinaryReaderExImpl.java",
"license": "apache-2.0",
"size": 63355
} | [
"org.apache.ignite.binary.BinaryObjectException"
] | import org.apache.ignite.binary.BinaryObjectException; | import org.apache.ignite.binary.*; | [
"org.apache.ignite"
] | org.apache.ignite; | 1,552,877 |
public byte[][] getEndKeys() throws IOException {
return getStartEndKeys().getSecond();
} | byte[][] function() throws IOException { return getStartEndKeys().getSecond(); } | /**
* Gets the ending row key for every region in the currently open table.
* <p>
* This is mainly useful for the MapReduce integration.
* @return Array of region ending row keys
* @throws IOException if a remote or network exception occurs
*/ | Gets the ending row key for every region in the currently open table. This is mainly useful for the MapReduce integration | getEndKeys | {
"repo_name": "zwqjsj0404/HBase-Research",
"path": "src/main/java/org/apache/hadoop/hbase/client/HTable.java",
"license": "apache-2.0",
"size": 45429
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 645,148 |
protected MappedFieldType provideMappedFieldType(String name) {
DoubleFieldType doubleFieldType = new DoubleFieldType();
doubleFieldType.setName(name);
doubleFieldType.setHasDocValues(true);
return doubleFieldType;
} | MappedFieldType function(String name) { DoubleFieldType doubleFieldType = new DoubleFieldType(); doubleFieldType.setName(name); doubleFieldType.setHasDocValues(true); return doubleFieldType; } | /**
* Return a field type. We use {@link DoubleFieldType} by default since it is compatible with all sort modes
* Tests that require other field type than double can override this.
*/ | Return a field type. We use <code>DoubleFieldType</code> by default since it is compatible with all sort modes Tests that require other field type than double can override this | provideMappedFieldType | {
"repo_name": "cwurm/elasticsearch",
"path": "core/src/test/java/org/elasticsearch/search/sort/AbstractSortTestCase.java",
"license": "apache-2.0",
"size": 13708
} | [
"org.elasticsearch.index.mapper.MappedFieldType",
"org.elasticsearch.index.mapper.core.LegacyDoubleFieldMapper"
] | import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.core.LegacyDoubleFieldMapper; | import org.elasticsearch.index.mapper.*; import org.elasticsearch.index.mapper.core.*; | [
"org.elasticsearch.index"
] | org.elasticsearch.index; | 2,307,092 |
public void toXML(XMLWriter generatedXML, boolean showToken) {
generatedXML.writeElement(null, "activelock", XMLWriter.OPENING);
generatedXML.writeElement(null, "locktype", XMLWriter.OPENING);
generatedXML.writeElement(null, type, XMLWriter.NO_CONTENT);
generatedXML.writeElement(null, "locktype", XMLWriter.CLOSING);
generatedXML.writeElement(null, "lockscope", XMLWriter.OPENING);
generatedXML.writeElement(null, scope, XMLWriter.NO_CONTENT);
generatedXML.writeElement(null, "lockscope", XMLWriter.CLOSING);
generatedXML.writeElement(null, "depth", XMLWriter.OPENING);
if (depth == INFINITY) {
generatedXML.writeText("Infinity");
} else {
generatedXML.writeText("0");
}
generatedXML.writeElement(null, "depth", XMLWriter.CLOSING);
generatedXML.writeElement(null, "owner", XMLWriter.OPENING);
generatedXML.writeText(owner);
generatedXML.writeElement(null, "owner", XMLWriter.CLOSING);
generatedXML.writeElement(null, "timeout", XMLWriter.OPENING);
long timeout = (expiresAt - System.currentTimeMillis()) / 1000;
generatedXML.writeText("Second-" + timeout);
generatedXML.writeElement(null, "timeout", XMLWriter.CLOSING);
generatedXML.writeElement(null, "locktoken", XMLWriter.OPENING);
if (showToken) {
Enumeration tokensList = tokens.elements();
while (tokensList.hasMoreElements()) {
generatedXML.writeElement(null, "href", XMLWriter.OPENING);
generatedXML.writeText("opaquelocktoken:"
+ tokensList.nextElement());
generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
}
} else {
generatedXML.writeElement(null, "href", XMLWriter.OPENING);
generatedXML.writeText("opaquelocktoken:dummytoken");
generatedXML.writeElement(null, "href", XMLWriter.CLOSING);
}
generatedXML.writeElement(null, "locktoken", XMLWriter.CLOSING);
generatedXML.writeElement(null, "activelock", XMLWriter.CLOSING);
}
}
// --------------------------------------------------- Property Inner Class
private class Property {
public String name;
public String value;
public String namespace;
public String namespaceAbbrev;
public int status = WebdavStatus.SC_OK;
}
};
// -------------------------------------------------------- WebdavStatus Class
class WebdavStatus {
// ----------------------------------------------------- Instance Variables
private static Hashtable mapStatusCodes = new Hashtable();
// ------------------------------------------------------ HTTP Status Codes
public static final int SC_OK = HttpServletResponse.SC_OK;
public static final int SC_CREATED = HttpServletResponse.SC_CREATED;
public static final int SC_ACCEPTED = HttpServletResponse.SC_ACCEPTED;
public static final int SC_NO_CONTENT = HttpServletResponse.SC_NO_CONTENT;
public static final int SC_MOVED_PERMANENTLY =
HttpServletResponse.SC_MOVED_PERMANENTLY;
public static final int SC_MOVED_TEMPORARILY =
HttpServletResponse.SC_MOVED_TEMPORARILY;
public static final int SC_NOT_MODIFIED =
HttpServletResponse.SC_NOT_MODIFIED;
public static final int SC_BAD_REQUEST =
HttpServletResponse.SC_BAD_REQUEST;
public static final int SC_UNAUTHORIZED =
HttpServletResponse.SC_UNAUTHORIZED;
public static final int SC_FORBIDDEN = HttpServletResponse.SC_FORBIDDEN;
public static final int SC_NOT_FOUND = HttpServletResponse.SC_NOT_FOUND;
public static final int SC_INTERNAL_SERVER_ERROR =
HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
public static final int SC_NOT_IMPLEMENTED =
HttpServletResponse.SC_NOT_IMPLEMENTED;
public static final int SC_BAD_GATEWAY =
HttpServletResponse.SC_BAD_GATEWAY;
public static final int SC_SERVICE_UNAVAILABLE =
HttpServletResponse.SC_SERVICE_UNAVAILABLE;
public static final int SC_CONTINUE = 100;
public static final int SC_METHOD_NOT_ALLOWED = 405;
public static final int SC_CONFLICT = 409;
public static final int SC_PRECONDITION_FAILED = 412;
public static final int SC_REQUEST_TOO_LONG = 413;
public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415;
// -------------------------------------------- Extended WebDav status code
public static final int SC_MULTI_STATUS = 207;
// This one colides with HTTP 1.1
// "207 Parital Update OK"
public static final int SC_UNPROCESSABLE_ENTITY = 418;
// This one colides with HTTP 1.1
// "418 Reauthentication Required"
public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419;
// This one colides with HTTP 1.1
// "419 Proxy Reauthentication Required"
public static final int SC_METHOD_FAILURE = 420;
public static final int SC_LOCKED = 423;
// ------------------------------------------------------------ Initializer
static {
// HTTP 1.0 tatus Code
addStatusCodeMap(SC_OK, "OK");
addStatusCodeMap(SC_CREATED, "Created");
addStatusCodeMap(SC_ACCEPTED, "Accepted");
addStatusCodeMap(SC_NO_CONTENT, "No Content");
addStatusCodeMap(SC_MOVED_PERMANENTLY, "Moved Permanently");
addStatusCodeMap(SC_MOVED_TEMPORARILY, "Moved Temporarily");
addStatusCodeMap(SC_NOT_MODIFIED, "Not Modified");
addStatusCodeMap(SC_BAD_REQUEST, "Bad Request");
addStatusCodeMap(SC_UNAUTHORIZED, "Unauthorized");
addStatusCodeMap(SC_FORBIDDEN, "Forbidden");
addStatusCodeMap(SC_NOT_FOUND, "Not Found");
addStatusCodeMap(SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
addStatusCodeMap(SC_NOT_IMPLEMENTED, "Not Implemented");
addStatusCodeMap(SC_BAD_GATEWAY, "Bad Gateway");
addStatusCodeMap(SC_SERVICE_UNAVAILABLE, "Service Unavailable");
addStatusCodeMap(SC_CONTINUE, "Continue");
addStatusCodeMap(SC_METHOD_NOT_ALLOWED, "Method Not Allowed");
addStatusCodeMap(SC_CONFLICT, "Conflict");
addStatusCodeMap(SC_PRECONDITION_FAILED, "Precondition Failed");
addStatusCodeMap(SC_REQUEST_TOO_LONG, "Request Too Long");
addStatusCodeMap(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type");
// WebDav Status Codes
addStatusCodeMap(SC_MULTI_STATUS, "Multi-Status");
addStatusCodeMap(SC_UNPROCESSABLE_ENTITY, "Unprocessable Entity");
addStatusCodeMap(SC_INSUFFICIENT_SPACE_ON_RESOURCE,
"Insufficient Space On Resource");
addStatusCodeMap(SC_METHOD_FAILURE, "Method Failure");
addStatusCodeMap(SC_LOCKED, "Locked");
}
// --------------------------------------------------------- Public Methods | void function(XMLWriter generatedXML, boolean showToken) { generatedXML.writeElement(null, STR, XMLWriter.OPENING); generatedXML.writeElement(null, STR, XMLWriter.OPENING); generatedXML.writeElement(null, type, XMLWriter.NO_CONTENT); generatedXML.writeElement(null, STR, XMLWriter.CLOSING); generatedXML.writeElement(null, STR, XMLWriter.OPENING); generatedXML.writeElement(null, scope, XMLWriter.NO_CONTENT); generatedXML.writeElement(null, STR, XMLWriter.CLOSING); generatedXML.writeElement(null, "depth", XMLWriter.OPENING); if (depth == INFINITY) { generatedXML.writeText(STR); } else { generatedXML.writeText("0"); } generatedXML.writeElement(null, "depth", XMLWriter.CLOSING); generatedXML.writeElement(null, "owner", XMLWriter.OPENING); generatedXML.writeText(owner); generatedXML.writeElement(null, "owner", XMLWriter.CLOSING); generatedXML.writeElement(null, STR, XMLWriter.OPENING); long timeout = (expiresAt - System.currentTimeMillis()) / 1000; generatedXML.writeText(STR + timeout); generatedXML.writeElement(null, STR, XMLWriter.CLOSING); generatedXML.writeElement(null, STR, XMLWriter.OPENING); if (showToken) { Enumeration tokensList = tokens.elements(); while (tokensList.hasMoreElements()) { generatedXML.writeElement(null, "href", XMLWriter.OPENING); generatedXML.writeText(STR + tokensList.nextElement()); generatedXML.writeElement(null, "href", XMLWriter.CLOSING); } } else { generatedXML.writeElement(null, "href", XMLWriter.OPENING); generatedXML.writeText(STR); generatedXML.writeElement(null, "href", XMLWriter.CLOSING); } generatedXML.writeElement(null, STR, XMLWriter.CLOSING); generatedXML.writeElement(null, STR, XMLWriter.CLOSING); } } private class Property { public String name; public String value; public String namespace; public String namespaceAbbrev; public int status = WebdavStatus.SC_OK; } }; class WebdavStatus { private static Hashtable mapStatusCodes = new Hashtable(); public static final int SC_OK = HttpServletResponse.SC_OK; public static final int SC_CREATED = HttpServletResponse.SC_CREATED; public static final int SC_ACCEPTED = HttpServletResponse.SC_ACCEPTED; public static final int SC_NO_CONTENT = HttpServletResponse.SC_NO_CONTENT; public static final int SC_MOVED_PERMANENTLY = HttpServletResponse.SC_MOVED_PERMANENTLY; public static final int SC_MOVED_TEMPORARILY = HttpServletResponse.SC_MOVED_TEMPORARILY; public static final int SC_NOT_MODIFIED = HttpServletResponse.SC_NOT_MODIFIED; public static final int SC_BAD_REQUEST = HttpServletResponse.SC_BAD_REQUEST; public static final int SC_UNAUTHORIZED = HttpServletResponse.SC_UNAUTHORIZED; public static final int SC_FORBIDDEN = HttpServletResponse.SC_FORBIDDEN; public static final int SC_NOT_FOUND = HttpServletResponse.SC_NOT_FOUND; public static final int SC_INTERNAL_SERVER_ERROR = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; public static final int SC_NOT_IMPLEMENTED = HttpServletResponse.SC_NOT_IMPLEMENTED; public static final int SC_BAD_GATEWAY = HttpServletResponse.SC_BAD_GATEWAY; public static final int SC_SERVICE_UNAVAILABLE = HttpServletResponse.SC_SERVICE_UNAVAILABLE; public static final int SC_CONTINUE = 100; public static final int SC_METHOD_NOT_ALLOWED = 405; public static final int SC_CONFLICT = 409; public static final int SC_PRECONDITION_FAILED = 412; public static final int SC_REQUEST_TOO_LONG = 413; public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; public static final int SC_MULTI_STATUS = 207; public static final int SC_UNPROCESSABLE_ENTITY = 418; public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; public static final int SC_METHOD_FAILURE = 420; public static final int SC_LOCKED = 423; static { addStatusCodeMap(SC_OK, "OK"); addStatusCodeMap(SC_CREATED, STR); addStatusCodeMap(SC_ACCEPTED, STR); addStatusCodeMap(SC_NO_CONTENT, STR); addStatusCodeMap(SC_MOVED_PERMANENTLY, STR); addStatusCodeMap(SC_MOVED_TEMPORARILY, STR); addStatusCodeMap(SC_NOT_MODIFIED, STR); addStatusCodeMap(SC_BAD_REQUEST, STR); addStatusCodeMap(SC_UNAUTHORIZED, STR); addStatusCodeMap(SC_FORBIDDEN, STR); addStatusCodeMap(SC_NOT_FOUND, STR); addStatusCodeMap(SC_INTERNAL_SERVER_ERROR, STR); addStatusCodeMap(SC_NOT_IMPLEMENTED, STR); addStatusCodeMap(SC_BAD_GATEWAY, STR); addStatusCodeMap(SC_SERVICE_UNAVAILABLE, STR); addStatusCodeMap(SC_CONTINUE, STR); addStatusCodeMap(SC_METHOD_NOT_ALLOWED, STR); addStatusCodeMap(SC_CONFLICT, STR); addStatusCodeMap(SC_PRECONDITION_FAILED, STR); addStatusCodeMap(SC_REQUEST_TOO_LONG, STR); addStatusCodeMap(SC_UNSUPPORTED_MEDIA_TYPE, STR); addStatusCodeMap(SC_MULTI_STATUS, STR); addStatusCodeMap(SC_UNPROCESSABLE_ENTITY, STR); addStatusCodeMap(SC_INSUFFICIENT_SPACE_ON_RESOURCE, STR); addStatusCodeMap(SC_METHOD_FAILURE, STR); addStatusCodeMap(SC_LOCKED, STR); } | /**
* Get an XML representation of this lock token. This method will
* append an XML fragment to the given XML writer.
*/ | Get an XML representation of this lock token. This method will append an XML fragment to the given XML writer | toXML | {
"repo_name": "bnguyen82/stuff-projects",
"path": "HowTomcatWorks/src/org/apache/catalina/servlets/WebdavServlet.java",
"license": "mit",
"size": 105726
} | [
"java.util.Enumeration",
"java.util.Hashtable",
"javax.servlet.http.HttpServletResponse",
"org.apache.catalina.util.XMLWriter"
] | import java.util.Enumeration; import java.util.Hashtable; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.util.XMLWriter; | import java.util.*; import javax.servlet.http.*; import org.apache.catalina.util.*; | [
"java.util",
"javax.servlet",
"org.apache.catalina"
] | java.util; javax.servlet; org.apache.catalina; | 546,474 |
public static boolean ensurePathExists(File path, boolean isDir) {
if (!isSdcardMounted()) {
return false;
}
if (isSdcardFull()) {
return false;
}
return isDir ? ensureDirExists(path) : ensureParentExists(path);
} | static boolean function(File path, boolean isDir) { if (!isSdcardMounted()) { return false; } if (isSdcardFull()) { return false; } return isDir ? ensureDirExists(path) : ensureParentExists(path); } | /**
* ensure dir or parent dir for a given path exists.
* @param path the given path
* @param isDir whether the given path is a dir or a file
* @return true on success ; false on fail
*/ | ensure dir or parent dir for a given path exists | ensurePathExists | {
"repo_name": "liuxu0703/AppFrame",
"path": "lib_frame/src/main/java/lx/af/utils/PathUtils.java",
"license": "apache-2.0",
"size": 8398
} | [
"java.io.File"
] | import java.io.File; | import java.io.*; | [
"java.io"
] | java.io; | 921,902 |
public boolean verifySignature() {
if (getSignature() == null) {
//if (_log.shouldLog(Log.WARN)) _log.warn("Signature is null!");
return false;
}
if (getDestination() == null) {
//if (_log.shouldLog(Log.WARN)) _log.warn("Destination is null!");
return false;
}
if (getCreationDate() == null) {
//if (_log.shouldLog(Log.WARN)) _log.warn("Date is null!");
return false;
}
if (tooOld()) {
//if (_log.shouldLog(Log.WARN)) _log.warn("Too old!");
return false;
}
byte data[] = getBytes();
if (data == null) {
//if (_log.shouldLog(Log.WARN)) _log.warn("Bytes could not be found - wtf?");
return false;
}
boolean ok = DSAEngine.getInstance().verifySignature(getSignature(), data,
getDestination().getSigningPublicKey());
if (!ok) {
Log log = I2PAppContext.getGlobalContext().logManager().getLog(SessionConfig.class);
if (log.shouldLog(Log.WARN)) log.warn("DSA signature failed!");
}
return ok;
} | boolean function() { if (getSignature() == null) { return false; } if (getDestination() == null) { return false; } if (getCreationDate() == null) { return false; } if (tooOld()) { return false; } byte data[] = getBytes(); if (data == null) { return false; } boolean ok = DSAEngine.getInstance().verifySignature(getSignature(), data, getDestination().getSigningPublicKey()); if (!ok) { Log log = I2PAppContext.getGlobalContext().logManager().getLog(SessionConfig.class); if (log.shouldLog(Log.WARN)) log.warn(STR); } return ok; } | /**
* Verify that the signature matches the destination's signing public key.
*
* Note that this also returns false if the creation date is too far in the
* past or future. See tooOld() and getCreationDate().
*
* @return true only if the signature matches
*/ | Verify that the signature matches the destination's signing public key. Note that this also returns false if the creation date is too far in the past or future. See tooOld() and getCreationDate() | verifySignature | {
"repo_name": "NoYouShutup/CryptMeme",
"path": "CryptMeme/core/java/src/net/i2p/data/i2cp/SessionConfig.java",
"license": "mit",
"size": 9022
} | [
"net.i2p.I2PAppContext",
"net.i2p.crypto.DSAEngine",
"net.i2p.util.Log"
] | import net.i2p.I2PAppContext; import net.i2p.crypto.DSAEngine; import net.i2p.util.Log; | import net.i2p.*; import net.i2p.crypto.*; import net.i2p.util.*; | [
"net.i2p",
"net.i2p.crypto",
"net.i2p.util"
] | net.i2p; net.i2p.crypto; net.i2p.util; | 27,940 |
void close(@Nullable String message);
}
private static final class CloseableServerStreamIterator<T> implements CloseableIterator<T> {
private final ServerStream<T> stream;
private final Iterator<T> iterator;
public CloseableServerStreamIterator(ServerStream<T> stream) {
this.stream = stream;
this.iterator = stream.iterator();
} | void close(@Nullable String message); } private static final class CloseableServerStreamIterator<T> implements CloseableIterator<T> { private final ServerStream<T> stream; private final Iterator<T> iterator; public CloseableServerStreamIterator(ServerStream<T> stream) { this.stream = stream; this.iterator = stream.iterator(); } | /**
* Closes the iterator, freeing any underlying resources.
*
* @param message a message to include in the final RPC status
*/ | Closes the iterator, freeing any underlying resources | close | {
"repo_name": "vam-google/google-cloud-java",
"path": "google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/SpannerImpl.java",
"license": "apache-2.0",
"size": 111066
} | [
"com.google.api.gax.rpc.ServerStream",
"java.util.Iterator",
"javax.annotation.Nullable"
] | import com.google.api.gax.rpc.ServerStream; import java.util.Iterator; import javax.annotation.Nullable; | import com.google.api.gax.rpc.*; import java.util.*; import javax.annotation.*; | [
"com.google.api",
"java.util",
"javax.annotation"
] | com.google.api; java.util; javax.annotation; | 1,741,996 |
public static URL getIconUrl(String name) {
String key = Objects.requireNonNull(name, "icon name");
if (!KEY_TO_ICON.containsKey(key)) {
LOGGER.warn("Could not find icon url by name " + name + ", so falling back on default icon "
+ DEFAULT_ICON_PATH);
}
String path = KEY_TO_ICON.getOrDefault(key, DEFAULT_ICON_PATH);
return Objects.requireNonNull(IconTheme.class.getResource(path), "Path must not be null for key " + key);
} | static URL function(String name) { String key = Objects.requireNonNull(name, STR); if (!KEY_TO_ICON.containsKey(key)) { LOGGER.warn(STR + name + STR + DEFAULT_ICON_PATH); } String path = KEY_TO_ICON.getOrDefault(key, DEFAULT_ICON_PATH); return Objects.requireNonNull(IconTheme.class.getResource(path), STR + key); } | /**
* Looks up the URL for the image representing the given function, in the resource
* file listing images.
*
* @param name The name of the icon, such as "open", "save", "saveAs" etc.
* @return The URL to the actual image to use.
*/ | Looks up the URL for the image representing the given function, in the resource file listing images | getIconUrl | {
"repo_name": "Mr-DLib/jabref",
"path": "src/main/java/net/sf/jabref/gui/IconTheme.java",
"license": "mit",
"size": 13215
} | [
"java.util.Objects"
] | import java.util.Objects; | import java.util.*; | [
"java.util"
] | java.util; | 632,927 |
protected void onPrepareRequest(HttpUriRequest request) throws IOException {
// Nothing.
}
public static final class HttpPatch extends HttpEntityEnclosingRequestBase {
public final static String METHOD_NAME = "PATCH";
public HttpPatch() {
super();
}
public HttpPatch(final URI uri) {
super();
setURI(uri);
}
public HttpPatch(final String uri) {
super();
setURI(URI.create(uri));
} | void function(HttpUriRequest request) throws IOException { } public static final class HttpPatch extends HttpEntityEnclosingRequestBase { public final static String METHOD_NAME = "PATCH"; public HttpPatch() { super(); } public HttpPatch(final URI uri) { super(); setURI(uri); } public HttpPatch(final String uri) { super(); setURI(URI.create(uri)); } | /**
* Called before the request is executed using the underlying HttpClient.
*
* <p>Overwrite in subclasses to augment the request.</p>
*/ | Called before the request is executed using the underlying HttpClient. Overwrite in subclasses to augment the request | onPrepareRequest | {
"repo_name": "amirlotfi/Nikagram",
"path": "app/src/main/java/ir/nikagram/messenger/volley/toolbox/HttpClientStack.java",
"license": "gpl-2.0",
"size": 7524
} | [
"java.io.IOException",
"java.net.URI",
"org.apache.http.client.methods.HttpEntityEnclosingRequestBase",
"org.apache.http.client.methods.HttpUriRequest"
] | import java.io.IOException; import java.net.URI; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpUriRequest; | import java.io.*; import java.net.*; import org.apache.http.client.methods.*; | [
"java.io",
"java.net",
"org.apache.http"
] | java.io; java.net; org.apache.http; | 1,592,472 |
public ArrayList<String> serviceName_option_GET(String serviceName) throws IOException {
String qPath = "/dbaas/logs/{serviceName}/option";
StringBuilder sb = path(qPath, serviceName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | ArrayList<String> function(String serviceName) throws IOException { String qPath = STR; StringBuilder sb = path(qPath, serviceName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); } | /**
* Returns the subscribed additional options
*
* REST: GET /dbaas/logs/{serviceName}/option
* @param serviceName [required] Service name
*/ | Returns the subscribed additional options | serviceName_option_GET | {
"repo_name": "UrielCh/ovh-java-sdk",
"path": "ovh-java-sdk-dbaaslogs/src/main/java/net/minidev/ovh/api/ApiOvhDbaaslogs.java",
"license": "bsd-3-clause",
"size": 82370
} | [
"java.io.IOException",
"java.util.ArrayList"
] | import java.io.IOException; import java.util.ArrayList; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 754,084 |
@Path("/disableOSPFInterfaces")
@POST
@Consumes(MediaType.APPLICATION_XML)
public void disableOSPFInterfaces(List<OSPFProtocolEndpoint> interfaces) throws CapabilityException; | @Path(STR) @Consumes(MediaType.APPLICATION_XML) void function(List<OSPFProtocolEndpoint> interfaces) throws CapabilityException; | /**
* Disable OSPF in given interfaces, if they are already configured.
*
* @param interfaces
* @throws CapabilityException
*/ | Disable OSPF in given interfaces, if they are already configured | disableOSPFInterfaces | {
"repo_name": "dana-i2cat/opennaas-routing-nfv",
"path": "extensions/bundles/router.capability.ospf/src/main/java/org/opennaas/extensions/router/capability/ospf/IOSPFCapability.java",
"license": "lgpl-3.0",
"size": 4868
} | [
"java.util.List",
"javax.ws.rs.Consumes",
"javax.ws.rs.Path",
"javax.ws.rs.core.MediaType",
"org.opennaas.core.resources.capability.CapabilityException",
"org.opennaas.extensions.router.model.OSPFProtocolEndpoint"
] | import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import org.opennaas.core.resources.capability.CapabilityException; import org.opennaas.extensions.router.model.OSPFProtocolEndpoint; | import java.util.*; import javax.ws.rs.*; import javax.ws.rs.core.*; import org.opennaas.core.resources.capability.*; import org.opennaas.extensions.router.model.*; | [
"java.util",
"javax.ws",
"org.opennaas.core",
"org.opennaas.extensions"
] | java.util; javax.ws; org.opennaas.core; org.opennaas.extensions; | 1,313,611 |
public CharMatcher and(CharMatcher other) {
return new And(this, checkNotNull(other));
}
private static class And extends CharMatcher {
final CharMatcher first;
final CharMatcher second;
And(CharMatcher a, CharMatcher b) {
this(a, b, "CharMatcher.and(" + a + ", " + b + ")");
}
And(CharMatcher a, CharMatcher b, String description) {
super(description);
first = checkNotNull(a);
second = checkNotNull(b);
} | CharMatcher function(CharMatcher other) { return new And(this, checkNotNull(other)); } private static class And extends CharMatcher { final CharMatcher first; final CharMatcher second; And(CharMatcher a, CharMatcher b) { this(a, b, STR + a + STR + b + ")"); } And(CharMatcher a, CharMatcher b, String description) { super(description); first = checkNotNull(a); second = checkNotNull(b); } | /**
* Returns a matcher that matches any character matched by both this matcher and {@code other}.
*/ | Returns a matcher that matches any character matched by both this matcher and other | and | {
"repo_name": "user234/setyon-guava-libraries-clone",
"path": "guava-gwt/src-super/com/google/common/base/super/com/google/common/base/CharMatcher.java",
"license": "apache-2.0",
"size": 38127
} | [
"com.google.common.base.Preconditions"
] | import com.google.common.base.Preconditions; | import com.google.common.base.*; | [
"com.google.common"
] | com.google.common; | 2,297,142 |
public boolean canBeSteered()
{
Entity entity = this.getControllingPassenger();
if (!(entity instanceof EntityPlayer))
{
return false;
}
else
{
EntityPlayer entityplayer = (EntityPlayer)entity;
ItemStack itemstack = entityplayer.getHeldItemMainhand();
if (itemstack != null && itemstack.getItem() == Items.CARROT_ON_A_STICK)
{
return true;
}
else
{
itemstack = entityplayer.getHeldItemOffhand();
return itemstack != null && itemstack.getItem() == Items.CARROT_ON_A_STICK;
}
}
} | boolean function() { Entity entity = this.getControllingPassenger(); if (!(entity instanceof EntityPlayer)) { return false; } else { EntityPlayer entityplayer = (EntityPlayer)entity; ItemStack itemstack = entityplayer.getHeldItemMainhand(); if (itemstack != null && itemstack.getItem() == Items.CARROT_ON_A_STICK) { return true; } else { itemstack = entityplayer.getHeldItemOffhand(); return itemstack != null && itemstack.getItem() == Items.CARROT_ON_A_STICK; } } } | /**
* returns true if all the conditions for steering the entity are met. For pigs, this is true if it is being ridden
* by a player and the player is holding a carrot-on-a-stick
*/ | returns true if all the conditions for steering the entity are met. For pigs, this is true if it is being ridden by a player and the player is holding a carrot-on-a-stick | canBeSteered | {
"repo_name": "Discult/Bettercraft-Mod",
"path": "main/java/jordan/bettercraft/init/mobs/entitys/EntityBoar.java",
"license": "unlicense",
"size": 11660
} | [
"net.minecraft.entity.Entity",
"net.minecraft.entity.player.EntityPlayer",
"net.minecraft.init.Items",
"net.minecraft.item.ItemStack"
] | import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; | import net.minecraft.entity.*; import net.minecraft.entity.player.*; import net.minecraft.init.*; import net.minecraft.item.*; | [
"net.minecraft.entity",
"net.minecraft.init",
"net.minecraft.item"
] | net.minecraft.entity; net.minecraft.init; net.minecraft.item; | 426,238 |
public void setMessenger(Messenger msg) {
mClientProxy = DownloaderClientMarshaller.CreateProxy(msg);
if (null != mProgressInfo) {
mClientProxy.onDownloadProgress(mProgressInfo);
}
if (mState != -1) {
mClientProxy.onDownloadStateChanged(mState);
}
}
DownloadNotification(Context ctx, CharSequence applicationLabel) {
mState = -1;
mContext = ctx;
mLabel = applicationLabel;
mNotificationManager = (NotificationManager)
mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mActiveDownloadBuilder = new NotificationCompat.Builder(ctx);
mBuilder = new NotificationCompat.Builder(ctx);
// Set Notification category and priorities to something that makes sense for a long
// lived background task.
mActiveDownloadBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
mActiveDownloadBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS);
mBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
mBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS);
mCurrentBuilder = mBuilder;
} | void function(Messenger msg) { mClientProxy = DownloaderClientMarshaller.CreateProxy(msg); if (null != mProgressInfo) { mClientProxy.onDownloadProgress(mProgressInfo); } if (mState != -1) { mClientProxy.onDownloadStateChanged(mState); } } DownloadNotification(Context ctx, CharSequence applicationLabel) { mState = -1; mContext = ctx; mLabel = applicationLabel; mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE); mActiveDownloadBuilder = new NotificationCompat.Builder(ctx); mBuilder = new NotificationCompat.Builder(ctx); mActiveDownloadBuilder.setPriority(NotificationCompat.PRIORITY_LOW); mActiveDownloadBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS); mBuilder.setPriority(NotificationCompat.PRIORITY_LOW); mBuilder.setCategory(NotificationCompat.CATEGORY_PROGRESS); mCurrentBuilder = mBuilder; } | /**
* Called in response to onClientUpdated. Creates a new proxy and notifies
* it of the current state.
*
* @param msg the client Messenger to notify
*/ | Called in response to onClientUpdated. Creates a new proxy and notifies it of the current state | setMessenger | {
"repo_name": "honix/godot",
"path": "platform/android/java/lib/src/com/google/android/vending/expansion/downloader/impl/DownloadNotification.java",
"license": "mit",
"size": 9288
} | [
"android.app.NotificationManager",
"android.content.Context",
"android.os.Messenger",
"androidx.core.app.NotificationCompat",
"com.google.android.vending.expansion.downloader.DownloaderClientMarshaller"
] | import android.app.NotificationManager; import android.content.Context; import android.os.Messenger; import androidx.core.app.NotificationCompat; import com.google.android.vending.expansion.downloader.DownloaderClientMarshaller; | import android.app.*; import android.content.*; import android.os.*; import androidx.core.app.*; import com.google.android.vending.expansion.downloader.*; | [
"android.app",
"android.content",
"android.os",
"androidx.core",
"com.google.android"
] | android.app; android.content; android.os; androidx.core; com.google.android; | 1,867,985 |
public static void validateEqualClass(final Object object1, final Object object2)
{
try
{
if ((object1 != object2) && (object1.getClass() != object2.getClass()))
{
throw new ClassCastException(cannotCompareMessage(object1.getClass(),
object2.getClass()));
}
}
catch (final IllegalArgumentException e)
{
throw new BusinessRuleException(e.getMessage());
}
} | static void function(final Object object1, final Object object2) { try { if ((object1 != object2) && (object1.getClass() != object2.getClass())) { throw new ClassCastException(cannotCompareMessage(object1.getClass(), object2.getClass())); } } catch (final IllegalArgumentException e) { throw new BusinessRuleException(e.getMessage()); } } | /**
* A useful check for {@link Comparable#compareTo(Object)} methods.
*
* @param object1
* @param object2
*/ | A useful check for <code>Comparable#compareTo(Object)</code> methods | validateEqualClass | {
"repo_name": "openfurther/further-open-core",
"path": "core/core-api/src/main/java/edu/utah/further/core/api/message/ValidationUtil.java",
"license": "apache-2.0",
"size": 7320
} | [
"edu.utah.further.core.api.exception.BusinessRuleException"
] | import edu.utah.further.core.api.exception.BusinessRuleException; | import edu.utah.further.core.api.exception.*; | [
"edu.utah.further"
] | edu.utah.further; | 645,073 |
public static UniqueId randomId() {
byte[] b = new byte[LENGTH];
new Random().nextBytes(b);
return new UniqueId(b);
}
public UniqueId(byte[] id) {
super(id);
} | static UniqueId function() { byte[] b = new byte[LENGTH]; new Random().nextBytes(b); return new UniqueId(b); } public UniqueId(byte[] id) { super(id); } | /**
* Generate an UniqueId with random value.
*/ | Generate an UniqueId with random value | randomId | {
"repo_name": "ujvl/ray-ng",
"path": "java/api/src/main/java/org/ray/api/id/UniqueId.java",
"license": "apache-2.0",
"size": 1190
} | [
"java.util.Random"
] | import java.util.Random; | import java.util.*; | [
"java.util"
] | java.util; | 1,813,764 |
void enterSerdeClass(@NotNull CQLParser.SerdeClassContext ctx);
void exitSerdeClass(@NotNull CQLParser.SerdeClassContext ctx); | void enterSerdeClass(@NotNull CQLParser.SerdeClassContext ctx); void exitSerdeClass(@NotNull CQLParser.SerdeClassContext ctx); | /**
* Exit a parse tree produced by {@link CQLParser#serdeClass}.
* @param ctx the parse tree
*/ | Exit a parse tree produced by <code>CQLParser#serdeClass</code> | exitSerdeClass | {
"repo_name": "jack6215/StreamCQL",
"path": "cql/src/main/java/com/huawei/streaming/cql/semanticanalyzer/parser/CQLParserListener.java",
"license": "apache-2.0",
"size": 62500
} | [
"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; | 2,115,616 |
private void handleRequests() {
ZabCoinTossingHeader hdrReq = null;
//long currentTime = 0;
while (running) {
try {
hdrReq=queuedMessages.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
long new_zxid = getNewZxid();
if (!stats.isWarmup()) {
stats.incNumRequest();
}
ZabCoinTossingHeader hdrProposal = new ZabCoinTossingHeader(ZabCoinTossingHeader.PROPOSAL, new_zxid, hdrReq.getMessageId());
Message proposalMessage=new Message().putHeader(this.id, hdrProposal);
proposalMessage.setSrc(local_addr);
proposalMessage.setBuffer(new byte[1000]);
proposalMessage.setFlag(Message.Flag.DONT_BUNDLE);
Proposal p = new Proposal();
p.setMessageId(hdrReq.getMessageId());
p.setZxid(new_zxid);
p.AckCount++;
outstandingProposals.put(new_zxid, p);
queuedProposalMessage.put(new_zxid, hdrProposal);
try{
for (Address address : zabMembers) {
if(address.equals(leader))
continue;
if (!stats.isWarmup()) {
countMessageLeader.incrementAndGet();
stats.incCountMessageLeader();
}
Message cpy = proposalMessage.copy();
cpy.setDest(address);
down_prot.down(new Event(Event.MSG, cpy));
}
}catch(Exception ex) {
log.error("failed proposing message to members");
}
}
}
}
| void function() { ZabCoinTossingHeader hdrReq = null; while (running) { try { hdrReq=queuedMessages.take(); } catch (InterruptedException e) { e.printStackTrace(); } long new_zxid = getNewZxid(); if (!stats.isWarmup()) { stats.incNumRequest(); } ZabCoinTossingHeader hdrProposal = new ZabCoinTossingHeader(ZabCoinTossingHeader.PROPOSAL, new_zxid, hdrReq.getMessageId()); Message proposalMessage=new Message().putHeader(this.id, hdrProposal); proposalMessage.setSrc(local_addr); proposalMessage.setBuffer(new byte[1000]); proposalMessage.setFlag(Message.Flag.DONT_BUNDLE); Proposal p = new Proposal(); p.setMessageId(hdrReq.getMessageId()); p.setZxid(new_zxid); p.AckCount++; outstandingProposals.put(new_zxid, p); queuedProposalMessage.put(new_zxid, hdrProposal); try{ for (Address address : zabMembers) { if(address.equals(leader)) continue; if (!stats.isWarmup()) { countMessageLeader.incrementAndGet(); stats.incCountMessageLeader(); } Message cpy = proposalMessage.copy(); cpy.setDest(address); down_prot.down(new Event(Event.MSG, cpy)); } }catch(Exception ex) { log.error(STR); } } } } | /**
* create a proposal and send it out to all the members
*
* @param message
*/ | create a proposal and send it out to all the members | handleRequests | {
"repo_name": "ibrahimshbat/JGroups",
"path": "src/org/jgroups/protocols/jzookeeper/tailtimeout/ZabCoinTossing.java",
"license": "apache-2.0",
"size": 24438
} | [
"org.jgroups.Address",
"org.jgroups.Event",
"org.jgroups.Message",
"org.jgroups.protocols.jzookeeper.Proposal",
"org.jgroups.protocols.jzookeeper.ZabCoinTossingHeader"
] | import org.jgroups.Address; import org.jgroups.Event; import org.jgroups.Message; import org.jgroups.protocols.jzookeeper.Proposal; import org.jgroups.protocols.jzookeeper.ZabCoinTossingHeader; | import org.jgroups.*; import org.jgroups.protocols.jzookeeper.*; | [
"org.jgroups",
"org.jgroups.protocols"
] | org.jgroups; org.jgroups.protocols; | 2,402,942 |
@Override
public Metadata.Custom apply(Metadata.Custom part) {
return new TransformMetadata(resetMode);
} | Metadata.Custom function(Metadata.Custom part) { return new TransformMetadata(resetMode); } | /**
* Merge the diff with the transform metadata.
* @param part The current transform metadata.
* @return The new transform metadata.
*/ | Merge the diff with the transform metadata | apply | {
"repo_name": "GlenRSmith/elasticsearch",
"path": "x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/transform/TransformMetadata.java",
"license": "apache-2.0",
"size": 5422
} | [
"org.elasticsearch.cluster.metadata.Metadata"
] | import org.elasticsearch.cluster.metadata.Metadata; | import org.elasticsearch.cluster.metadata.*; | [
"org.elasticsearch.cluster"
] | org.elasticsearch.cluster; | 163,183 |
@Override
public Adapter createVarianceAdapter() {
if (varianceItemProvider == null) {
varianceItemProvider = new VarianceItemProvider(this);
}
return varianceItemProvider;
}
protected NumericLiteralItemProvider numericLiteralItemProvider; | Adapter function() { if (varianceItemProvider == null) { varianceItemProvider = new VarianceItemProvider(this); } return varianceItemProvider; } protected NumericLiteralItemProvider numericLiteralItemProvider; | /**
* This creates an adapter for a {@link de.uka.ipd.sdq.dsexplore.qml.contract.Variance}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This creates an adapter for a <code>de.uka.ipd.sdq.dsexplore.qml.contract.Variance</code>. | createVarianceAdapter | {
"repo_name": "KAMP-Research/KAMP",
"path": "bundles/Toometa/de.uka.ipd.sdq.dsexplore.qml.contract.edit/src/de/uka/ipd/sdq/dsexplore/qml/contract/provider/QMLContractItemProviderAdapterFactory.java",
"license": "apache-2.0",
"size": 16428
} | [
"org.eclipse.emf.common.notify.Adapter"
] | import org.eclipse.emf.common.notify.Adapter; | import org.eclipse.emf.common.notify.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 920,251 |
public void addAdditionalClasses(Class... additionalClasses) {
for(Class cls : additionalClasses)
this.additionalClasses.add(cls);
}
private List<Class> additionalClasses = new ArrayList<Class>();
private Pool.Marshaller marshallers;
protected JAXBRIContext jaxbContext;
private String wsdlLocation;
private QName serviceName;
private QName portName;
private QName portTypeName;
private Map<Method,JavaMethodImpl> methodToJM = new HashMap<Method, JavaMethodImpl>();
private Map<QName,JavaMethodImpl> nameToJM = new HashMap<QName, JavaMethodImpl>();
private Map<QName, JavaMethodImpl> wsdlOpToJM = new HashMap<QName, JavaMethodImpl>();
private List<JavaMethodImpl> javaMethods = new ArrayList<JavaMethodImpl>();
private final Map<TypeReference, Bridge> bridgeMap = new HashMap<TypeReference, Bridge>();
protected final QName emptyBodyName = new QName("");
private String targetNamespace = "";
private List<String> knownNamespaceURIs = null;
private WSDLPortImpl port;
private final WebServiceFeature[] features;
private static final Logger LOGGER = Logger.getLogger(AbstractSEIModelImpl.class.getName()); | void function(Class... additionalClasses) { for(Class cls : additionalClasses) this.additionalClasses.add(cls); } private List<Class> additionalClasses = new ArrayList<Class>(); private Pool.Marshaller marshallers; protected JAXBRIContext jaxbContext; private String wsdlLocation; private QName serviceName; private QName portName; private QName portTypeName; private Map<Method,JavaMethodImpl> methodToJM = new HashMap<Method, JavaMethodImpl>(); private Map<QName,JavaMethodImpl> nameToJM = new HashMap<QName, JavaMethodImpl>(); private Map<QName, JavaMethodImpl> wsdlOpToJM = new HashMap<QName, JavaMethodImpl>(); private List<JavaMethodImpl> javaMethods = new ArrayList<JavaMethodImpl>(); private final Map<TypeReference, Bridge> bridgeMap = new HashMap<TypeReference, Bridge>(); protected final QName emptyBodyName = new QName(STR"; private List<String> knownNamespaceURIs = null; private WSDLPortImpl port; private final WebServiceFeature[] features; private static final Logger LOGGER = Logger.getLogger(AbstractSEIModelImpl.class.getName()); | /**
* Adds additional classes obtained from {@link XmlSeeAlso} annotation. In starting
* from wsdl case these classes would most likely be JAXB ObjectFactory that references other classes.
*/ | Adds additional classes obtained from <code>XmlSeeAlso</code> annotation. In starting from wsdl case these classes would most likely be JAXB ObjectFactory that references other classes | addAdditionalClasses | {
"repo_name": "axDev-JDK/jaxws",
"path": "src/share/jaxws_classes/com/sun/xml/internal/ws/model/AbstractSEIModelImpl.java",
"license": "gpl-2.0",
"size": 14773
} | [
"com.sun.xml.internal.bind.api.Bridge",
"com.sun.xml.internal.bind.api.JAXBRIContext",
"com.sun.xml.internal.bind.api.TypeReference",
"com.sun.xml.internal.ws.model.wsdl.WSDLPortImpl",
"com.sun.xml.internal.ws.util.Pool",
"java.lang.reflect.Method",
"java.util.ArrayList",
"java.util.HashMap",
"java.... | import com.sun.xml.internal.bind.api.Bridge; import com.sun.xml.internal.bind.api.JAXBRIContext; import com.sun.xml.internal.bind.api.TypeReference; import com.sun.xml.internal.ws.model.wsdl.WSDLPortImpl; import com.sun.xml.internal.ws.util.Pool; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import javax.xml.namespace.QName; import javax.xml.ws.WebServiceFeature; | import com.sun.xml.internal.bind.api.*; import com.sun.xml.internal.ws.model.wsdl.*; import com.sun.xml.internal.ws.util.*; import java.lang.reflect.*; import java.util.*; import java.util.logging.*; import javax.xml.namespace.*; import javax.xml.ws.*; | [
"com.sun.xml",
"java.lang",
"java.util",
"javax.xml"
] | com.sun.xml; java.lang; java.util; javax.xml; | 2,498,495 |
@Override
protected void build() {
boolean addSubs = MyPreferences.addSubCategoriesToSum(context);
if (addSubs) {
SQLiteDatabase db = em.db();
Cursor cursor = null;
try {
long categoryId = filterIds.get(currentFilterOrder);
Category parent = em.getCategory(categoryId);
String where = CategoryColumns.left+" BETWEEN ? AND ?";
String[] pars = new String[]{String.valueOf(parent.left), String.valueOf(parent.right)};
cursor = db.query(DatabaseHelper.CATEGORY_TABLE, new String[]{CategoryColumns._id.name()}, where, pars, null, null, null);
int[] categories = new int[cursor.getCount()+1];
int i=0;
while (cursor.moveToNext()) {
categories[i] = cursor.getInt(0);
i++;
}
categories[i] = filterIds.get(currentFilterOrder).intValue();
data = new ReportDataByPeriod(context, startPeriod, periodLength, currency, columnFilter, categories, em);
} finally {
if (cursor!=null) cursor.close();
}
} else {
// only root category
data = new ReportDataByPeriod(context, startPeriod, periodLength, currency, columnFilter, filterIds.get(currentFilterOrder).intValue(), em);
}
points = new ArrayList<>();
List<PeriodValue> pvs = data.getPeriodValues();
for (PeriodValue pv : pvs) {
points.add(new Report2DPoint(pv));
}
} | void function() { boolean addSubs = MyPreferences.addSubCategoriesToSum(context); if (addSubs) { SQLiteDatabase db = em.db(); Cursor cursor = null; try { long categoryId = filterIds.get(currentFilterOrder); Category parent = em.getCategory(categoryId); String where = CategoryColumns.left+STR; String[] pars = new String[]{String.valueOf(parent.left), String.valueOf(parent.right)}; cursor = db.query(DatabaseHelper.CATEGORY_TABLE, new String[]{CategoryColumns._id.name()}, where, pars, null, null, null); int[] categories = new int[cursor.getCount()+1]; int i=0; while (cursor.moveToNext()) { categories[i] = cursor.getInt(0); i++; } categories[i] = filterIds.get(currentFilterOrder).intValue(); data = new ReportDataByPeriod(context, startPeriod, periodLength, currency, columnFilter, categories, em); } finally { if (cursor!=null) cursor.close(); } } else { data = new ReportDataByPeriod(context, startPeriod, periodLength, currency, columnFilter, filterIds.get(currentFilterOrder).intValue(), em); } points = new ArrayList<>(); List<PeriodValue> pvs = data.getPeriodValues(); for (PeriodValue pv : pvs) { points.add(new Report2DPoint(pv)); } } | /**
* Request data and fill data objects (list of points, max, min, etc.)
*/ | Request data and fill data objects (list of points, max, min, etc.) | build | {
"repo_name": "emmanuel-florent/flowzr-android-black",
"path": "src/main/java/com/flowzr/report/CategoryByPeriodReport.java",
"license": "gpl-2.0",
"size": 4056
} | [
"android.database.Cursor",
"android.database.sqlite.SQLiteDatabase",
"com.flowzr.db.DatabaseHelper",
"com.flowzr.graph.Report2DPoint",
"com.flowzr.model.Category",
"com.flowzr.model.PeriodValue",
"com.flowzr.model.ReportDataByPeriod",
"com.flowzr.utils.MyPreferences",
"java.util.ArrayList",
"java.... | import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.flowzr.db.DatabaseHelper; import com.flowzr.graph.Report2DPoint; import com.flowzr.model.Category; import com.flowzr.model.PeriodValue; import com.flowzr.model.ReportDataByPeriod; import com.flowzr.utils.MyPreferences; import java.util.ArrayList; import java.util.List; | import android.database.*; import android.database.sqlite.*; import com.flowzr.db.*; import com.flowzr.graph.*; import com.flowzr.model.*; import com.flowzr.utils.*; import java.util.*; | [
"android.database",
"com.flowzr.db",
"com.flowzr.graph",
"com.flowzr.model",
"com.flowzr.utils",
"java.util"
] | android.database; com.flowzr.db; com.flowzr.graph; com.flowzr.model; com.flowzr.utils; java.util; | 2,719,865 |
@Test
public void endPutAllIncrementsPutAlls() {
cachePerfStats.endPutAll(0);
assertThat(statistics.getInt(putAllsId)).isEqualTo(1);
} | void function() { cachePerfStats.endPutAll(0); assertThat(statistics.getInt(putAllsId)).isEqualTo(1); } | /**
* Characterization test: Note that the only way to increment {@code putalls} is to invoke {@code
* endPutAll}.
*/ | Characterization test: Note that the only way to increment putalls is to invoke endPutAll | endPutAllIncrementsPutAlls | {
"repo_name": "davebarnes97/geode",
"path": "geode-core/src/test/java/org/apache/geode/internal/cache/CachePerfStatsTest.java",
"license": "apache-2.0",
"size": 34945
} | [
"org.assertj.core.api.Assertions"
] | import org.assertj.core.api.Assertions; | import org.assertj.core.api.*; | [
"org.assertj.core"
] | org.assertj.core; | 996,674 |
public static void closeEL(InputStream is, OutputStream os) {
closeEL(is);
closeEL(os);
} | static void function(InputStream is, OutputStream os) { closeEL(is); closeEL(os); } | /**
* close inputstream without a Exception
*
* @param is
* @param os
*/ | close inputstream without a Exception | closeEL | {
"repo_name": "jzuijlek/Lucee",
"path": "core/src/main/java/lucee/commons/io/IOUtil.java",
"license": "lgpl-2.1",
"size": 33023
} | [
"java.io.InputStream",
"java.io.OutputStream"
] | import java.io.InputStream; import java.io.OutputStream; | import java.io.*; | [
"java.io"
] | java.io; | 502,780 |
public static Boolean or(Row row, ExpressionEvalContext context, Expression<?>... operands) {
boolean seenUnknown = false;
for (Expression<?> operand : operands) {
Boolean result = (Boolean) operand.eval(row, context);
if (isTrue(result)) {
return Boolean.TRUE;
}
if (isNull(result)) {
seenUnknown = true;
}
}
return seenUnknown ? null : Boolean.FALSE;
}
/**
* Negates the given boolean value.
*
* @param value the value to negate.
* @return {@code true} if the passed value was {@code false}, {@code false} | static Boolean function(Row row, ExpressionEvalContext context, Expression<?>... operands) { boolean seenUnknown = false; for (Expression<?> operand : operands) { Boolean result = (Boolean) operand.eval(row, context); if (isTrue(result)) { return Boolean.TRUE; } if (isNull(result)) { seenUnknown = true; } } return seenUnknown ? null : Boolean.FALSE; } /** * Negates the given boolean value. * * @param value the value to negate. * @return {@code true} if the passed value was {@code false}, {@code false} | /**
* Performs OR for the given operands acting on the given row in the given
* context.
* <p>
* The method exhibits a short-circuiting behaviour: there is no guarantee
* all of the passed operands would be evaluated. Operand evaluation order
* is unspecified.
*
* @param row the row to evaluate the operands on.
* @param context the context to evaluate the operands in.
* @param operands the boolean operands to evaluate.
* @return {@code false} if all of the operands were evaluated to {@code false},
* {@code true} if at least one of the operands was evaluated to {@code true},
* {@code null} otherwise.
*/ | Performs OR for the given operands acting on the given row in the given context. The method exhibits a short-circuiting behaviour: there is no guarantee all of the passed operands would be evaluated. Operand evaluation order is unspecified | or | {
"repo_name": "emre-aydin/hazelcast",
"path": "hazelcast/src/main/java/com/hazelcast/sql/impl/expression/predicate/TernaryLogic.java",
"license": "apache-2.0",
"size": 6012
} | [
"com.hazelcast.sql.impl.expression.Expression",
"com.hazelcast.sql.impl.expression.ExpressionEvalContext",
"com.hazelcast.sql.impl.row.Row"
] | import com.hazelcast.sql.impl.expression.Expression; import com.hazelcast.sql.impl.expression.ExpressionEvalContext; import com.hazelcast.sql.impl.row.Row; | import com.hazelcast.sql.impl.expression.*; import com.hazelcast.sql.impl.row.*; | [
"com.hazelcast.sql"
] | com.hazelcast.sql; | 1,010,654 |
protected String toStringWithTryLock(Supplier<String> dfltToStr) {
if (tryLockEntry(ENTRY_LOCK_TIMEOUT)) {
try {
return dfltToStr.get();
}
finally {
unlockEntry();
}
}
else {
String keySens = GridToStringBuilder.includeSensitive() ? ", key=" + key : "";
return "GridCacheMapEntry [err='Partial result represented because entry lock wasn't acquired."
+ " Waiting time elapsed.'"
+ keySens
+ ", hash=" + hash
+ "]";
}
}
private static class MvccRemoveLockListener implements IgniteInClosure<IgniteInternalFuture> {
private static final long serialVersionUID = -1578749008606139541L;
private final IgniteInternalTx tx;
private final AffinityTopologyVersion topVer;
private final UUID affNodeId;
private final MvccSnapshot mvccVer;
private final boolean needHistory;
private final GridFutureAdapter<GridCacheUpdateTxResult> resFut;
private final boolean needVal;
private final CacheEntryPredicate filter;
private GridCacheMapEntry entry;
private IgniteUuid futId;
private int batchNum;
private final boolean needOldVal;
MvccRemoveLockListener(IgniteInternalTx tx,
GridCacheMapEntry entry,
UUID affNodeId,
AffinityTopologyVersion topVer,
MvccSnapshot mvccVer,
boolean needHistory,
GridFutureAdapter<GridCacheUpdateTxResult> resFut,
boolean needOldVal,
boolean retVal,
@Nullable CacheEntryPredicate filter) {
this.tx = tx;
this.entry = entry;
this.topVer = topVer;
this.affNodeId = affNodeId;
this.mvccVer = mvccVer;
this.needHistory = needHistory;
this.resFut = resFut;
this.needOldVal = needOldVal;
this.needVal = retVal;
this.filter = filter;
} | String function(Supplier<String> dfltToStr) { if (tryLockEntry(ENTRY_LOCK_TIMEOUT)) { try { return dfltToStr.get(); } finally { unlockEntry(); } } else { String keySens = GridToStringBuilder.includeSensitive() ? STR + key : STRGridCacheMapEntry [err='Partial result represented because entry lock wasn't acquired.STR Waiting time elapsed.'STR, hash=STR]"; } } private static class MvccRemoveLockListener implements IgniteInClosure<IgniteInternalFuture> { private static final long serialVersionUID = -1578749008606139541L; private final IgniteInternalTx tx; private final AffinityTopologyVersion topVer; private final UUID affNodeId; private final MvccSnapshot mvccVer; private final boolean needHistory; private final GridFutureAdapter<GridCacheUpdateTxResult> resFut; private final boolean needVal; private final CacheEntryPredicate filter; private GridCacheMapEntry entry; private IgniteUuid futId; private int batchNum; private final boolean needOldVal; MvccRemoveLockListener(IgniteInternalTx tx, GridCacheMapEntry entry, UUID affNodeId, AffinityTopologyVersion topVer, MvccSnapshot mvccVer, boolean needHistory, GridFutureAdapter<GridCacheUpdateTxResult> resFut, boolean needOldVal, boolean retVal, @Nullable CacheEntryPredicate filter) { this.tx = tx; this.entry = entry; this.topVer = topVer; this.affNodeId = affNodeId; this.mvccVer = mvccVer; this.needHistory = needHistory; this.resFut = resFut; this.needOldVal = needOldVal; this.needVal = retVal; this.filter = filter; } | /**
* Does thread safe {@link #toString} for {@link GridCacheMapEntry} classes.
*
* @param dfltToStr {@link #toString()} supplier.
* @return Result of dfltToStr call If lock acquired or a short representation of {@link GridCacheMapEntry}.
*/ | Does thread safe <code>#toString</code> for <code>GridCacheMapEntry</code> classes | toStringWithTryLock | {
"repo_name": "xtern/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheMapEntry.java",
"license": "apache-2.0",
"size": 228391
} | [
"java.util.function.Supplier",
"org.apache.ignite.internal.IgniteInternalFuture",
"org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion",
"org.apache.ignite.internal.processors.cache.mvcc.MvccSnapshot",
"org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx",
"org.apa... | import java.util.function.Supplier; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion; import org.apache.ignite.internal.processors.cache.mvcc.MvccSnapshot; import org.apache.ignite.internal.processors.cache.transactions.IgniteInternalTx; import org.apache.ignite.internal.util.future.GridFutureAdapter; import org.apache.ignite.internal.util.tostring.GridToStringBuilder; import org.apache.ignite.lang.IgniteInClosure; import org.apache.ignite.lang.IgniteUuid; import org.jetbrains.annotations.Nullable; | import java.util.function.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.processors.affinity.*; import org.apache.ignite.internal.processors.cache.mvcc.*; import org.apache.ignite.internal.processors.cache.transactions.*; import org.apache.ignite.internal.util.future.*; import org.apache.ignite.internal.util.tostring.*; import org.apache.ignite.lang.*; import org.jetbrains.annotations.*; | [
"java.util",
"org.apache.ignite",
"org.jetbrains.annotations"
] | java.util; org.apache.ignite; org.jetbrains.annotations; | 510,847 |
private void assertValidOrder(List<PassFactory> checks) {
assertPassOrder(
checks,
closureRewriteModule,
checkVariableReferences,
"If checkVariableReferences runs before closureRewriteModule, it will produce invalid"
+ " warnings because it will think of module-scoped variables as global variables.");
assertPassOrder(
checks,
closureRewriteModule,
processDefines,
"Must rewrite goog.module before processing @define's, so that @defines in modules work.");
assertPassOrder(
checks,
closurePrimitives,
polymerPass,
"The Polymer pass must run after goog.provide processing.");
assertPassOrder(
checks,
polymerPass,
suspiciousCode,
"The Polymer pass must run before suspiciousCode processing.");
assertPassOrder(
checks,
dartSuperAccessorsPass,
TranspilationPasses.es6ConvertSuper,
"The Dart super accessors pass must run before ES6->ES3 super lowering.");
if (checks.contains(closureGoogScopeAliases)) {
Preconditions.checkState(
checks.contains(checkVariableReferences),
"goog.scope processing requires variable checking");
}
assertPassOrder(
checks,
checkVariableReferences,
closureGoogScopeAliases,
"Variable checking must happen before goog.scope processing.");
assertPassOrder(
checks,
TranspilationPasses.es6ConvertSuper,
removeSuperMethodsPass,
"Super-call method removal must run after Es6 super rewriting, "
+ "because Es6 super calls are matched on their post-processed form.");
assertPassOrder(
checks,
closurePrimitives,
removeSuperMethodsPass,
"Super-call method removal must run after Es6 super rewriting, "
+ "because Closure base calls are expected to be in post-processed form.");
assertPassOrder(
checks,
closureCodeRemoval,
removeSuperMethodsPass,
"Super-call method removal must run after closure code removal, because "
+ "removing assertions may make more super calls eligible to be stripped.");
} | void function(List<PassFactory> checks) { assertPassOrder( checks, closureRewriteModule, checkVariableReferences, STR + STR); assertPassOrder( checks, closureRewriteModule, processDefines, STR); assertPassOrder( checks, closurePrimitives, polymerPass, STR); assertPassOrder( checks, polymerPass, suspiciousCode, STR); assertPassOrder( checks, dartSuperAccessorsPass, TranspilationPasses.es6ConvertSuper, STR); if (checks.contains(closureGoogScopeAliases)) { Preconditions.checkState( checks.contains(checkVariableReferences), STR); } assertPassOrder( checks, checkVariableReferences, closureGoogScopeAliases, STR); assertPassOrder( checks, TranspilationPasses.es6ConvertSuper, removeSuperMethodsPass, STR + STR); assertPassOrder( checks, closurePrimitives, removeSuperMethodsPass, STR + STR); assertPassOrder( checks, closureCodeRemoval, removeSuperMethodsPass, STR + STR); } | /**
* Certain checks need to run in a particular order. For example, the PolymerPass
* will not work correctly unless it runs after the goog.provide() processing.
* This enforces those constraints.
* @param checks The list of check passes
*/ | Certain checks need to run in a particular order. For example, the PolymerPass will not work correctly unless it runs after the goog.provide() processing. This enforces those constraints | assertValidOrder | {
"repo_name": "LorenzoDV/closure-compiler",
"path": "src/com/google/javascript/jscomp/DefaultPassConfig.java",
"license": "apache-2.0",
"size": 96559
} | [
"com.google.common.base.Preconditions",
"java.util.List"
] | import com.google.common.base.Preconditions; import java.util.List; | import com.google.common.base.*; import java.util.*; | [
"com.google.common",
"java.util"
] | com.google.common; java.util; | 986,549 |
ImmutableList<FilesetTraversalParams> getTraversals(); | ImmutableList<FilesetTraversalParams> getTraversals(); | /**
* Returns a list of the traversals that went into this Fileset. Only used by Skyframe-native
* filesets, so will be null if Skyframe-native filesets are not enabled.
*/ | Returns a list of the traversals that went into this Fileset. Only used by Skyframe-native filesets, so will be null if Skyframe-native filesets are not enabled | getTraversals | {
"repo_name": "dropbox/bazel",
"path": "src/main/java/com/google/devtools/build/lib/analysis/fileset/FilesetProvider.java",
"license": "apache-2.0",
"size": 1271
} | [
"com.google.common.collect.ImmutableList",
"com.google.devtools.build.lib.actions.FilesetTraversalParams"
] | import com.google.common.collect.ImmutableList; import com.google.devtools.build.lib.actions.FilesetTraversalParams; | import com.google.common.collect.*; import com.google.devtools.build.lib.actions.*; | [
"com.google.common",
"com.google.devtools"
] | com.google.common; com.google.devtools; | 304,957 |
protected MimeBodyPart secure(Message msg) throws Exception {
// Set up encrypt/sign variables
MimeBodyPart dataBP = msg.getData();
Partnership partnership = msg.getPartnership();
String contentTxfrEncoding = partnership.getAttribute(Partnership.PA_CONTENT_TRANSFER_ENCODING);
if (contentTxfrEncoding == null) {
contentTxfrEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
}
boolean encrypt = partnership.getAttribute(Partnership.PA_ENCRYPTION_ALGORITHM) != null;
boolean sign = partnership.getAttribute(Partnership.PA_SIGNATURE_ALGORITHM) != null;
if (!sign) {
calcAndStoreMic(msg, dataBP, (sign || encrypt));
}
// Check if compression is enabled
String compressionType = msg.getPartnership().getAttribute("compression_type");
if (logger.isTraceEnabled()) {
logger.trace("Compression type from config: " + compressionType);
}
boolean isCompress = false;
if (compressionType != null && !"NONE".equalsIgnoreCase(compressionType)) {
if (compressionType.equalsIgnoreCase(ICryptoHelper.COMPRESSION_ZLIB)) {
isCompress = true;
} else {
throw new OpenAS2Exception("Unsupported compression type: " + compressionType);
}
}
String compressionMode = msg.getPartnership().getAttribute("compression_mode");
boolean isCompressBeforeSign = true; // Defaults to compressing the
// entire message before signing
// and encryption
if (compressionMode != null && compressionMode.equalsIgnoreCase("compress-after-signing")) {
isCompressBeforeSign = false;
}
if (isCompress && isCompressBeforeSign) {
if (logger.isTraceEnabled()) {
logger.trace("Compressing outbound message before signing...");
}
if (!sign && !encrypt) {
// Add any additional headers since this will be the outermost Mime body part if
// configured
addCustomOuterMimeHeaders(msg, dataBP);
}
dataBP = AS2Util.getCryptoHelper().compress(msg, dataBP, compressionType, contentTxfrEncoding);
}
// Encrypt and/or sign the data if requested
CertificateFactory certFx = getSession().getCertificateFactory();
// Sign the data if requested
if (sign) {
if (!encrypt && !(isCompress && !isCompressBeforeSign)) {
// Add any additional headers since this will be the outermost Mime body part if
// configured
addCustomOuterMimeHeaders(msg, dataBP);
}
calcAndStoreMic(msg, dataBP, (sign || encrypt));
X509Certificate senderCert = certFx.getCertificate(msg, Partnership.PTYPE_SENDER);
PrivateKey senderKey = certFx.getPrivateKey(msg, senderCert);
String digest = partnership.getAttribute(Partnership.PA_SIGNATURE_ALGORITHM);
if (logger.isDebugEnabled()) {
logger.debug("Params for creating signed body part:: DATA: " + dataBP + "\n SIGN DIGEST: " + digest + "\n CERT ALG NAME EXTRACTED: " + senderCert.getSigAlgName() + "\n CERT PUB KEY ALG NAME EXTRACTED: " + senderCert.getPublicKey().getAlgorithm() + msg.getLogMsgID());
}
boolean isRemoveCmsAlgorithmProtectionAttr = "true".equalsIgnoreCase(partnership.getAttribute(Partnership.PA_REMOVE_PROTECTION_ATTRIB));
dataBP = AS2Util.getCryptoHelper().sign(dataBP, senderCert, senderKey, digest, contentTxfrEncoding, msg.getPartnership().isRenameDigestToOldName(), isRemoveCmsAlgorithmProtectionAttr);
DataHistoryItem historyItem = new DataHistoryItem(dataBP.getContentType());
// *** add one more item to msg history
msg.getHistory().getItems().add(historyItem);
if (logger.isDebugEnabled()) {
logger.debug("signed data" + msg.getLogMsgID());
}
}
if (isCompress && !isCompressBeforeSign) {
if (!encrypt) {
// Add any additional headers since this will be the outermost Mime body part if
// configured
addCustomOuterMimeHeaders(msg, dataBP);
}
if (logger.isTraceEnabled()) {
logger.trace("Compressing outbound message after signing...");
}
dataBP = AS2Util.getCryptoHelper().compress(msg, dataBP, compressionType, contentTxfrEncoding);
}
// Encrypt the data if requested
if (encrypt) {
// Add any additional headers since this will be the outermost Mime body part if
// configured
addCustomOuterMimeHeaders(msg, dataBP);
String algorithm = partnership.getAttribute(Partnership.PA_ENCRYPTION_ALGORITHM);
X509Certificate receiverCert = certFx.getCertificate(msg, Partnership.PTYPE_RECEIVER);
dataBP = AS2Util.getCryptoHelper().encrypt(dataBP, receiverCert, algorithm, contentTxfrEncoding);
// Asynch MDN 2007-03-12
DataHistoryItem historyItem = new DataHistoryItem(dataBP.getContentType());
// *** add one more item to msg history
msg.getHistory().getItems().add(historyItem);
if (logger.isDebugEnabled()) {
logger.debug("encrypted data" + msg.getLogMsgID());
}
}
String t = dataBP.getEncoding();
if ((t == null || t.length() < 1) && "true".equalsIgnoreCase(partnership.getAttribute(Partnership.PA_SET_CONTENT_TRANSFER_ENCODING_OMBP))) {
dataBP.setHeader("Content-Transfer-Encoding", contentTxfrEncoding);
}
return dataBP;
} | MimeBodyPart function(Message msg) throws Exception { MimeBodyPart dataBP = msg.getData(); Partnership partnership = msg.getPartnership(); String contentTxfrEncoding = partnership.getAttribute(Partnership.PA_CONTENT_TRANSFER_ENCODING); if (contentTxfrEncoding == null) { contentTxfrEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING; } boolean encrypt = partnership.getAttribute(Partnership.PA_ENCRYPTION_ALGORITHM) != null; boolean sign = partnership.getAttribute(Partnership.PA_SIGNATURE_ALGORITHM) != null; if (!sign) { calcAndStoreMic(msg, dataBP, (sign encrypt)); } String compressionType = msg.getPartnership().getAttribute(STR); if (logger.isTraceEnabled()) { logger.trace(STR + compressionType); } boolean isCompress = false; if (compressionType != null && !"NONE".equalsIgnoreCase(compressionType)) { if (compressionType.equalsIgnoreCase(ICryptoHelper.COMPRESSION_ZLIB)) { isCompress = true; } else { throw new OpenAS2Exception(STR + compressionType); } } String compressionMode = msg.getPartnership().getAttribute(STR); boolean isCompressBeforeSign = true; if (compressionMode != null && compressionMode.equalsIgnoreCase(STR)) { isCompressBeforeSign = false; } if (isCompress && isCompressBeforeSign) { if (logger.isTraceEnabled()) { logger.trace(STR); } if (!sign && !encrypt) { addCustomOuterMimeHeaders(msg, dataBP); } dataBP = AS2Util.getCryptoHelper().compress(msg, dataBP, compressionType, contentTxfrEncoding); } CertificateFactory certFx = getSession().getCertificateFactory(); if (sign) { if (!encrypt && !(isCompress && !isCompressBeforeSign)) { addCustomOuterMimeHeaders(msg, dataBP); } calcAndStoreMic(msg, dataBP, (sign encrypt)); X509Certificate senderCert = certFx.getCertificate(msg, Partnership.PTYPE_SENDER); PrivateKey senderKey = certFx.getPrivateKey(msg, senderCert); String digest = partnership.getAttribute(Partnership.PA_SIGNATURE_ALGORITHM); if (logger.isDebugEnabled()) { logger.debug(STR + dataBP + STR + digest + STR + senderCert.getSigAlgName() + STR + senderCert.getPublicKey().getAlgorithm() + msg.getLogMsgID()); } boolean isRemoveCmsAlgorithmProtectionAttr = "true".equalsIgnoreCase(partnership.getAttribute(Partnership.PA_REMOVE_PROTECTION_ATTRIB)); dataBP = AS2Util.getCryptoHelper().sign(dataBP, senderCert, senderKey, digest, contentTxfrEncoding, msg.getPartnership().isRenameDigestToOldName(), isRemoveCmsAlgorithmProtectionAttr); DataHistoryItem historyItem = new DataHistoryItem(dataBP.getContentType()); msg.getHistory().getItems().add(historyItem); if (logger.isDebugEnabled()) { logger.debug(STR + msg.getLogMsgID()); } } if (isCompress && !isCompressBeforeSign) { if (!encrypt) { addCustomOuterMimeHeaders(msg, dataBP); } if (logger.isTraceEnabled()) { logger.trace(STR); } dataBP = AS2Util.getCryptoHelper().compress(msg, dataBP, compressionType, contentTxfrEncoding); } if (encrypt) { addCustomOuterMimeHeaders(msg, dataBP); String algorithm = partnership.getAttribute(Partnership.PA_ENCRYPTION_ALGORITHM); X509Certificate receiverCert = certFx.getCertificate(msg, Partnership.PTYPE_RECEIVER); dataBP = AS2Util.getCryptoHelper().encrypt(dataBP, receiverCert, algorithm, contentTxfrEncoding); DataHistoryItem historyItem = new DataHistoryItem(dataBP.getContentType()); msg.getHistory().getItems().add(historyItem); if (logger.isDebugEnabled()) { logger.debug(STR + msg.getLogMsgID()); } } String t = dataBP.getEncoding(); if ((t == null t.length() < 1) && "true".equalsIgnoreCase(partnership.getAttribute(Partnership.PA_SET_CONTENT_TRANSFER_ENCODING_OMBP))) { dataBP.setHeader(STR, contentTxfrEncoding); } return dataBP; } | /**
* Returns a MimeBodyPart or MimeMultipart object
*
* @param msg The message object carried around containing necessary
* information
* @return The secured mimebodypart
* @throws Exception some unforseen issue has occurred
*/ | Returns a MimeBodyPart or MimeMultipart object | secure | {
"repo_name": "igwtech/OpenAs2App",
"path": "Server/src/main/java/org/openas2/processor/sender/AS2SenderModule.java",
"license": "bsd-2-clause",
"size": 33297
} | [
"java.security.PrivateKey",
"java.security.cert.X509Certificate",
"javax.mail.internet.MimeBodyPart",
"org.openas2.OpenAS2Exception",
"org.openas2.Session",
"org.openas2.cert.CertificateFactory",
"org.openas2.lib.helper.ICryptoHelper",
"org.openas2.message.DataHistoryItem",
"org.openas2.message.Mess... | import java.security.PrivateKey; import java.security.cert.X509Certificate; import javax.mail.internet.MimeBodyPart; import org.openas2.OpenAS2Exception; import org.openas2.Session; import org.openas2.cert.CertificateFactory; import org.openas2.lib.helper.ICryptoHelper; import org.openas2.message.DataHistoryItem; import org.openas2.message.Message; import org.openas2.partner.Partnership; import org.openas2.util.AS2Util; | import java.security.*; import java.security.cert.*; import javax.mail.internet.*; import org.openas2.*; import org.openas2.cert.*; import org.openas2.lib.helper.*; import org.openas2.message.*; import org.openas2.partner.*; import org.openas2.util.*; | [
"java.security",
"javax.mail",
"org.openas2",
"org.openas2.cert",
"org.openas2.lib",
"org.openas2.message",
"org.openas2.partner",
"org.openas2.util"
] | java.security; javax.mail; org.openas2; org.openas2.cert; org.openas2.lib; org.openas2.message; org.openas2.partner; org.openas2.util; | 2,428,610 |
public void setOpinion(Opine opinion, SimpleUserInfo author, String authorImageUrl, UserHandler
userHandler, PLYAndroid client) {
if (this.opinion != null && opinion.equals(this.opinion)) {
return;
}
// display new opinion
this.opinion = opinion;
opinionView.setText(opinion.getText());
boolean isFriend = userHandler.isFriend(author);
// colorize cardview if this entry was created by oneself or a friend
setCardBackgroundColor(isFriend ? friendBackgroundColor : cardBackgroundColor);
// display new author
authorView.setAuthor(author, authorImageUrl, isFriend, opinion.getProduct(), opinion.getCreated());
// update like view
likeView.setObjectId(opinion.getId());
likeView.setClient(client);
User currentUser = userHandler.getUser();
String userId = currentUser == null ? null : currentUser.getId();
likeView.setFromVoters(opinion.getUpVoters(), opinion.getDownVoters(), userId, userHandler
.getFriends(), widthPx);
} | void function(Opine opinion, SimpleUserInfo author, String authorImageUrl, UserHandler userHandler, PLYAndroid client) { if (this.opinion != null && opinion.equals(this.opinion)) { return; } this.opinion = opinion; opinionView.setText(opinion.getText()); boolean isFriend = userHandler.isFriend(author); setCardBackgroundColor(isFriend ? friendBackgroundColor : cardBackgroundColor); authorView.setAuthor(author, authorImageUrl, isFriend, opinion.getProduct(), opinion.getCreated()); likeView.setObjectId(opinion.getId()); likeView.setClient(client); User currentUser = userHandler.getUser(); String userId = currentUser == null ? null : currentUser.getId(); likeView.setFromVoters(opinion.getUpVoters(), opinion.getDownVoters(), userId, userHandler .getFriends(), widthPx); } | /**
* Sets a new opinion to be displayed in the cardview.
*
* @param opinion
* the opine to show
* @param author
* the author to show
* @param authorImageUrl
* the URL of the author's avatar image to load
* @param userHandler
* the handler to retrieve user info from for friend and voting info
* @param client
* the PLYAndroid client to use for voting
*/ | Sets a new opinion to be displayed in the cardview | setOpinion | {
"repo_name": "ProductLayer/ProductLayer-SDK-for-Android",
"path": "ply-android-common/src/main/java/com/productlayer/android/common/view/OpinionView.java",
"license": "bsd-2-clause",
"size": 8418
} | [
"com.productlayer.android.common.handler.UserHandler",
"com.productlayer.android.sdk.PLYAndroid",
"com.productlayer.core.beans.Opine",
"com.productlayer.core.beans.SimpleUserInfo",
"com.productlayer.core.beans.User"
] | import com.productlayer.android.common.handler.UserHandler; import com.productlayer.android.sdk.PLYAndroid; import com.productlayer.core.beans.Opine; import com.productlayer.core.beans.SimpleUserInfo; import com.productlayer.core.beans.User; | import com.productlayer.android.common.handler.*; import com.productlayer.android.sdk.*; import com.productlayer.core.beans.*; | [
"com.productlayer.android",
"com.productlayer.core"
] | com.productlayer.android; com.productlayer.core; | 162,442 |
Observable<DomainModelResults> executeAsync();
}
}
interface ComputerVisionAnalyzeImageByDomainInStreamDefinition extends
ComputerVisionAnalyzeImageByDomainInStreamDefinitionStages.WithModel,
ComputerVisionAnalyzeImageByDomainInStreamDefinitionStages.WithImage,
ComputerVisionAnalyzeImageByDomainInStreamDefinitionStages.WithExecute {
} | Observable<DomainModelResults> executeAsync(); } } interface ComputerVisionAnalyzeImageByDomainInStreamDefinition extends ComputerVisionAnalyzeImageByDomainInStreamDefinitionStages.WithModel, ComputerVisionAnalyzeImageByDomainInStreamDefinitionStages.WithImage, ComputerVisionAnalyzeImageByDomainInStreamDefinitionStages.WithExecute { } | /**
* Execute the request asynchronously.
*
* @return the observable to the DomainModelResults object
*/ | Execute the request asynchronously | executeAsync | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/cognitiveservices/ms-azure-cs-computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/ComputerVision.java",
"license": "mit",
"size": 98515
} | [
"com.microsoft.azure.cognitiveservices.vision.computervision.models.DomainModelResults"
] | import com.microsoft.azure.cognitiveservices.vision.computervision.models.DomainModelResults; | import com.microsoft.azure.cognitiveservices.vision.computervision.models.*; | [
"com.microsoft.azure"
] | com.microsoft.azure; | 2,773,223 |
public static Context getContext() {
return SDL.getContext();
} | static Context function() { return SDL.getContext(); } | /**
* This method is called by SDL using JNI.
*/ | This method is called by SDL using JNI | getContext | {
"repo_name": "nrz/ylikuutio",
"path": "external/SDL2-2.0.14/android-project/app/src/main/java/org/libsdl/app/SDLActivity.java",
"license": "agpl-3.0",
"size": 83693
} | [
"android.content.Context"
] | import android.content.Context; | import android.content.*; | [
"android.content"
] | android.content; | 2,149,159 |
@Test
public void testRecommender() throws ClassNotFoundException, LibrecException, IOException {
Resource resource = new Resource("rec/cf/rating/pmf-test.properties");
conf.addResource(resource);
RecommenderJob job = new RecommenderJob(conf);
job.runJob();
}
| void function() throws ClassNotFoundException, LibrecException, IOException { Resource resource = new Resource(STR); conf.addResource(resource); RecommenderJob job = new RecommenderJob(conf); job.runJob(); } | /**
* Test the whole process of PMF Recommender
*
* @throws ClassNotFoundException
* @throws LibrecException
* @throws IOException
*/ | Test the whole process of PMF Recommender | testRecommender | {
"repo_name": "rburke2233/librec",
"path": "core/src/test/java/net/librec/recommender/cf/rating/PMFTestCase.java",
"license": "gpl-3.0",
"size": 1719
} | [
"java.io.IOException",
"net.librec.common.LibrecException",
"net.librec.conf.Configuration",
"net.librec.job.RecommenderJob"
] | import java.io.IOException; import net.librec.common.LibrecException; import net.librec.conf.Configuration; import net.librec.job.RecommenderJob; | import java.io.*; import net.librec.common.*; import net.librec.conf.*; import net.librec.job.*; | [
"java.io",
"net.librec.common",
"net.librec.conf",
"net.librec.job"
] | java.io; net.librec.common; net.librec.conf; net.librec.job; | 716,647 |
public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn)
{
float f = ageInTicks * (float)Math.PI * -0.1F;
for (int i = 0; i < 4; ++i)
{
this.blazeSticks[i].rotationPointY = -2.0F + MathHelper.cos(((float)(i * 2) + ageInTicks) * 0.25F);
this.blazeSticks[i].rotationPointX = MathHelper.cos(f) * 9.0F;
this.blazeSticks[i].rotationPointZ = MathHelper.sin(f) * 9.0F;
++f;
}
f = ((float)Math.PI / 4F) + ageInTicks * (float)Math.PI * 0.03F;
for (int j = 4; j < 8; ++j)
{
this.blazeSticks[j].rotationPointY = 2.0F + MathHelper.cos(((float)(j * 2) + ageInTicks) * 0.25F);
this.blazeSticks[j].rotationPointX = MathHelper.cos(f) * 7.0F;
this.blazeSticks[j].rotationPointZ = MathHelper.sin(f) * 7.0F;
++f;
}
f = 0.47123894F + ageInTicks * (float)Math.PI * -0.05F;
for (int k = 8; k < 12; ++k)
{
this.blazeSticks[k].rotationPointY = 11.0F + MathHelper.cos(((float)k * 1.5F + ageInTicks) * 0.5F);
this.blazeSticks[k].rotationPointX = MathHelper.cos(f) * 5.0F;
this.blazeSticks[k].rotationPointZ = MathHelper.sin(f) * 5.0F;
++f;
}
this.blazeHead.rotateAngleY = netHeadYaw * 0.017453292F;
this.blazeHead.rotateAngleX = headPitch * 0.017453292F;
} | void function(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) { float f = ageInTicks * (float)Math.PI * -0.1F; for (int i = 0; i < 4; ++i) { this.blazeSticks[i].rotationPointY = -2.0F + MathHelper.cos(((float)(i * 2) + ageInTicks) * 0.25F); this.blazeSticks[i].rotationPointX = MathHelper.cos(f) * 9.0F; this.blazeSticks[i].rotationPointZ = MathHelper.sin(f) * 9.0F; ++f; } f = ((float)Math.PI / 4F) + ageInTicks * (float)Math.PI * 0.03F; for (int j = 4; j < 8; ++j) { this.blazeSticks[j].rotationPointY = 2.0F + MathHelper.cos(((float)(j * 2) + ageInTicks) * 0.25F); this.blazeSticks[j].rotationPointX = MathHelper.cos(f) * 7.0F; this.blazeSticks[j].rotationPointZ = MathHelper.sin(f) * 7.0F; ++f; } f = 0.47123894F + ageInTicks * (float)Math.PI * -0.05F; for (int k = 8; k < 12; ++k) { this.blazeSticks[k].rotationPointY = 11.0F + MathHelper.cos(((float)k * 1.5F + ageInTicks) * 0.5F); this.blazeSticks[k].rotationPointX = MathHelper.cos(f) * 5.0F; this.blazeSticks[k].rotationPointZ = MathHelper.sin(f) * 5.0F; ++f; } this.blazeHead.rotateAngleY = netHeadYaw * 0.017453292F; this.blazeHead.rotateAngleX = headPitch * 0.017453292F; } | /**
* Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms
* and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how
* "far" arms and legs can swing at most.
*/ | Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how "far" arms and legs can swing at most | setRotationAngles | {
"repo_name": "danielyc/test-1.9.4",
"path": "build/tmp/recompileMc/sources/net/minecraft/client/model/ModelBlaze.java",
"license": "gpl-3.0",
"size": 3127
} | [
"net.minecraft.entity.Entity",
"net.minecraft.util.math.MathHelper"
] | import net.minecraft.entity.Entity; import net.minecraft.util.math.MathHelper; | import net.minecraft.entity.*; import net.minecraft.util.math.*; | [
"net.minecraft.entity",
"net.minecraft.util"
] | net.minecraft.entity; net.minecraft.util; | 2,456,169 |
public void apply(JacobianMatrix m)
{
int n = size();
for(int i=0; i < n; ++i)
{
int f = _fbus[i], t = _tbus[i];
m.addValue(f, f, _fself.get(i));
m.addValue(t, t, _tself.get(i));
m.addValue(f, t, _fmut.get(i));
m.addValue(t, f, _tmut.get(i));
}
} | void function(JacobianMatrix m) { int n = size(); for(int i=0; i < n; ++i) { int f = _fbus[i], t = _tbus[i]; m.addValue(f, f, _fself.get(i)); m.addValue(t, t, _tself.get(i)); m.addValue(f, t, _fmut.get(i)); m.addValue(t, f, _tmut.get(i)); } } | /**
* Apply the results into an nbus x nbus Jacobian Matrix
* @param m
*/ | Apply the results into an nbus x nbus Jacobian Matrix | apply | {
"repo_name": "powerdata/com.powerdata.openpa",
"path": "pwrflow/ACBranchJacobianList.java",
"license": "bsd-3-clause",
"size": 9489
} | [
"com.powerdata.openpa.tools.matrix.JacobianMatrix"
] | import com.powerdata.openpa.tools.matrix.JacobianMatrix; | import com.powerdata.openpa.tools.matrix.*; | [
"com.powerdata.openpa"
] | com.powerdata.openpa; | 1,311,921 |
public Type inOut(String uri) {
return to(ExchangePattern.InOut, uri);
} | Type function(String uri) { return to(ExchangePattern.InOut, uri); } | /**
* Sends the message to the given endpoint using an <a
* href="http://camel.apache.org/request-reply.html">Request Reply</a> or <a
* href="http://camel.apache.org/exchange-pattern.html">InOut exchange
* pattern</a>
* <p/>
* Notice the existing MEP is restored after the message has been sent to
* the given endpoint.
*
* @param uri
* The endpoint uri which is used for sending the exchange
* @return the builder
*/ | Sends the message to the given endpoint using an Request Reply or InOut exchange pattern Notice the existing MEP is restored after the message has been sent to the given endpoint | inOut | {
"repo_name": "shuliangtao/apache-camel-2.13.0-src",
"path": "camel-core/src/main/java/org/apache/camel/model/ProcessorDefinition.java",
"license": "apache-2.0",
"size": 138060
} | [
"org.apache.camel.ExchangePattern"
] | import org.apache.camel.ExchangePattern; | import org.apache.camel.*; | [
"org.apache.camel"
] | org.apache.camel; | 264,683 |
EEnum getMessageSort(); | EEnum getMessageSort(); | /**
* Returns the meta object for enum '{@link ca.mcgill.cs.sel.ram.MessageSort <em>Message Sort</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for enum '<em>Message Sort</em>'.
* @see ca.mcgill.cs.sel.ram.MessageSort
* @generated
*/ | Returns the meta object for enum '<code>ca.mcgill.cs.sel.ram.MessageSort Message Sort</code>'. | getMessageSort | {
"repo_name": "mjorod/textram",
"path": "tool/ca.mcgill.sel.ram/src/ca/mcgill/cs/sel/ram/RamPackage.java",
"license": "mit",
"size": 271132
} | [
"org.eclipse.emf.ecore.EEnum"
] | import org.eclipse.emf.ecore.EEnum; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,065,450 |
Map<Comment, User> getAuthorsOfComments(Comment[] comments); | Map<Comment, User> getAuthorsOfComments(Comment[] comments); | /**
* for each comment, downloads the User that authored it and
* then maps the comment to the author.
*
* @param comments comments in question
* @return the map of the comments and their authors
*/ | for each comment, downloads the User that authored it and then maps the comment to the author | getAuthorsOfComments | {
"repo_name": "nareddyt/Bitter",
"path": "app/src/main/java/gitmad/bitter/data/UserProvider.java",
"license": "gpl-2.0",
"size": 1958
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 1,781,750 |
public void setTextAppearance(Context context, int resid)
{
TypedArray appearance = context.obtainStyledAttributes(resid, com.android.internal.R.styleable.TextAppearance);
int color;
ColorStateList colors;
int ts;
color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0);
if (color != 0)
{
setHighlightColor(color);
}
colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColor);
if (colors != null)
{
setTextColor(colors);
}
ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.TextAppearance_textSize, 0);
if (ts != 0)
{
setRawTextSize(ts);
}
colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColorHint);
if (colors != null)
{
setHintTextColor(colors);
}
colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColorLink);
if (colors != null)
{
setLinkTextColor(colors);
}
String familyName;
int typefaceIndex, styleIndex;
familyName = appearance.getString(com.android.internal.R.styleable.TextAppearance_fontFamily);
typefaceIndex = appearance.getInt(com.android.internal.R.styleable.TextAppearance_typeface, -1);
styleIndex = appearance.getInt(com.android.internal.R.styleable.TextAppearance_textStyle, -1);
setTypefaceFromAttrs(familyName, typefaceIndex, styleIndex);
if (appearance.getBoolean(com.android.internal.R.styleable.TextAppearance_textAllCaps, false))
{
setTransformationMethod(new AllCapsTransformationMethod(getContext()));
}
appearance.recycle();
} | void function(Context context, int resid) { TypedArray appearance = context.obtainStyledAttributes(resid, com.android.internal.R.styleable.TextAppearance); int color; ColorStateList colors; int ts; color = appearance.getColor(com.android.internal.R.styleable.TextAppearance_textColorHighlight, 0); if (color != 0) { setHighlightColor(color); } colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColor); if (colors != null) { setTextColor(colors); } ts = appearance.getDimensionPixelSize(com.android.internal.R.styleable.TextAppearance_textSize, 0); if (ts != 0) { setRawTextSize(ts); } colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColorHint); if (colors != null) { setHintTextColor(colors); } colors = appearance.getColorStateList(com.android.internal.R.styleable.TextAppearance_textColorLink); if (colors != null) { setLinkTextColor(colors); } String familyName; int typefaceIndex, styleIndex; familyName = appearance.getString(com.android.internal.R.styleable.TextAppearance_fontFamily); typefaceIndex = appearance.getInt(com.android.internal.R.styleable.TextAppearance_typeface, -1); styleIndex = appearance.getInt(com.android.internal.R.styleable.TextAppearance_textStyle, -1); setTypefaceFromAttrs(familyName, typefaceIndex, styleIndex); if (appearance.getBoolean(com.android.internal.R.styleable.TextAppearance_textAllCaps, false)) { setTransformationMethod(new AllCapsTransformationMethod(getContext())); } appearance.recycle(); } | /**
* Sets the text color, size, style, hint color, and highlight color
* from the specified TextAppearance resource.
*/ | Sets the text color, size, style, hint color, and highlight color from the specified TextAppearance resource | setTextAppearance | {
"repo_name": "haikuowuya/android_system_code",
"path": "src/android/widget/TextView.java",
"license": "apache-2.0",
"size": 271830
} | [
"android.content.Context",
"android.content.res.ColorStateList",
"android.content.res.TypedArray",
"android.text.method.AllCapsTransformationMethod"
] | import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.text.method.AllCapsTransformationMethod; | import android.content.*; import android.content.res.*; import android.text.method.*; | [
"android.content",
"android.text"
] | android.content; android.text; | 31,410 |
EClass getExtractedMetamodel(); | EClass getExtractedMetamodel(); | /**
* Returns the meta object for class '{@link bento.componetization.reveng.ExtractedMetamodel <em>Extracted Metamodel</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for class '<em>Extracted Metamodel</em>'.
* @see bento.componetization.reveng.ExtractedMetamodel
* @generated
*/ | Returns the meta object for class '<code>bento.componetization.reveng.ExtractedMetamodel Extracted Metamodel</code>'. | getExtractedMetamodel | {
"repo_name": "jesusc/bento",
"path": "componetization/bento.componetization.model/src-gen/bento/componetization/reveng/RevengPackage.java",
"license": "epl-1.0",
"size": 26106
} | [
"org.eclipse.emf.ecore.EClass"
] | import org.eclipse.emf.ecore.EClass; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,149,463 |
public static MozuClient<com.mozu.api.contracts.productruntime.ProductValidationSummary> validateProductClient(com.mozu.api.contracts.productruntime.ProductOptionSelections productOptionSelections, String productCode) throws Exception
{
return validateProductClient( productOptionSelections, productCode, null, null);
} | static MozuClient<com.mozu.api.contracts.productruntime.ProductValidationSummary> function(com.mozu.api.contracts.productruntime.ProductOptionSelections productOptionSelections, String productCode) throws Exception { return validateProductClient( productOptionSelections, productCode, null, null); } | /**
* Validate the final state of shopper-selected options.
* <p><pre><code>
* MozuClient<com.mozu.api.contracts.productruntime.ProductValidationSummary> mozuClient=ValidateProductClient( productOptionSelections, productCode);
* client.setBaseAddress(url);
* client.executeRequest();
* ProductValidationSummary productValidationSummary = client.Result();
* </code></pre></p>
* @param productCode Merchant-created code that uniquely identifies the product such as a SKU or item number. Once created, the product code is read-only.
* @param productOptionSelections For a product with shopper-configurable options, the properties of the product options selected by the shopper.
* @return Mozu.Api.MozuClient <com.mozu.api.contracts.productruntime.ProductValidationSummary>
* @see com.mozu.api.contracts.productruntime.ProductValidationSummary
* @see com.mozu.api.contracts.productruntime.ProductOptionSelections
*/ | Validate the final state of shopper-selected options. <code><code> MozuClient mozuClient=ValidateProductClient( productOptionSelections, productCode); client.setBaseAddress(url); client.executeRequest(); ProductValidationSummary productValidationSummary = client.Result(); </code></code> | validateProductClient | {
"repo_name": "sanjaymandadi/mozu-java",
"path": "mozu-java-core/src/main/java/com/mozu/api/clients/commerce/catalog/storefront/ProductClient.java",
"license": "mit",
"size": 25140
} | [
"com.mozu.api.MozuClient"
] | import com.mozu.api.MozuClient; | import com.mozu.api.*; | [
"com.mozu.api"
] | com.mozu.api; | 1,492,210 |
public void deleteClassificationNode(
final String project,
final TreeStructureGroup structureGroup,
final String path,
final Integer reclassifyId) {
final UUID locationId = UUID.fromString("5a172953-1b41-49d3-840a-33f79c3ce89f"); //$NON-NLS-1$
final ApiResourceVersion apiVersion = new ApiResourceVersion("3.1-preview.2"); //$NON-NLS-1$
final Map<String, Object> routeValues = new HashMap<String, Object>();
routeValues.put("project", project); //$NON-NLS-1$
routeValues.put("structureGroup", structureGroup); //$NON-NLS-1$
routeValues.put("path", path); //$NON-NLS-1$
final NameValueCollection queryParameters = new NameValueCollection();
queryParameters.addIfNotNull("$reclassifyId", reclassifyId); //$NON-NLS-1$
final VssRestRequest httpRequest = super.createRequest(HttpMethod.DELETE,
locationId,
routeValues,
apiVersion,
queryParameters,
VssMediaTypes.APPLICATION_JSON_TYPE);
super.sendRequest(httpRequest);
} | void function( final String project, final TreeStructureGroup structureGroup, final String path, final Integer reclassifyId) { final UUID locationId = UUID.fromString(STR); final ApiResourceVersion apiVersion = new ApiResourceVersion(STR); final Map<String, Object> routeValues = new HashMap<String, Object>(); routeValues.put(STR, project); routeValues.put(STR, structureGroup); routeValues.put("path", path); final NameValueCollection queryParameters = new NameValueCollection(); queryParameters.addIfNotNull(STR, reclassifyId); final VssRestRequest httpRequest = super.createRequest(HttpMethod.DELETE, locationId, routeValues, apiVersion, queryParameters, VssMediaTypes.APPLICATION_JSON_TYPE); super.sendRequest(httpRequest); } | /**
* [Preview API 3.1-preview.2]
*
* @param project
* Project ID or project name
* @param structureGroup
*
* @param path
*
* @param reclassifyId
*
*/ | [Preview API 3.1-preview.2] | deleteClassificationNode | {
"repo_name": "Microsoft/vso-httpclient-java",
"path": "Rest/alm-tfs-client/src/main/generated/com/microsoft/alm/teamfoundation/workitemtracking/webapi/WorkItemTrackingHttpClientBase.java",
"license": "mit",
"size": 169431
} | [
"com.microsoft.alm.client.HttpMethod",
"com.microsoft.alm.client.VssMediaTypes",
"com.microsoft.alm.client.VssRestRequest",
"com.microsoft.alm.client.model.NameValueCollection",
"com.microsoft.alm.teamfoundation.workitemtracking.webapi.models.TreeStructureGroup",
"com.microsoft.alm.visualstudio.services.w... | import com.microsoft.alm.client.HttpMethod; import com.microsoft.alm.client.VssMediaTypes; import com.microsoft.alm.client.VssRestRequest; import com.microsoft.alm.client.model.NameValueCollection; import com.microsoft.alm.teamfoundation.workitemtracking.webapi.models.TreeStructureGroup; import com.microsoft.alm.visualstudio.services.webapi.ApiResourceVersion; import java.util.HashMap; import java.util.Map; import java.util.UUID; | import com.microsoft.alm.client.*; import com.microsoft.alm.client.model.*; import com.microsoft.alm.teamfoundation.workitemtracking.webapi.models.*; import com.microsoft.alm.visualstudio.services.webapi.*; import java.util.*; | [
"com.microsoft.alm",
"java.util"
] | com.microsoft.alm; java.util; | 2,347,179 |
List<Snapshot> getAllByStorageDomain(Guid storageId); | List<Snapshot> getAllByStorageDomain(Guid storageId); | /**
* Get all the snapshots with disks on the specified storage domain.
*
* @param storageId
* The Storage Domain ID.
* @return the list of snapshots.
*/ | Get all the snapshots with disks on the specified storage domain | getAllByStorageDomain | {
"repo_name": "OpenUniversity/ovirt-engine",
"path": "backend/manager/modules/dal/src/main/java/org/ovirt/engine/core/dao/SnapshotDao.java",
"license": "apache-2.0",
"size": 9030
} | [
"java.util.List",
"org.ovirt.engine.core.common.businessentities.Snapshot",
"org.ovirt.engine.core.compat.Guid"
] | import java.util.List; import org.ovirt.engine.core.common.businessentities.Snapshot; import org.ovirt.engine.core.compat.Guid; | import java.util.*; import org.ovirt.engine.core.common.businessentities.*; import org.ovirt.engine.core.compat.*; | [
"java.util",
"org.ovirt.engine"
] | java.util; org.ovirt.engine; | 559,944 |
public List<DataObject> getDataToCopy()
{
if (model.getState() == DISCARDED) return null;
return model.getDataToCopy();
}
| List<DataObject> function() { if (model.getState() == DISCARDED) return null; return model.getDataToCopy(); } | /**
* Implemented as specified by the {@link TreeViewer} interface.
* @see TreeViewer#getDataToCopy()
*/ | Implemented as specified by the <code>TreeViewer</code> interface | getDataToCopy | {
"repo_name": "stelfrich/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/agents/treeviewer/view/TreeViewerComponent.java",
"license": "gpl-2.0",
"size": 160473
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,584,273 |
public static void main(String[] args)
{
System.out.println("YAJSW: "+YajswVersion.YAJSW_VERSION);
System.out.println("OS : "+YajswVersion.OS_VERSION);
System.out.println("JVM : "+YajswVersion.JAVA_VERSION);
String wrapperJar = WrapperLoader.getWrapperJar();
String homeDir = new File(wrapperJar).getParent();
if (!OperatingSystem.instance().setWorkingDir(homeDir))
System.out.println("could not set working dir, pls check configuration or user rights: "+homeDir);
// System.out.println(System.getProperty("java.class.path"));
buildOptions();
parseCommand(args);
if (cmds != null && cmds.size() > 0)
for (Iterator it = cmds.iterator(); it.hasNext();)
{
Object cmd = it.next();
if (cmd instanceof DefaultOption)
executeCommand((Option) cmd);
}
else
executeCommand(group.findOption("c"));
if (_exitOnTerminate)
Runtime.getRuntime().halt(_exitCode);
}
| static void function(String[] args) { System.out.println(STR+YajswVersion.YAJSW_VERSION); System.out.println(STR+YajswVersion.OS_VERSION); System.out.println(STR+YajswVersion.JAVA_VERSION); String wrapperJar = WrapperLoader.getWrapperJar(); String homeDir = new File(wrapperJar).getParent(); if (!OperatingSystem.instance().setWorkingDir(homeDir)) System.out.println(STR+homeDir); buildOptions(); parseCommand(args); if (cmds != null && cmds.size() > 0) for (Iterator it = cmds.iterator(); it.hasNext();) { Object cmd = it.next(); if (cmd instanceof DefaultOption) executeCommand((Option) cmd); } else executeCommand(group.findOption("c")); if (_exitOnTerminate) Runtime.getRuntime().halt(_exitCode); } | /**
* The main method.
*
* @param args
* the arguments
*/ | The main method | main | {
"repo_name": "roidelapluie/yajsw",
"path": "src/yajsw/src/main/java/org/rzo/yajsw/WrapperExe.java",
"license": "lgpl-2.1",
"size": 22961
} | [
"java.io.File",
"java.util.Iterator",
"org.apache.commons.cli2.Option",
"org.apache.commons.cli2.option.DefaultOption",
"org.rzo.yajsw.boot.WrapperLoader",
"org.rzo.yajsw.os.OperatingSystem"
] | import java.io.File; import java.util.Iterator; import org.apache.commons.cli2.Option; import org.apache.commons.cli2.option.DefaultOption; import org.rzo.yajsw.boot.WrapperLoader; import org.rzo.yajsw.os.OperatingSystem; | import java.io.*; import java.util.*; import org.apache.commons.cli2.*; import org.apache.commons.cli2.option.*; import org.rzo.yajsw.boot.*; import org.rzo.yajsw.os.*; | [
"java.io",
"java.util",
"org.apache.commons",
"org.rzo.yajsw"
] | java.io; java.util; org.apache.commons; org.rzo.yajsw; | 4,628 |
protected OkHttpClient.Builder newOkHttpClientBuilder() {
return new OkHttpClient.Builder();
} | OkHttpClient.Builder function() { return new OkHttpClient.Builder(); } | /**
* Subclasses may use this to apply a base configuration to the builder
*/ | Subclasses may use this to apply a base configuration to the builder | newOkHttpClientBuilder | {
"repo_name": "fabric8io/kubernetes-client",
"path": "httpclient-okhttp/src/main/java/io/fabric8/kubernetes/client/okhttp/OkHttpClientFactory.java",
"license": "apache-2.0",
"size": 4105
} | [
"io.fabric8.kubernetes.client.http.HttpClient"
] | import io.fabric8.kubernetes.client.http.HttpClient; | import io.fabric8.kubernetes.client.http.*; | [
"io.fabric8.kubernetes"
] | io.fabric8.kubernetes; | 1,430,431 |
public static @NotNull String mangleNameToClassName(@NotNull String localName) {
return NameConverter.standard.toClassName(localName);
} | static @NotNull String function(@NotNull String localName) { return NameConverter.standard.toClassName(localName); } | /**
* Computes a Java class name from a local name.
*
* <p>
* This method faithfully implements the name mangling rule as specified in the JAXB spec.
*
* @return
* Typically, this method returns "NameLikeThis".
*/ | Computes a Java class name from a local name. This method faithfully implements the name mangling rule as specified in the JAXB spec | mangleNameToClassName | {
"repo_name": "PrincetonUniversity/NVJVM",
"path": "build/linux-amd64/jaxws/drop/jaxws_src/src/com/sun/xml/internal/bind/api/JAXBRIContext.java",
"license": "gpl-2.0",
"size": 17009
} | [
"com.sun.istack.internal.NotNull",
"com.sun.xml.internal.bind.api.impl.NameConverter"
] | import com.sun.istack.internal.NotNull; import com.sun.xml.internal.bind.api.impl.NameConverter; | import com.sun.istack.internal.*; import com.sun.xml.internal.bind.api.impl.*; | [
"com.sun.istack",
"com.sun.xml"
] | com.sun.istack; com.sun.xml; | 596,575 |
@ServiceMethod(returns = ReturnType.SINGLE)
Response<NetworkInterfaceInner> updateTagsWithResponse(
String resourceGroupName, String networkInterfaceName, TagsObject parameters, Context context); | @ServiceMethod(returns = ReturnType.SINGLE) Response<NetworkInterfaceInner> updateTagsWithResponse( String resourceGroupName, String networkInterfaceName, TagsObject parameters, Context context); | /**
* Updates a network interface tags.
*
* @param resourceGroupName The name of the resource group.
* @param networkInterfaceName The name of the network interface.
* @param parameters Parameters supplied to update network interface tags.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.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 network interface in a resource group along with {@link Response}.
*/ | Updates a network interface tags | updateTagsWithResponse | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/NetworkInterfacesClient.java",
"license": "mit",
"size": 71039
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.Response",
"com.azure.core.util.Context",
"com.azure.resourcemanager.network.fluent.models.NetworkInterfaceInner",
"com.azure.resourcemanager.network.models.TagsObject"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.network.fluent.models.NetworkInterfaceInner; import com.azure.resourcemanager.network.models.TagsObject; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.core.util.*; import com.azure.resourcemanager.network.fluent.models.*; import com.azure.resourcemanager.network.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 1,861,968 |
public void territoryForDeployment(String territory, boolean autoDeploy) {
Map<String, Integer> territoryUnitMap = Maps.newHashMap();
territoryUnitMap.put(territory, 1);
container.sendMakeMove(riskLogic.performDeployment(
riskState, territoryUnitMap, myPlayerId, autoDeploy));
} | void function(String territory, boolean autoDeploy) { Map<String, Integer> territoryUnitMap = Maps.newHashMap(); territoryUnitMap.put(territory, 1); container.sendMakeMove(riskLogic.performDeployment( riskState, territoryUnitMap, myPlayerId, autoDeploy)); } | /**
* Perform the deployment operations for given territory.
* This method is called by view only if the presenter called
* {@link View#chooseTerritoryForDeployment()}.
* @param territory
*/ | Perform the deployment operations for given territory. This method is called by view only if the presenter called <code>View#chooseTerritoryForDeployment()</code> | territoryForDeployment | {
"repo_name": "spk83/risk",
"path": "src/org/risk/graphics/RiskPresenter.java",
"license": "apache-2.0",
"size": 13634
} | [
"com.google.common.collect.Maps",
"java.util.Map"
] | import com.google.common.collect.Maps; import java.util.Map; | import com.google.common.collect.*; import java.util.*; | [
"com.google.common",
"java.util"
] | com.google.common; java.util; | 1,888,418 |
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// retrieve the error code, if available
int errorCode = -1;
if (data != null) {
errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, -1);
}
switch (requestCode) {
case REQUEST_CODE_MASKED_WALLET:
Log.d(TAG, "onActivityResult() => RESULT CODE MASKED WALLET");
switch (resultCode) {
case Activity.RESULT_OK:
Log.d(TAG, "onActivityResult() => RESULT OK");
// "MaskedWalletRequest" will generate this MaskedWallet.
MaskedWallet maskedWallet = data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET);
launchProductCheckoutActivity(maskedWallet);
break;
case Activity.RESULT_CANCELED:
Log.d(TAG, "onActivityResult() => RESULT CANCELLED");
break;
default:
Log.d(TAG, "onActivityResult() => DEFAULT handleError()");
handleError(errorCode);
break;
}
break;
case WalletConstants.RESULT_ERROR:
Log.d(TAG, "onActivityResult() => RESULT ERROR");
handleError(errorCode);
break;
default:
Log.d(TAG, "onActivityResult() => DEFAULT");
super.onActivityResult(requestCode, resultCode, data);
break;
}
} | void function(int requestCode, int resultCode, Intent data) { int errorCode = -1; if (data != null) { errorCode = data.getIntExtra(WalletConstants.EXTRA_ERROR_CODE, -1); } switch (requestCode) { case REQUEST_CODE_MASKED_WALLET: Log.d(TAG, STR); switch (resultCode) { case Activity.RESULT_OK: Log.d(TAG, STR); MaskedWallet maskedWallet = data.getParcelableExtra(WalletConstants.EXTRA_MASKED_WALLET); launchProductCheckoutActivity(maskedWallet); break; case Activity.RESULT_CANCELED: Log.d(TAG, STR); break; default: Log.d(TAG, STR); handleError(errorCode); break; } break; case WalletConstants.RESULT_ERROR: Log.d(TAG, STR); handleError(errorCode); break; default: Log.d(TAG, STR); super.onActivityResult(requestCode, resultCode, data); break; } } | /**
* If successful, this will receive a Masked Wallet.
* Masked Wallet will be passed as a parameter to launch the ProductCheckoutActivity
* @param requestCode
* @param resultCode
* @param data
*/ | If successful, this will receive a Masked Wallet. Masked Wallet will be passed as a parameter to launch the ProductCheckoutActivity | onActivityResult | {
"repo_name": "briandang714/android-pay-payment-gateway",
"path": "app/src/main/java/com/android_pay_payment_gateway/ProductDetailActivity.java",
"license": "apache-2.0",
"size": 13687
} | [
"android.app.Activity",
"android.content.Intent",
"android.util.Log",
"com.google.android.gms.wallet.MaskedWallet",
"com.google.android.gms.wallet.WalletConstants"
] | import android.app.Activity; import android.content.Intent; import android.util.Log; import com.google.android.gms.wallet.MaskedWallet; import com.google.android.gms.wallet.WalletConstants; | import android.app.*; import android.content.*; import android.util.*; import com.google.android.gms.wallet.*; | [
"android.app",
"android.content",
"android.util",
"com.google.android"
] | android.app; android.content; android.util; com.google.android; | 2,361,805 |
public Builder applyToAllUnaryMethods(
ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) {
super.applyToAllUnaryMethods(
getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater);
return this;
} | Builder function( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods( getStubSettingsBuilder().unaryMethodSettingsBuilders(), settingsUpdater); return this; } | /**
* Applies the given settings updater function to all of the unary API methods in this service.
*
* <p>Note: This method does not support applying settings to streaming methods.
*/ | Applies the given settings updater function to all of the unary API methods in this service. Note: This method does not support applying settings to streaming methods | applyToAllUnaryMethods | {
"repo_name": "googleads/google-ads-java",
"path": "google-ads-stubs-v8/src/main/java/com/google/ads/googleads/v8/services/CarrierConstantServiceSettings.java",
"license": "apache-2.0",
"size": 7425
} | [
"com.google.api.core.ApiFunction",
"com.google.api.gax.rpc.UnaryCallSettings"
] | import com.google.api.core.ApiFunction; import com.google.api.gax.rpc.UnaryCallSettings; | import com.google.api.core.*; import com.google.api.gax.rpc.*; | [
"com.google.api"
] | com.google.api; | 250,834 |
private void guardar() {
getCtx().x = x;
getCtx().y = y;
getCtx().lastPressed = lastPressed;
getCtx().map = map;
getCtx().getMapas().put(play.getMapa(), play);
getCtx().existe = true;
boolean saved = Guardador.guardar(getCtx());
writing = true;
if (saved) {
getCtx().dialogo.procesarDialogo("guardado_1");
} else {
getCtx().dialogo.procesarDialogo("guardado_2");
}
String l1 = getCtx().dialogo.siguienteLinea();
String l2 = getCtx().dialogo.siguienteLinea();
if (l1 != null) {
if (l2 == null) {
l2 = "";
}
getCtx().dialogo.setLineas(l1, l2);
}
} | void function() { getCtx().x = x; getCtx().y = y; getCtx().lastPressed = lastPressed; getCtx().map = map; getCtx().getMapas().put(play.getMapa(), play); getCtx().existe = true; boolean saved = Guardador.guardar(getCtx()); writing = true; if (saved) { getCtx().dialogo.procesarDialogo(STR); } else { getCtx().dialogo.procesarDialogo(STR); } String l1 = getCtx().dialogo.siguienteLinea(); String l2 = getCtx().dialogo.siguienteLinea(); if (l1 != null) { if (l2 == null) { l2 = ""; } getCtx().dialogo.setLineas(l1, l2); } } | /**
* Guarda el objeto ArchivoGuardado en un fichero binario.
*/ | Guarda el objeto ArchivoGuardado en un fichero binario | guardar | {
"repo_name": "jorcox/PokemonAdaByron3D",
"path": "src/com/pokemon/pantallas/MenuPlay.java",
"license": "apache-2.0",
"size": 7211
} | [
"com.pokemon.utilidades.Guardador"
] | import com.pokemon.utilidades.Guardador; | import com.pokemon.utilidades.*; | [
"com.pokemon.utilidades"
] | com.pokemon.utilidades; | 1,108,993 |
public void executeDartCallbackInBackgroundIsolate(Intent intent, final CountDownLatch latch) {
// Grab the handle for the callback associated with this alarm. Pay close
// attention to the type of the callback handle as storing this value in a
// variable of the wrong size will cause the callback lookup to fail.
long callbackHandle = intent.getLongExtra("callbackHandle", 0); | void function(Intent intent, final CountDownLatch latch) { long callbackHandle = intent.getLongExtra(STR, 0); | /**
* Executes the desired Dart callback in a background Dart isolate.
*
* <p>The given {@code intent} should contain a {@code long} extra called "callbackHandle", which
* corresponds to a callback registered with the Dart VM.
*/ | Executes the desired Dart callback in a background Dart isolate. The given intent should contain a long extra called "callbackHandle", which corresponds to a callback registered with the Dart VM | executeDartCallbackInBackgroundIsolate | {
"repo_name": "mehmetf/plugins",
"path": "packages/android_alarm_manager/android/src/main/java/io/flutter/plugins/androidalarmmanager/FlutterBackgroundExecutor.java",
"license": "bsd-3-clause",
"size": 9575
} | [
"android.content.Intent",
"java.util.concurrent.CountDownLatch"
] | import android.content.Intent; import java.util.concurrent.CountDownLatch; | import android.content.*; import java.util.concurrent.*; | [
"android.content",
"java.util"
] | android.content; java.util; | 1,156,242 |
public static Block getBlockByItem(Item item) {
return Block.getBlockFromItem(item);
} | static Block function(Item item) { return Block.getBlockFromItem(item); } | /**
* Gets a block by it's item version.
*
* @param item The item to get the block from.
* @return Return the block associated with param item.
*/ | Gets a block by it's item version | getBlockByItem | {
"repo_name": "BlazeLoader/BlazeLoader",
"path": "src/main/com/blazeloader/api/block/ApiBlock.java",
"license": "bsd-2-clause",
"size": 12935
} | [
"net.minecraft.block.Block",
"net.minecraft.item.Item"
] | import net.minecraft.block.Block; import net.minecraft.item.Item; | import net.minecraft.block.*; import net.minecraft.item.*; | [
"net.minecraft.block",
"net.minecraft.item"
] | net.minecraft.block; net.minecraft.item; | 1,498,909 |
EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser,
int tenantId) throws DeviceManagementDAOException; | EnrolmentInfo getEnrolment(DeviceIdentifier deviceId, String currentUser, int tenantId) throws DeviceManagementDAOException; | /**
* This method is used to retrieve current enrollment of a given device and user.
*
* @param deviceId device id.
* @param currentUser user name.
* @param tenantId tenant id.
* @return returns EnrolmentInfo object.
* @throws DeviceManagementDAOException
*/ | This method is used to retrieve current enrollment of a given device and user | getEnrolment | {
"repo_name": "GDLMadushanka/carbon-device-mgt",
"path": "components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/dao/DeviceDAO.java",
"license": "apache-2.0",
"size": 17541
} | [
"org.wso2.carbon.device.mgt.common.DeviceIdentifier",
"org.wso2.carbon.device.mgt.common.EnrolmentInfo"
] | import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.EnrolmentInfo; | import org.wso2.carbon.device.mgt.common.*; | [
"org.wso2.carbon"
] | org.wso2.carbon; | 1,838,542 |
public void onEntityDestroyed(ClientEntity ent);
}
private static Comparator<ClientEntity> renderComparator = new Comparator<ClientEntity>() { | void function(ClientEntity ent); } private static Comparator<ClientEntity> renderComparator = new Comparator<ClientEntity>() { | /**
* A {@link ClientEntity} was destroyed
* @param ent
*/ | A <code>ClientEntity</code> was destroyed | onEntityDestroyed | {
"repo_name": "tonysparks/seventh",
"path": "src/seventh/client/ClientGame.java",
"license": "gpl-2.0",
"size": 69082
} | [
"java.util.Comparator"
] | import java.util.Comparator; | import java.util.*; | [
"java.util"
] | java.util; | 1,145,602 |
public static boolean isItemFuel(ItemStack par0ItemStack)
{
return getItemBurnTime(par0ItemStack) > 0;
} | static boolean function(ItemStack par0ItemStack) { return getItemBurnTime(par0ItemStack) > 0; } | /**
* Return true if item is a fuel source (getItemBurnTime() > 0).
*/ | Return true if item is a fuel source (getItemBurnTime() > 0) | isItemFuel | {
"repo_name": "Morton00000/CivCraft",
"path": "common/civcraft/tiles/machines/TileFurnaceMold.java",
"license": "gpl-3.0",
"size": 13788
} | [
"net.minecraft.item.ItemStack"
] | import net.minecraft.item.ItemStack; | import net.minecraft.item.*; | [
"net.minecraft.item"
] | net.minecraft.item; | 2,561,528 |
@org.junit.Test
public void testPKIPath() throws Exception {
Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
WSSecHeader secHeader = new WSSecHeader();
secHeader.insertSecurityHeader(doc);
PKIPathSecurity bst = new PKIPathSecurity(doc);
CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
cryptoType.setAlias("wss40");
X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
bst.setX509Certificates(certs, crypto);
WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement());
if (LOG.isDebugEnabled()) {
LOG.debug("PKIPath output");
String outputString =
org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
LOG.debug(outputString);
}
WSSConfig config = WSSConfig.getNewInstance();
config.setWsiBSPCompliant(true);
WSSecurityEngine secEngine = new WSSecurityEngine();
secEngine.setWssConfig(config);
List<WSSecurityEngineResult> results =
secEngine.processSecurityHeader(doc, null, null, crypto);
WSSecurityEngineResult actionResult =
WSSecurityUtil.fetchActionResult(results, WSConstants.BST);
PKIPathSecurity token =
(PKIPathSecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN);
assertNotNull(token);
} | @org.junit.Test void function() throws Exception { Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG); WSSecHeader secHeader = new WSSecHeader(); secHeader.insertSecurityHeader(doc); PKIPathSecurity bst = new PKIPathSecurity(doc); CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS); cryptoType.setAlias("wss40"); X509Certificate[] certs = crypto.getX509Certificates(cryptoType); bst.setX509Certificates(certs, crypto); WSSecurityUtil.prependChildElement(secHeader.getSecurityHeader(), bst.getElement()); if (LOG.isDebugEnabled()) { LOG.debug(STR); String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc); LOG.debug(outputString); } WSSConfig config = WSSConfig.getNewInstance(); config.setWsiBSPCompliant(true); WSSecurityEngine secEngine = new WSSecurityEngine(); secEngine.setWssConfig(config); List<WSSecurityEngineResult> results = secEngine.processSecurityHeader(doc, null, null, crypto); WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.BST); PKIPathSecurity token = (PKIPathSecurity)actionResult.get(WSSecurityEngineResult.TAG_BINARY_SECURITY_TOKEN); assertNotNull(token); } | /**
* A unit test for an PKIPath BinarySecurityToken
*/ | A unit test for an PKIPath BinarySecurityToken | testPKIPath | {
"repo_name": "fatfredyy/wss4j-ecc",
"path": "src/test/java/org/apache/ws/security/message/token/BinarySecurityTokenTest.java",
"license": "apache-2.0",
"size": 7339
} | [
"java.security.cert.X509Certificate",
"java.util.List",
"org.apache.ws.security.WSConstants",
"org.apache.ws.security.WSSConfig",
"org.apache.ws.security.WSSecurityEngine",
"org.apache.ws.security.WSSecurityEngineResult",
"org.apache.ws.security.common.SOAPUtil",
"org.apache.ws.security.components.cry... | import java.security.cert.X509Certificate; import java.util.List; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSSConfig; import org.apache.ws.security.WSSecurityEngine; import org.apache.ws.security.WSSecurityEngineResult; import org.apache.ws.security.common.SOAPUtil; import org.apache.ws.security.components.crypto.CryptoType; import org.apache.ws.security.message.WSSecHeader; import org.apache.ws.security.util.WSSecurityUtil; import org.w3c.dom.Document; | import java.security.cert.*; import java.util.*; import org.apache.ws.security.*; import org.apache.ws.security.common.*; import org.apache.ws.security.components.crypto.*; import org.apache.ws.security.message.*; import org.apache.ws.security.util.*; import org.w3c.dom.*; | [
"java.security",
"java.util",
"org.apache.ws",
"org.w3c.dom"
] | java.security; java.util; org.apache.ws; org.w3c.dom; | 97,500 |
@MethodSource("com.azure.messaging.servicebus.IntegrationTestBase#messagingEntityProvider")
@ParameterizedTest
void nonSessionQueueSendMessage(MessagingEntityType entityType) {
// Arrange
setSenderAndReceiver(entityType, 0, false);
final String messageId = UUID.randomUUID().toString();
final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId);
// Assert & Act
StepVerifier.create(sender.sendMessage(message).doOnSuccess(aVoid -> messagesPending.incrementAndGet()))
.verifyComplete();
} | @MethodSource(STR) void nonSessionQueueSendMessage(MessagingEntityType entityType) { setSenderAndReceiver(entityType, 0, false); final String messageId = UUID.randomUUID().toString(); final ServiceBusMessage message = TestUtils.getServiceBusMessage(CONTENTS_BYTES, messageId); StepVerifier.create(sender.sendMessage(message).doOnSuccess(aVoid -> messagesPending.incrementAndGet())) .verifyComplete(); } | /**
* Verifies that we can send a message to a non-session queue.
*/ | Verifies that we can send a message to a non-session queue | nonSessionQueueSendMessage | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/servicebus/azure-messaging-servicebus/src/test/java/com/azure/messaging/servicebus/ServiceBusSenderAsyncClientIntegrationTest.java",
"license": "mit",
"size": 22853
} | [
"com.azure.messaging.servicebus.implementation.MessagingEntityType",
"java.util.UUID",
"org.junit.jupiter.params.provider.MethodSource"
] | import com.azure.messaging.servicebus.implementation.MessagingEntityType; import java.util.UUID; import org.junit.jupiter.params.provider.MethodSource; | import com.azure.messaging.servicebus.implementation.*; import java.util.*; import org.junit.jupiter.params.provider.*; | [
"com.azure.messaging",
"java.util",
"org.junit.jupiter"
] | com.azure.messaging; java.util; org.junit.jupiter; | 795,462 |
public void setDefaultRegTokens(Set<Token> p) {
this.defaultRegTokens = p;
} | void function(Set<Token> p) { this.defaultRegTokens = p; } | /**
* Setter for defaultRegTokens
* @param p The packageLists to set.
*/ | Setter for defaultRegTokens | setDefaultRegTokens | {
"repo_name": "mcalmer/spacewalk",
"path": "java/code/src/com/redhat/rhn/domain/kickstart/KickstartData.java",
"license": "gpl-2.0",
"size": 48539
} | [
"com.redhat.rhn.domain.token.Token",
"java.util.Set"
] | import com.redhat.rhn.domain.token.Token; import java.util.Set; | import com.redhat.rhn.domain.token.*; import java.util.*; | [
"com.redhat.rhn",
"java.util"
] | com.redhat.rhn; java.util; | 2,360,237 |
public static String getDefaultPartitionName(JobConfWrapper confWrapper) {
return getDefaultPartitionName(confWrapper.conf());
} | static String function(JobConfWrapper confWrapper) { return getDefaultPartitionName(confWrapper.conf()); } | /**
* Gets the {@link HiveConf.ConfVars#DEFAULTPARTITIONNAME} value from the {@link
* JobConfWrapper}.
*/ | Gets the <code>HiveConf.ConfVars#DEFAULTPARTITIONNAME</code> value from the <code>JobConfWrapper</code> | getDefaultPartitionName | {
"repo_name": "apache/flink",
"path": "flink-connectors/flink-connector-hive/src/main/java/org/apache/flink/connectors/hive/util/JobConfUtils.java",
"license": "apache-2.0",
"size": 2704
} | [
"org.apache.flink.connectors.hive.JobConfWrapper"
] | import org.apache.flink.connectors.hive.JobConfWrapper; | import org.apache.flink.connectors.hive.*; | [
"org.apache.flink"
] | org.apache.flink; | 813,684 |
@Test
public void testUpgradeFromRel2ReservedImage() throws Exception {
unpackStorage(HADOOP2_RESERVED_IMAGE, HADOOP_DFS_DIR_TXT);
MiniDFSCluster cluster = null;
// Try it once without setting the upgrade flag to ensure it fails
final Configuration conf = new Configuration();
try {
cluster =
new MiniDFSCluster.Builder(conf)
.format(false)
.startupOption(StartupOption.UPGRADE)
.numDataNodes(0).build();
} catch (IllegalArgumentException e) {
GenericTestUtils.assertExceptionContains(
"reserved path component in this version",
e);
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
// Try it again with a custom rename string
try {
FSImageFormat.setRenameReservedPairs(
".snapshot=.user-snapshot," +
".reserved=.my-reserved");
cluster =
new MiniDFSCluster.Builder(conf)
.format(false)
.startupOption(StartupOption.UPGRADE)
.numDataNodes(0).build();
DistributedFileSystem dfs = cluster.getFileSystem();
// Make sure the paths were renamed as expected
// Also check that paths are present after a restart, checks that the
// upgraded fsimage has the same state.
final String[] expected = new String[] {
"/edits",
"/edits/.reserved",
"/edits/.user-snapshot",
"/edits/.user-snapshot/editsdir",
"/edits/.user-snapshot/editsdir/editscontents",
"/edits/.user-snapshot/editsdir/editsdir2",
"/image",
"/image/.reserved",
"/image/.user-snapshot",
"/image/.user-snapshot/imagedir",
"/image/.user-snapshot/imagedir/imagecontents",
"/image/.user-snapshot/imagedir/imagedir2",
"/.my-reserved",
"/.my-reserved/edits-touch",
"/.my-reserved/image-touch"
};
for (int i=0; i<2; i++) {
// Restart the second time through this loop
if (i==1) {
cluster.finalizeCluster(conf);
cluster.restartNameNode(true);
}
ArrayList<Path> toList = new ArrayList<Path>();
toList.add(new Path("/"));
ArrayList<String> found = new ArrayList<String>();
while (!toList.isEmpty()) {
Path p = toList.remove(0);
FileStatus[] statuses = dfs.listStatus(p);
for (FileStatus status: statuses) {
final String path = status.getPath().toUri().getPath();
System.out.println("Found path " + path);
found.add(path);
if (status.isDirectory()) {
toList.add(status.getPath());
}
}
}
for (String s: expected) {
assertTrue("Did not find expected path " + s, found.contains(s));
}
assertEquals("Found an unexpected path while listing filesystem",
found.size(), expected.length);
}
} finally {
if (cluster != null) {
cluster.shutdown();
}
}
} | void function() throws Exception { unpackStorage(HADOOP2_RESERVED_IMAGE, HADOOP_DFS_DIR_TXT); MiniDFSCluster cluster = null; final Configuration conf = new Configuration(); try { cluster = new MiniDFSCluster.Builder(conf) .format(false) .startupOption(StartupOption.UPGRADE) .numDataNodes(0).build(); } catch (IllegalArgumentException e) { GenericTestUtils.assertExceptionContains( STR, e); } finally { if (cluster != null) { cluster.shutdown(); } } try { FSImageFormat.setRenameReservedPairs( STR + STR); cluster = new MiniDFSCluster.Builder(conf) .format(false) .startupOption(StartupOption.UPGRADE) .numDataNodes(0).build(); DistributedFileSystem dfs = cluster.getFileSystem(); final String[] expected = new String[] { STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR, STR }; for (int i=0; i<2; i++) { if (i==1) { cluster.finalizeCluster(conf); cluster.restartNameNode(true); } ArrayList<Path> toList = new ArrayList<Path>(); toList.add(new Path("/")); ArrayList<String> found = new ArrayList<String>(); while (!toList.isEmpty()) { Path p = toList.remove(0); FileStatus[] statuses = dfs.listStatus(p); for (FileStatus status: statuses) { final String path = status.getPath().toUri().getPath(); System.out.println(STR + path); found.add(path); if (status.isDirectory()) { toList.add(status.getPath()); } } } for (String s: expected) { assertTrue(STR + s, found.contains(s)); } assertEquals(STR, found.size(), expected.length); } } finally { if (cluster != null) { cluster.shutdown(); } } } | /**
* Test upgrade from 2.0 image with a variety of .snapshot and .reserved
* paths to test renaming on upgrade
*/ | Test upgrade from 2.0 image with a variety of .snapshot and .reserved paths to test renaming on upgrade | testUpgradeFromRel2ReservedImage | {
"repo_name": "Reidddddd/mo-hadoop2.6.0",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestDFSUpgradeFromImage.java",
"license": "apache-2.0",
"size": 21804
} | [
"java.util.ArrayList",
"org.apache.hadoop.conf.Configuration",
"org.apache.hadoop.fs.FileStatus",
"org.apache.hadoop.fs.Path",
"org.apache.hadoop.hdfs.server.common.HdfsServerConstants",
"org.apache.hadoop.hdfs.server.namenode.FSImageFormat",
"org.apache.hadoop.test.GenericTestUtils",
"org.junit.Asser... | import java.util.ArrayList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.hdfs.server.namenode.FSImageFormat; import org.apache.hadoop.test.GenericTestUtils; import org.junit.Assert; | import java.util.*; import org.apache.hadoop.conf.*; import org.apache.hadoop.fs.*; import org.apache.hadoop.hdfs.server.common.*; import org.apache.hadoop.hdfs.server.namenode.*; import org.apache.hadoop.test.*; import org.junit.*; | [
"java.util",
"org.apache.hadoop",
"org.junit"
] | java.util; org.apache.hadoop; org.junit; | 178,520 |
public static <T> List<T> readFromUnstartedReader(Source.Reader<T> reader) throws IOException {
return readRemainingFromReader(reader, false);
} | static <T> List<T> function(Source.Reader<T> reader) throws IOException { return readRemainingFromReader(reader, false); } | /**
* Reads all elements from the given unstarted {@link Source.Reader}.
*/ | Reads all elements from the given unstarted <code>Source.Reader</code> | readFromUnstartedReader | {
"repo_name": "vikkyrk/incubator-beam",
"path": "sdks/java/core/src/main/java/org/apache/beam/sdk/testing/SourceTestUtils.java",
"license": "apache-2.0",
"size": 32371
} | [
"java.io.IOException",
"java.util.List",
"org.apache.beam.sdk.io.Source"
] | import java.io.IOException; import java.util.List; import org.apache.beam.sdk.io.Source; | import java.io.*; import java.util.*; import org.apache.beam.sdk.io.*; | [
"java.io",
"java.util",
"org.apache.beam"
] | java.io; java.util; org.apache.beam; | 2,097,620 |
// c.f. HADOOP-6559
private synchronized void reLogin()
throws LoginException {
if (!isKrbTicket) {
return;
}
LoginContext login = getLogin();
if (login == null) {
throw new LoginException("login must be done first");
}
sleepUntilSufficientTimeElapsed();
LOG.info("Initiating logout for " + principal);
synchronized (Login.class) {
//clear up the kerberos state. But the tokens are not cleared! As per
//the Java kerberos login module code, only the kerberos credentials
//are cleared
login.logout();
//login and also update the subject field of this instance to
//have the new credentials (pass it to the LoginContext constructor)
login = new LoginContext(loginContextName, getSubject());
LOG.info("Initiating re-login for " + principal);
login.login();
setLogin(login);
}
} | synchronized void function() throws LoginException { if (!isKrbTicket) { return; } LoginContext login = getLogin(); if (login == null) { throw new LoginException(STR); } sleepUntilSufficientTimeElapsed(); LOG.info(STR + principal); synchronized (Login.class) { login.logout(); login = new LoginContext(loginContextName, getSubject()); LOG.info(STR + principal); login.login(); setLogin(login); } } | /**
* Re-login a principal. This method assumes that {@link #login(String)} has happened already.
* @throws javax.security.auth.login.LoginException on a failure
*/ | Re-login a principal. This method assumes that <code>#login(String)</code> has happened already | reLogin | {
"repo_name": "anshuiisc/storm-Allbolts-wiring",
"path": "storm-core/src/jvm/org/apache/storm/messaging/netty/Login.java",
"license": "apache-2.0",
"size": 19046
} | [
"javax.security.auth.login.LoginContext",
"javax.security.auth.login.LoginException"
] | import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; | import javax.security.auth.login.*; | [
"javax.security"
] | javax.security; | 646,373 |
public ClassNamePersistence getClassNamePersistence() {
return classNamePersistence;
} | ClassNamePersistence function() { return classNamePersistence; } | /**
* Returns the class name persistence.
*
* @return the class name persistence
*/ | Returns the class name persistence | getClassNamePersistence | {
"repo_name": "falko0000/moduleEProc",
"path": "postavwiki/postavwiki-service/src/main/java/tj/postavwiki/service/base/PostavwikiServiceBaseImpl.java",
"license": "lgpl-2.1",
"size": 9811
} | [
"com.liferay.portal.kernel.service.persistence.ClassNamePersistence"
] | import com.liferay.portal.kernel.service.persistence.ClassNamePersistence; | import com.liferay.portal.kernel.service.persistence.*; | [
"com.liferay.portal"
] | com.liferay.portal; | 1,470,337 |
default Vector3i getHighestPositionAt(Vector3i position) {
return new Vector3i(position.getX(), getHighestYAt(position.getX(), position.getZ()), position.getZ());
} | default Vector3i getHighestPositionAt(Vector3i position) { return new Vector3i(position.getX(), getHighestYAt(position.getX(), position.getZ()), position.getZ()); } | /**
* Get the {@link Location} of the highest block that sunlight can reach in
* the given column.
*
* <p>This method ignores all transparent blocks, providing the highest
* opaque block.</p>
*
* @param position The column position
* @return The highest opaque position
*/ | Get the <code>Location</code> of the highest block that sunlight can reach in the given column. This method ignores all transparent blocks, providing the highest opaque block | getHighestPositionAt | {
"repo_name": "JBYoshi/SpongeAPI",
"path": "src/main/java/org/spongepowered/api/world/extent/Extent.java",
"license": "mit",
"size": 22806
} | [
"com.flowpowered.math.vector.Vector3i"
] | import com.flowpowered.math.vector.Vector3i; | import com.flowpowered.math.vector.*; | [
"com.flowpowered.math"
] | com.flowpowered.math; | 1,985,218 |
private TreeMap<String,Element> parseObject() {
TreeMap<String,Element> object=new TreeMap<>();//create hashed map
char chr=next();//consume first character
assert chr=='{';//assert first character is open curly bracket
while (chr!='}') {//until closing bracket found
switch (peek()) {//switch on next character
case ' ':
case '\t':
case '\n':
case '\r': chr=next(); //discard whitespace
break;
case '"': String key=parseString();//parse key
while (peek()<=' ') next();//skip whitespace
chr=next();//consume the next character
if (chr!=':') throw new RuntimeException("Invalid syntax : "+context());//must be havin a giraffe?
while (peek()<=' ') next();//skip whitespace
switch (peek()) {//switch on the next character in key value pair
case '"': object.put(key, new ScalarElement(Element.STRING,parseString()));//parse string value
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': object.put(key, new ScalarElement(Element.NUMBER,parseNumber()));//parse number value
break;
case 'f':
case 't': object.put(key, new ScalarElement(Element.BOOLEAN,parseBoolean()));//parse boolean value
break;
case 'n': object.put(key, new ScalarElement(Element.NULL,parseNull()));//parse null value
break;
case '[': object.put(key, new ArrayElement(parseArray()));//parse array value
break;
case '{': object.put(key, new ObjectElement(parseObject()));//parse object value
break;
default : throw new RuntimeException("Invalid syntax : "+context());//we have a problem houston
};//switch on the next character in key value pair
break;
case ',': chr=next();//consume comma character
break;
case '}': chr=next();//consume close bracket character
break;
default : throw new RuntimeException("Invalid syntax : "+context());//gone pete tong
}//switch on next character
}//until closing bracket found
return object;//happy days
}//parseObject()
| TreeMap<String,Element> function() { TreeMap<String,Element> object=new TreeMap<>(); char chr=next(); assert chr=='{'; while (chr!='}') { switch (peek()) { case ' ': case '\t': case '\n': case '\r': chr=next(); break; case 'STRInvalid syntax : STR': object.put(key, new ScalarElement(Element.STRING,parseString())); break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': object.put(key, new ScalarElement(Element.NUMBER,parseNumber())); break; case 'f': case 't': object.put(key, new ScalarElement(Element.BOOLEAN,parseBoolean())); break; case 'n': object.put(key, new ScalarElement(Element.NULL,parseNull())); break; case '[': object.put(key, new ArrayElement(parseArray())); break; case '{': object.put(key, new ObjectElement(parseObject())); break; default : throw new RuntimeException(STR+context()); }; break; case ',': chr=next(); break; case '}': chr=next(); break; default : throw new RuntimeException(STR+context()); } } return object; } | /**
* Parses an object
* @return hashed map representation of the object
*/ | Parses an object | parseObject | {
"repo_name": "justonedb/json",
"path": "src/main/java/com/justone/json/Parser.java",
"license": "mit",
"size": 19025
} | [
"java.util.TreeMap"
] | import java.util.TreeMap; | import java.util.*; | [
"java.util"
] | java.util; | 741,881 |
public void delete(Object object, DynamoDBMapperConfig config) {
config = mergeConfig(config);
Class<?> clazz = object.getClass();
String tableName = getTableName(clazz, config);
Method hashKeyGetter = reflector.getHashKeyGetter(clazz);
AttributeValue hashKeyElement = getHashKeyElement(safeInvoke(hashKeyGetter, object), hashKeyGetter);
AttributeValue rangeKeyElement = null;
Method rangeKeyGetter = reflector.getRangeKeyGetter(clazz);
if ( rangeKeyGetter != null ) {
rangeKeyElement = getRangeKeyElement(safeInvoke(rangeKeyGetter, object), rangeKeyGetter);
}
Key objectKey = new Key().withHashKeyElement(hashKeyElement).withRangeKeyElement(rangeKeyElement);
Map<String, ExpectedAttributeValue> expectedValues = new HashMap<String, ExpectedAttributeValue>();
if ( config.getSaveBehavior() != SaveBehavior.CLOBBER ) {
for ( Method method : reflector.getRelevantGetters(clazz) ) {
if ( reflector.isVersionAttributeGetter(method) ) {
Object getterResult = safeInvoke(method, object);
String attributeName = reflector.getAttributeName(method);
ExpectedAttributeValue expected = new ExpectedAttributeValue();
AttributeValue currentValue = getSimpleAttributeValue(method, getterResult);
expected.setExists(currentValue != null);
if ( currentValue != null )
expected.setValue(currentValue);
expectedValues.put(attributeName, expected);
break;
}
}
}
db.deleteItem(applyUserAgent(new DeleteItemRequest().withKey(objectKey).withTableName(tableName).withExpected(expectedValues)));
}
| void function(Object object, DynamoDBMapperConfig config) { config = mergeConfig(config); Class<?> clazz = object.getClass(); String tableName = getTableName(clazz, config); Method hashKeyGetter = reflector.getHashKeyGetter(clazz); AttributeValue hashKeyElement = getHashKeyElement(safeInvoke(hashKeyGetter, object), hashKeyGetter); AttributeValue rangeKeyElement = null; Method rangeKeyGetter = reflector.getRangeKeyGetter(clazz); if ( rangeKeyGetter != null ) { rangeKeyElement = getRangeKeyElement(safeInvoke(rangeKeyGetter, object), rangeKeyGetter); } Key objectKey = new Key().withHashKeyElement(hashKeyElement).withRangeKeyElement(rangeKeyElement); Map<String, ExpectedAttributeValue> expectedValues = new HashMap<String, ExpectedAttributeValue>(); if ( config.getSaveBehavior() != SaveBehavior.CLOBBER ) { for ( Method method : reflector.getRelevantGetters(clazz) ) { if ( reflector.isVersionAttributeGetter(method) ) { Object getterResult = safeInvoke(method, object); String attributeName = reflector.getAttributeName(method); ExpectedAttributeValue expected = new ExpectedAttributeValue(); AttributeValue currentValue = getSimpleAttributeValue(method, getterResult); expected.setExists(currentValue != null); if ( currentValue != null ) expected.setValue(currentValue); expectedValues.put(attributeName, expected); break; } } } db.deleteItem(applyUserAgent(new DeleteItemRequest().withKey(objectKey).withTableName(tableName).withExpected(expectedValues))); } | /**
* Deletes the given object from its DynamoDB table.
*
* @param config
* Config override object. If {@link SaveBehavior#CLOBBER} is
* supplied, version fields will not be considered when deleting
* the object.
*/ | Deletes the given object from its DynamoDB table | delete | {
"repo_name": "XidongHuang/aws-sdk-for-java",
"path": "src/main/java/com/amazonaws/services/dynamodb/datamodeling/DynamoDBMapper.java",
"license": "apache-2.0",
"size": 54208
} | [
"com.amazonaws.services.dynamodb.datamodeling.DynamoDBMapperConfig",
"com.amazonaws.services.dynamodb.model.AttributeValue",
"com.amazonaws.services.dynamodb.model.DeleteItemRequest",
"com.amazonaws.services.dynamodb.model.ExpectedAttributeValue",
"com.amazonaws.services.dynamodb.model.Key",
"java.lang.re... | import com.amazonaws.services.dynamodb.datamodeling.DynamoDBMapperConfig; import com.amazonaws.services.dynamodb.model.AttributeValue; import com.amazonaws.services.dynamodb.model.DeleteItemRequest; import com.amazonaws.services.dynamodb.model.ExpectedAttributeValue; import com.amazonaws.services.dynamodb.model.Key; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; | import com.amazonaws.services.dynamodb.datamodeling.*; import com.amazonaws.services.dynamodb.model.*; import java.lang.reflect.*; import java.util.*; | [
"com.amazonaws.services",
"java.lang",
"java.util"
] | com.amazonaws.services; java.lang; java.util; | 867,422 |
public BBContainer getContainerNoFlip() {
assert(m_pool == null);
assert(isDirect == true);
assert(buffer.b.isDirect());
return buffer;
} | BBContainer function() { assert(m_pool == null); assert(isDirect == true); assert(buffer.b.isDirect()); return buffer; } | /**
* When a fast serializer is shared between Java and native
* this is called to retrieve a reference to the to buffer without
* flipping it. OnBufferGrowCallback needs this to update the pointer
* to the shared buffer when the parameter buffer grows.
*/ | When a fast serializer is shared between Java and native this is called to retrieve a reference to the to buffer without flipping it. OnBufferGrowCallback needs this to update the pointer to the shared buffer when the parameter buffer grows | getContainerNoFlip | {
"repo_name": "malin1993ml/h-store",
"path": "src/frontend/org/voltdb/messaging/FastSerializer.java",
"license": "gpl-3.0",
"size": 18532
} | [
"org.voltdb.utils.DBBPool"
] | import org.voltdb.utils.DBBPool; | import org.voltdb.utils.*; | [
"org.voltdb.utils"
] | org.voltdb.utils; | 203,436 |
private void createTable(Connection conn, String table) throws SQLException {
// only primary-key columns can be marked non-null
String ddl =
"create table if not exists " + table + "( " +
TRACE.columnName + " bigint not null, " +
PARENT.columnName + " bigint not null, " +
SPAN.columnName + " bigint not null, " +
DESCRIPTION.columnName + " varchar, " +
START.columnName + " bigint, " +
END.columnName + " bigint, " +
HOSTNAME.columnName + " varchar, " +
TAG_COUNT + " smallint, " +
ANNOTATION_COUNT + " smallint" +
" CONSTRAINT pk PRIMARY KEY (" + TRACE.columnName + ", "
+ PARENT.columnName + ", " + SPAN.columnName + "))\n" +
// We have a config parameter that can be set so that tables are
// transactional by default. If that's set, we still don't want these system
// tables created as transactional tables, make these table non
// transactional
PhoenixDatabaseMetaData.TRANSACTIONAL + "=" + Boolean.FALSE;
;
PreparedStatement stmt = conn.prepareStatement(ddl);
stmt.execute();
this.table = table;
} | void function(Connection conn, String table) throws SQLException { String ddl = STR + table + STR + TRACE.columnName + STR + PARENT.columnName + STR + SPAN.columnName + STR + DESCRIPTION.columnName + STR + START.columnName + STR + END.columnName + STR + HOSTNAME.columnName + STR + TAG_COUNT + STR + ANNOTATION_COUNT + STR + STR + TRACE.columnName + STR + PARENT.columnName + STR + SPAN.columnName + "))\n" + PhoenixDatabaseMetaData.TRANSACTIONAL + "=" + Boolean.FALSE; ; PreparedStatement stmt = conn.prepareStatement(ddl); stmt.execute(); this.table = table; } | /**
* Create a stats table with the given name. Stores the name for use later when creating upsert
* statements
*
* @param conn connection to use when creating the table
* @param table name of the table to create
* @throws SQLException if any phoenix operations fails
*/ | Create a stats table with the given name. Stores the name for use later when creating upsert statements | createTable | {
"repo_name": "RCheungIT/phoenix",
"path": "phoenix-core/src/main/java/org/apache/phoenix/trace/PhoenixMetricsSink.java",
"license": "apache-2.0",
"size": 12253
} | [
"java.sql.Connection",
"java.sql.PreparedStatement",
"java.sql.SQLException",
"org.apache.phoenix.jdbc.PhoenixDatabaseMetaData"
] | import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData; | import java.sql.*; import org.apache.phoenix.jdbc.*; | [
"java.sql",
"org.apache.phoenix"
] | java.sql; org.apache.phoenix; | 2,063,125 |
public ConnectionQueryServices getChildQueryServices(ImmutableBytesWritable tenantId); | ConnectionQueryServices function(ImmutableBytesWritable tenantId); | /**
* Get (and create if necessary) a child QueryService for a given tenantId.
* The QueryService will be cached for the lifetime of the parent QueryService
* @param tenantId the organization ID
* @return the child QueryService
*/ | Get (and create if necessary) a child QueryService for a given tenantId. The QueryService will be cached for the lifetime of the parent QueryService | getChildQueryServices | {
"repo_name": "apurtell/phoenix",
"path": "phoenix-core/src/main/java/org/apache/phoenix/query/ConnectionQueryServices.java",
"license": "apache-2.0",
"size": 9894
} | [
"org.apache.hadoop.hbase.io.ImmutableBytesWritable"
] | import org.apache.hadoop.hbase.io.ImmutableBytesWritable; | import org.apache.hadoop.hbase.io.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 769,138 |
public static Element createPolicySetElement(PolicySetElementDTO policyElementDTO, Document doc)
throws PolicyBuilderException {
Element policyElement = doc.createElement(PolicyConstants.POLICY_SET_ELEMENT);
policyElement.setAttribute("xmlns", PolicyConstants.XACMLData.XACML3_POLICY_NAMESPACE);
if(policyElementDTO.getPolicySetId() != null &&
policyElementDTO.getPolicySetId().trim().length() > 0) {
policyElement.setAttribute(PolicyConstants.POLICY_SET_ID, policyElementDTO.
getPolicySetId());
} else {
throw new PolicyBuilderException("Policy name can not be null");
}
if(policyElementDTO.getPolicyCombiningAlgId() != null && policyElementDTO.
getPolicyCombiningAlgId().trim().length() > 0) {
policyElement.setAttribute(PolicyConstants.POLICY_ALGORITHM, policyElementDTO.
getPolicyCombiningAlgId());
} else {
policyElement.setAttribute(PolicyConstants.POLICY_ALGORITHM,
PolicyConstants.PolicyCombiningAlog.DENY_OVERRIDE_ID); // TODO
log.warn("Rule combining algorithm is not defined. Use default algorithm; Deny Override");
}
if(policyElementDTO.getVersion() != null && policyElementDTO.getVersion().trim().length() > 0){
policyElement.setAttribute(PolicyConstants.POLICY_VERSION,
policyElementDTO.getVersion());
} else {
// policy version is can be handled by policy registry. therefore we can ignore it, although it
// is a required attribute
policyElement.setAttribute(PolicyConstants.POLICY_VERSION, "1.0");
}
if(policyElementDTO.getDescription() != null && policyElementDTO.
getDescription().trim().length() > 0) {
Element descriptionElement = doc.createElement(PolicyConstants.
DESCRIPTION_ELEMENT);
descriptionElement.setTextContent(policyElementDTO.getDescription());
policyElement.appendChild(descriptionElement);
}
TargetElementDTO targetElementDTO = policyElementDTO.getTargetElementDTO();
List<ObligationElementDTO> obligationElementDTOs = policyElementDTO.getObligationElementDTOs();
if(targetElementDTO != null){
policyElement.appendChild(createTargetElement(targetElementDTO, doc));
} else {
policyElement.appendChild(doc.createElement(PolicyConstants.TARGET_ELEMENT));
}
List<String> policySets = policyElementDTO.getPolicySets();
if(policySets != null && policySets.size() > 0){
// TODO
}
List<String> policies = policyElementDTO.getPolicies();
if(policies != null && policies.size() > 0){
// TODO
}
List<String> policySetIds = policyElementDTO.getPolicySetIdReferences();
if(policySetIds != null && policySetIds.size() > 0){
for(String policySetId : policySetIds){
Element element = doc.createElement(PolicyConstants.POLICY_SET_ID_REFERENCE_ELEMENT);
element.setTextContent(policySetId);
policyElement.appendChild(element);
}
}
List<String> policyIds = policyElementDTO.getPolicyIdReferences();
if(policyIds != null && policyIds.size() > 0){
for(String policyId : policyIds){
Element element = doc.createElement(PolicyConstants.POLICY_ID_REFERENCE_ELEMENT);
element.setTextContent(policyId);
policyElement.appendChild(element);
}
}
if(obligationElementDTOs != null && obligationElementDTOs.size() > 0){
List<ObligationElementDTO> obligations = new ArrayList<ObligationElementDTO>();
List<ObligationElementDTO> advices = new ArrayList<ObligationElementDTO>();
for(ObligationElementDTO obligationElementDTO : obligationElementDTOs){
if(obligationElementDTO.getType() == ObligationElementDTO.ADVICE){
advices.add(obligationElementDTO);
} else {
obligations.add(obligationElementDTO);
}
}
Element obligation = createObligationsElement(obligations, doc);
Element advice = createAdvicesElement(advices, doc);
if(obligation != null){
policyElement.appendChild(obligation);
}
if(advice != null){
policyElement.appendChild(advice);
}
}
return policyElement;
} | static Element function(PolicySetElementDTO policyElementDTO, Document doc) throws PolicyBuilderException { Element policyElement = doc.createElement(PolicyConstants.POLICY_SET_ELEMENT); policyElement.setAttribute("xmlns", PolicyConstants.XACMLData.XACML3_POLICY_NAMESPACE); if(policyElementDTO.getPolicySetId() != null && policyElementDTO.getPolicySetId().trim().length() > 0) { policyElement.setAttribute(PolicyConstants.POLICY_SET_ID, policyElementDTO. getPolicySetId()); } else { throw new PolicyBuilderException(STR); } if(policyElementDTO.getPolicyCombiningAlgId() != null && policyElementDTO. getPolicyCombiningAlgId().trim().length() > 0) { policyElement.setAttribute(PolicyConstants.POLICY_ALGORITHM, policyElementDTO. getPolicyCombiningAlgId()); } else { policyElement.setAttribute(PolicyConstants.POLICY_ALGORITHM, PolicyConstants.PolicyCombiningAlog.DENY_OVERRIDE_ID); log.warn(STR); } if(policyElementDTO.getVersion() != null && policyElementDTO.getVersion().trim().length() > 0){ policyElement.setAttribute(PolicyConstants.POLICY_VERSION, policyElementDTO.getVersion()); } else { policyElement.setAttribute(PolicyConstants.POLICY_VERSION, "1.0"); } if(policyElementDTO.getDescription() != null && policyElementDTO. getDescription().trim().length() > 0) { Element descriptionElement = doc.createElement(PolicyConstants. DESCRIPTION_ELEMENT); descriptionElement.setTextContent(policyElementDTO.getDescription()); policyElement.appendChild(descriptionElement); } TargetElementDTO targetElementDTO = policyElementDTO.getTargetElementDTO(); List<ObligationElementDTO> obligationElementDTOs = policyElementDTO.getObligationElementDTOs(); if(targetElementDTO != null){ policyElement.appendChild(createTargetElement(targetElementDTO, doc)); } else { policyElement.appendChild(doc.createElement(PolicyConstants.TARGET_ELEMENT)); } List<String> policySets = policyElementDTO.getPolicySets(); if(policySets != null && policySets.size() > 0){ } List<String> policies = policyElementDTO.getPolicies(); if(policies != null && policies.size() > 0){ } List<String> policySetIds = policyElementDTO.getPolicySetIdReferences(); if(policySetIds != null && policySetIds.size() > 0){ for(String policySetId : policySetIds){ Element element = doc.createElement(PolicyConstants.POLICY_SET_ID_REFERENCE_ELEMENT); element.setTextContent(policySetId); policyElement.appendChild(element); } } List<String> policyIds = policyElementDTO.getPolicyIdReferences(); if(policyIds != null && policyIds.size() > 0){ for(String policyId : policyIds){ Element element = doc.createElement(PolicyConstants.POLICY_ID_REFERENCE_ELEMENT); element.setTextContent(policyId); policyElement.appendChild(element); } } if(obligationElementDTOs != null && obligationElementDTOs.size() > 0){ List<ObligationElementDTO> obligations = new ArrayList<ObligationElementDTO>(); List<ObligationElementDTO> advices = new ArrayList<ObligationElementDTO>(); for(ObligationElementDTO obligationElementDTO : obligationElementDTOs){ if(obligationElementDTO.getType() == ObligationElementDTO.ADVICE){ advices.add(obligationElementDTO); } else { obligations.add(obligationElementDTO); } } Element obligation = createObligationsElement(obligations, doc); Element advice = createAdvicesElement(advices, doc); if(obligation != null){ policyElement.appendChild(obligation); } if(advice != null){ policyElement.appendChild(advice); } } return policyElement; } | /**
* This method creates a policy set element of the XACML policy
* @param policyElementDTO policy element data object
* @param doc XML document
* @return policyElement
* @throws PolicyBuilderException if
*/ | This method creates a policy set element of the XACML policy | createPolicySetElement | {
"repo_name": "shaundmorris/arbitro",
"path": "modules/arbitro-utils/src/main/java/com/connexta/arbitro/utils/PolicyUtils.java",
"license": "apache-2.0",
"size": 39198
} | [
"com.connexta.arbitro.utils.Constants",
"com.connexta.arbitro.utils.exception.PolicyBuilderException",
"com.connexta.arbitro.utils.policy.dto.ObligationElementDTO",
"com.connexta.arbitro.utils.policy.dto.PolicySetElementDTO",
"com.connexta.arbitro.utils.policy.dto.TargetElementDTO",
"java.util.ArrayList",... | import com.connexta.arbitro.utils.Constants; import com.connexta.arbitro.utils.exception.PolicyBuilderException; import com.connexta.arbitro.utils.policy.dto.ObligationElementDTO; import com.connexta.arbitro.utils.policy.dto.PolicySetElementDTO; import com.connexta.arbitro.utils.policy.dto.TargetElementDTO; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; | import com.connexta.arbitro.utils.*; import com.connexta.arbitro.utils.exception.*; import com.connexta.arbitro.utils.policy.dto.*; import java.util.*; import org.w3c.dom.*; | [
"com.connexta.arbitro",
"java.util",
"org.w3c.dom"
] | com.connexta.arbitro; java.util; org.w3c.dom; | 654,827 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.