repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UCaseProps.java | UCaseProps.getSlotValueAndOffset | private final long getSlotValueAndOffset(int excWord, int index, int excOffset) {
"""
/*
Get the value of an optional-value slot where hasSlot(excWord, index).
@param excWord (in) initial exceptions word
@param index (in) desired slot index
@param excOffset (in) offset into exceptions[] after excWord=exceptions.charAt(excOffset++);
@return bits 31..0: slot value
63..32: modified excOffset, moved to the last char of the value, use +1 for beginning of next slot
"""
long value;
if((excWord&EXC_DOUBLE_SLOTS)==0) {
excOffset+=slotOffset(excWord, index);
value=exceptions.charAt(excOffset);
} else {
excOffset+=2*slotOffset(excWord, index);
value=exceptions.charAt(excOffset++);
value=(value<<16)|exceptions.charAt(excOffset);
}
return value |((long)excOffset<<32);
} | java | private final long getSlotValueAndOffset(int excWord, int index, int excOffset) {
long value;
if((excWord&EXC_DOUBLE_SLOTS)==0) {
excOffset+=slotOffset(excWord, index);
value=exceptions.charAt(excOffset);
} else {
excOffset+=2*slotOffset(excWord, index);
value=exceptions.charAt(excOffset++);
value=(value<<16)|exceptions.charAt(excOffset);
}
return value |((long)excOffset<<32);
} | [
"private",
"final",
"long",
"getSlotValueAndOffset",
"(",
"int",
"excWord",
",",
"int",
"index",
",",
"int",
"excOffset",
")",
"{",
"long",
"value",
";",
"if",
"(",
"(",
"excWord",
"&",
"EXC_DOUBLE_SLOTS",
")",
"==",
"0",
")",
"{",
"excOffset",
"+=",
"sl... | /*
Get the value of an optional-value slot where hasSlot(excWord, index).
@param excWord (in) initial exceptions word
@param index (in) desired slot index
@param excOffset (in) offset into exceptions[] after excWord=exceptions.charAt(excOffset++);
@return bits 31..0: slot value
63..32: modified excOffset, moved to the last char of the value, use +1 for beginning of next slot | [
"/",
"*",
"Get",
"the",
"value",
"of",
"an",
"optional",
"-",
"value",
"slot",
"where",
"hasSlot",
"(",
"excWord",
"index",
")",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/UCaseProps.java#L162-L173 |
PrashamTrivedi/SharedPreferenceInspector | sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java | SharedPreferenceUtils.putFloat | public void putFloat(String key, float value) {
"""
put the float value to shared preference
@param key
the name of the preference to save
@param value
the name of the preference to modify.
@see android.content.SharedPreferences#edit()#putFloat(String, float)
"""
sharedPreferences.edit().putFloat(key, value).commit();
} | java | public void putFloat(String key, float value) {
sharedPreferences.edit().putFloat(key, value).commit();
} | [
"public",
"void",
"putFloat",
"(",
"String",
"key",
",",
"float",
"value",
")",
"{",
"sharedPreferences",
".",
"edit",
"(",
")",
".",
"putFloat",
"(",
"key",
",",
"value",
")",
".",
"commit",
"(",
")",
";",
"}"
] | put the float value to shared preference
@param key
the name of the preference to save
@param value
the name of the preference to modify.
@see android.content.SharedPreferences#edit()#putFloat(String, float) | [
"put",
"the",
"float",
"value",
"to",
"shared",
"preference"
] | train | https://github.com/PrashamTrivedi/SharedPreferenceInspector/blob/c04d567c4d0fc5e0f8cda308ca85df19c6b3b838/sharedpreferenceinspector/src/main/java/com/ceelites/sharedpreferenceinspector/Utils/SharedPreferenceUtils.java#L460-L462 |
RestComm/media-core | ice/src/main/java/org/restcomm/media/core/ice/harvest/HostCandidateHarvester.java | HostCandidateHarvester.getNetworkInterfaces | private Enumeration<NetworkInterface> getNetworkInterfaces() throws HarvestException {
"""
Finds all Network interfaces available on this server.
@return The list of available network interfaces.
@throws HarvestException
When an error occurs while retrieving the network interfaces
"""
try {
return NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
throw new HarvestException("Could not retrieve list of available Network Interfaces.", e);
}
} | java | private Enumeration<NetworkInterface> getNetworkInterfaces() throws HarvestException {
try {
return NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
throw new HarvestException("Could not retrieve list of available Network Interfaces.", e);
}
} | [
"private",
"Enumeration",
"<",
"NetworkInterface",
">",
"getNetworkInterfaces",
"(",
")",
"throws",
"HarvestException",
"{",
"try",
"{",
"return",
"NetworkInterface",
".",
"getNetworkInterfaces",
"(",
")",
";",
"}",
"catch",
"(",
"SocketException",
"e",
")",
"{",
... | Finds all Network interfaces available on this server.
@return The list of available network interfaces.
@throws HarvestException
When an error occurs while retrieving the network interfaces | [
"Finds",
"all",
"Network",
"interfaces",
"available",
"on",
"this",
"server",
"."
] | train | https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/ice/src/main/java/org/restcomm/media/core/ice/harvest/HostCandidateHarvester.java#L71-L77 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/charset/CharsetHelper.java | CharsetHelper.getInputStreamAndCharsetFromBOM | @Nonnull
public static InputStreamAndCharset getInputStreamAndCharsetFromBOM (@Nonnull @WillNotClose final InputStream aIS) {
"""
If a BOM is present in the {@link InputStream} it is read and if possible
the charset is automatically determined from the BOM.
@param aIS
The input stream to use. May not be <code>null</code>.
@return Never <code>null</code>. Always use the input stream contained in
the returned object and never the one passed in as a parameter,
because the returned IS is a push-back InputStream that has a
couple of bytes already buffered!
"""
ValueEnforcer.notNull (aIS, "InputStream");
// Check for BOM
final int nMaxBOMBytes = EUnicodeBOM.getMaximumByteCount ();
@WillNotClose
final NonBlockingPushbackInputStream aPIS = new NonBlockingPushbackInputStream (StreamHelper.getBuffered (aIS),
nMaxBOMBytes);
try
{
// Try to read as many bytes as necessary to determine all supported BOMs
final byte [] aBOM = new byte [nMaxBOMBytes];
final int nReadBOMBytes = aPIS.read (aBOM);
EUnicodeBOM eBOM = null;
Charset aDeterminedCharset = null;
if (nReadBOMBytes > 0)
{
// Some byte BOMs were read - determine
eBOM = EUnicodeBOM.getFromBytesOrNull (ArrayHelper.getCopy (aBOM, 0, nReadBOMBytes));
if (eBOM == null)
{
// Unread the whole BOM
aPIS.unread (aBOM, 0, nReadBOMBytes);
// aDeterminedCharset stays null
}
else
{
if (LOGGER.isDebugEnabled ())
LOGGER.debug ("Found " + eBOM + " on " + aIS.getClass ().getName ());
// Unread the unnecessary parts of the BOM
final int nBOMBytes = eBOM.getByteCount ();
if (nBOMBytes < nReadBOMBytes)
aPIS.unread (aBOM, nBOMBytes, nReadBOMBytes - nBOMBytes);
// Use the Charset of the BOM - maybe null!
aDeterminedCharset = eBOM.getCharset ();
}
}
return new InputStreamAndCharset (aPIS, eBOM, aDeterminedCharset);
}
catch (final IOException ex)
{
LOGGER.error ("Failed to determine BOM", ex);
StreamHelper.close (aPIS);
throw new UncheckedIOException (ex);
}
} | java | @Nonnull
public static InputStreamAndCharset getInputStreamAndCharsetFromBOM (@Nonnull @WillNotClose final InputStream aIS)
{
ValueEnforcer.notNull (aIS, "InputStream");
// Check for BOM
final int nMaxBOMBytes = EUnicodeBOM.getMaximumByteCount ();
@WillNotClose
final NonBlockingPushbackInputStream aPIS = new NonBlockingPushbackInputStream (StreamHelper.getBuffered (aIS),
nMaxBOMBytes);
try
{
// Try to read as many bytes as necessary to determine all supported BOMs
final byte [] aBOM = new byte [nMaxBOMBytes];
final int nReadBOMBytes = aPIS.read (aBOM);
EUnicodeBOM eBOM = null;
Charset aDeterminedCharset = null;
if (nReadBOMBytes > 0)
{
// Some byte BOMs were read - determine
eBOM = EUnicodeBOM.getFromBytesOrNull (ArrayHelper.getCopy (aBOM, 0, nReadBOMBytes));
if (eBOM == null)
{
// Unread the whole BOM
aPIS.unread (aBOM, 0, nReadBOMBytes);
// aDeterminedCharset stays null
}
else
{
if (LOGGER.isDebugEnabled ())
LOGGER.debug ("Found " + eBOM + " on " + aIS.getClass ().getName ());
// Unread the unnecessary parts of the BOM
final int nBOMBytes = eBOM.getByteCount ();
if (nBOMBytes < nReadBOMBytes)
aPIS.unread (aBOM, nBOMBytes, nReadBOMBytes - nBOMBytes);
// Use the Charset of the BOM - maybe null!
aDeterminedCharset = eBOM.getCharset ();
}
}
return new InputStreamAndCharset (aPIS, eBOM, aDeterminedCharset);
}
catch (final IOException ex)
{
LOGGER.error ("Failed to determine BOM", ex);
StreamHelper.close (aPIS);
throw new UncheckedIOException (ex);
}
} | [
"@",
"Nonnull",
"public",
"static",
"InputStreamAndCharset",
"getInputStreamAndCharsetFromBOM",
"(",
"@",
"Nonnull",
"@",
"WillNotClose",
"final",
"InputStream",
"aIS",
")",
"{",
"ValueEnforcer",
".",
"notNull",
"(",
"aIS",
",",
"\"InputStream\"",
")",
";",
"// Chec... | If a BOM is present in the {@link InputStream} it is read and if possible
the charset is automatically determined from the BOM.
@param aIS
The input stream to use. May not be <code>null</code>.
@return Never <code>null</code>. Always use the input stream contained in
the returned object and never the one passed in as a parameter,
because the returned IS is a push-back InputStream that has a
couple of bytes already buffered! | [
"If",
"a",
"BOM",
"is",
"present",
"in",
"the",
"{",
"@link",
"InputStream",
"}",
"it",
"is",
"read",
"and",
"if",
"possible",
"the",
"charset",
"is",
"automatically",
"determined",
"from",
"the",
"BOM",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/charset/CharsetHelper.java#L310-L359 |
hal/core | gui/src/main/java/org/jboss/as/console/client/widgets/forms/AddressBinding.java | AddressBinding.asResource | public ModelNode asResource(ModelNode baseAddress, String... args) {
"""
Turns this address into a ModelNode with an address property.<br/>
This method allows to specify a base address prefix (i.e server vs. domain addressing).
@param baseAddress
@param args parameters for address wildcards
@return a ModelNode with an address property
"""
assert getNumWildCards() ==args.length :
"Address arguments don't match number of wildcards: "+getNumWildCards()+" -> "+ Arrays.toString(args);
ModelNode model = new ModelNode();
model.get(ADDRESS).set(baseAddress);
int argsCounter = 0;
for(String[] tuple : address)
{
String parent = tuple[0];
String child = tuple[1];
if(parent.startsWith("{"))
{
parent = args[argsCounter];
argsCounter++;
}
if(child.startsWith("{"))
{
child = args[argsCounter];
argsCounter++;
}
model.get(ADDRESS).add(parent, child);
}
return model;
} | java | public ModelNode asResource(ModelNode baseAddress, String... args) {
assert getNumWildCards() ==args.length :
"Address arguments don't match number of wildcards: "+getNumWildCards()+" -> "+ Arrays.toString(args);
ModelNode model = new ModelNode();
model.get(ADDRESS).set(baseAddress);
int argsCounter = 0;
for(String[] tuple : address)
{
String parent = tuple[0];
String child = tuple[1];
if(parent.startsWith("{"))
{
parent = args[argsCounter];
argsCounter++;
}
if(child.startsWith("{"))
{
child = args[argsCounter];
argsCounter++;
}
model.get(ADDRESS).add(parent, child);
}
return model;
} | [
"public",
"ModelNode",
"asResource",
"(",
"ModelNode",
"baseAddress",
",",
"String",
"...",
"args",
")",
"{",
"assert",
"getNumWildCards",
"(",
")",
"==",
"args",
".",
"length",
":",
"\"Address arguments don't match number of wildcards: \"",
"+",
"getNumWildCards",
"(... | Turns this address into a ModelNode with an address property.<br/>
This method allows to specify a base address prefix (i.e server vs. domain addressing).
@param baseAddress
@param args parameters for address wildcards
@return a ModelNode with an address property | [
"Turns",
"this",
"address",
"into",
"a",
"ModelNode",
"with",
"an",
"address",
"property",
".",
"<br",
"/",
">",
"This",
"method",
"allows",
"to",
"specify",
"a",
"base",
"address",
"prefix",
"(",
"i",
".",
"e",
"server",
"vs",
".",
"domain",
"addressing... | train | https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/jboss/as/console/client/widgets/forms/AddressBinding.java#L80-L110 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.deleteHistoricalVersions | public void deleteHistoricalVersions(int versionsToKeep, int versionsDeleted, long timeDeleted, I_CmsReport report)
throws CmsException {
"""
Deletes the versions from the history tables, keeping the given number of versions per resource.<p>
@param versionsToKeep number of versions to keep, is ignored if negative
@param versionsDeleted number of versions to keep for deleted resources, is ignored if negative
@param timeDeleted deleted resources older than this will also be deleted, is ignored if negative
@param report the report for output logging
@throws CmsException if operation was not successful
"""
m_securityManager.deleteHistoricalVersions(m_context, versionsToKeep, versionsDeleted, timeDeleted, report);
} | java | public void deleteHistoricalVersions(int versionsToKeep, int versionsDeleted, long timeDeleted, I_CmsReport report)
throws CmsException {
m_securityManager.deleteHistoricalVersions(m_context, versionsToKeep, versionsDeleted, timeDeleted, report);
} | [
"public",
"void",
"deleteHistoricalVersions",
"(",
"int",
"versionsToKeep",
",",
"int",
"versionsDeleted",
",",
"long",
"timeDeleted",
",",
"I_CmsReport",
"report",
")",
"throws",
"CmsException",
"{",
"m_securityManager",
".",
"deleteHistoricalVersions",
"(",
"m_context... | Deletes the versions from the history tables, keeping the given number of versions per resource.<p>
@param versionsToKeep number of versions to keep, is ignored if negative
@param versionsDeleted number of versions to keep for deleted resources, is ignored if negative
@param timeDeleted deleted resources older than this will also be deleted, is ignored if negative
@param report the report for output logging
@throws CmsException if operation was not successful | [
"Deletes",
"the",
"versions",
"from",
"the",
"history",
"tables",
"keeping",
"the",
"given",
"number",
"of",
"versions",
"per",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L952-L956 |
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/map/AbstractIntDoubleMap.java | AbstractIntDoubleMap.assign | public void assign(AbstractIntDoubleMap other) {
"""
Clears the receiver, then adds all (key,value) pairs of <tt>other</tt>values to it.
@param other the other map to be copied into the receiver.
"""
clear();
other.forEachPair(
new IntDoubleProcedure() {
public boolean apply(int key, double value) {
put(key,value);
return true;
}
}
);
} | java | public void assign(AbstractIntDoubleMap other) {
clear();
other.forEachPair(
new IntDoubleProcedure() {
public boolean apply(int key, double value) {
put(key,value);
return true;
}
}
);
} | [
"public",
"void",
"assign",
"(",
"AbstractIntDoubleMap",
"other",
")",
"{",
"clear",
"(",
")",
";",
"other",
".",
"forEachPair",
"(",
"new",
"IntDoubleProcedure",
"(",
")",
"{",
"public",
"boolean",
"apply",
"(",
"int",
"key",
",",
"double",
"value",
")",
... | Clears the receiver, then adds all (key,value) pairs of <tt>other</tt>values to it.
@param other the other map to be copied into the receiver. | [
"Clears",
"the",
"receiver",
"then",
"adds",
"all",
"(",
"key",
"value",
")",
"pairs",
"of",
"<tt",
">",
"other<",
"/",
"tt",
">",
"values",
"to",
"it",
"."
] | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/map/AbstractIntDoubleMap.java#L54-L64 |
forge/furnace | se/src/main/java/org/jboss/forge/furnace/se/FurnaceFactory.java | FurnaceFactory.getInstance | public static Furnace getInstance(final ClassLoader clientLoader, final ClassLoader furnaceLoader) {
"""
Produce a {@link Furnace} instance using the first given {@link ClassLoader} to act as the client for which
{@link Class} instances should be translated across {@link ClassLoader} boundaries, and the second given
{@link ClassLoader} to load core furnace implementation classes.
"""
try
{
Class<?> furnaceType = furnaceLoader.loadClass("org.jboss.forge.furnace.impl.FurnaceImpl");
final Object instance = furnaceType.newInstance();
final Furnace furnace = (Furnace) ClassLoaderAdapterBuilder
.callingLoader(clientLoader)
.delegateLoader(furnaceLoader)
.enhance(instance, Furnace.class);
Callable<Set<ClassLoader>> whitelistCallback = new Callable<Set<ClassLoader>>()
{
volatile long lastRegistryVersion = -1;
final Set<ClassLoader> result = Sets.getConcurrentSet();
@Override
public Set<ClassLoader> call() throws Exception
{
if (furnace.getStatus().isStarted())
{
long registryVersion = furnace.getAddonRegistry().getVersion();
if (registryVersion != lastRegistryVersion)
{
result.clear();
lastRegistryVersion = registryVersion;
for (Addon addon : furnace.getAddonRegistry().getAddons())
{
ClassLoader classLoader = addon.getClassLoader();
if (classLoader != null)
result.add(classLoader);
}
}
}
return result;
}
};
return (Furnace) ClassLoaderAdapterBuilder
.callingLoader(clientLoader)
.delegateLoader(furnaceLoader)
.whitelist(whitelistCallback)
.enhance(instance, Furnace.class);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | java | public static Furnace getInstance(final ClassLoader clientLoader, final ClassLoader furnaceLoader)
{
try
{
Class<?> furnaceType = furnaceLoader.loadClass("org.jboss.forge.furnace.impl.FurnaceImpl");
final Object instance = furnaceType.newInstance();
final Furnace furnace = (Furnace) ClassLoaderAdapterBuilder
.callingLoader(clientLoader)
.delegateLoader(furnaceLoader)
.enhance(instance, Furnace.class);
Callable<Set<ClassLoader>> whitelistCallback = new Callable<Set<ClassLoader>>()
{
volatile long lastRegistryVersion = -1;
final Set<ClassLoader> result = Sets.getConcurrentSet();
@Override
public Set<ClassLoader> call() throws Exception
{
if (furnace.getStatus().isStarted())
{
long registryVersion = furnace.getAddonRegistry().getVersion();
if (registryVersion != lastRegistryVersion)
{
result.clear();
lastRegistryVersion = registryVersion;
for (Addon addon : furnace.getAddonRegistry().getAddons())
{
ClassLoader classLoader = addon.getClassLoader();
if (classLoader != null)
result.add(classLoader);
}
}
}
return result;
}
};
return (Furnace) ClassLoaderAdapterBuilder
.callingLoader(clientLoader)
.delegateLoader(furnaceLoader)
.whitelist(whitelistCallback)
.enhance(instance, Furnace.class);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
} | [
"public",
"static",
"Furnace",
"getInstance",
"(",
"final",
"ClassLoader",
"clientLoader",
",",
"final",
"ClassLoader",
"furnaceLoader",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
">",
"furnaceType",
"=",
"furnaceLoader",
".",
"loadClass",
"(",
"\"org.jboss.forge.fu... | Produce a {@link Furnace} instance using the first given {@link ClassLoader} to act as the client for which
{@link Class} instances should be translated across {@link ClassLoader} boundaries, and the second given
{@link ClassLoader} to load core furnace implementation classes. | [
"Produce",
"a",
"{"
] | train | https://github.com/forge/furnace/blob/bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a/se/src/main/java/org/jboss/forge/furnace/se/FurnaceFactory.java#L58-L108 |
fommil/matrix-toolkits-java | src/main/java/no/uib/cipr/matrix/io/MatrixVectorWriter.java | MatrixVectorWriter.printArray | public void printArray(float[] dataR, float[] dataI) {
"""
Prints an array to the underlying stream. One entry per line. The first
array specifies the real entries, and the second is the imaginary entries
"""
int size = dataR.length;
if (size != dataI.length)
throw new IllegalArgumentException(
"All arrays must be of the same size");
for (int i = 0; i < size; ++i)
format(Locale.ENGLISH, "% .12e % .12e%n", dataR[i], dataI[i]);
} | java | public void printArray(float[] dataR, float[] dataI) {
int size = dataR.length;
if (size != dataI.length)
throw new IllegalArgumentException(
"All arrays must be of the same size");
for (int i = 0; i < size; ++i)
format(Locale.ENGLISH, "% .12e % .12e%n", dataR[i], dataI[i]);
} | [
"public",
"void",
"printArray",
"(",
"float",
"[",
"]",
"dataR",
",",
"float",
"[",
"]",
"dataI",
")",
"{",
"int",
"size",
"=",
"dataR",
".",
"length",
";",
"if",
"(",
"size",
"!=",
"dataI",
".",
"length",
")",
"throw",
"new",
"IllegalArgumentException... | Prints an array to the underlying stream. One entry per line. The first
array specifies the real entries, and the second is the imaginary entries | [
"Prints",
"an",
"array",
"to",
"the",
"underlying",
"stream",
".",
"One",
"entry",
"per",
"line",
".",
"The",
"first",
"array",
"specifies",
"the",
"real",
"entries",
"and",
"the",
"second",
"is",
"the",
"imaginary",
"entries"
] | train | https://github.com/fommil/matrix-toolkits-java/blob/6157618bc86bcda3749af2a60bf869d8f3292960/src/main/java/no/uib/cipr/matrix/io/MatrixVectorWriter.java#L154-L161 |
atomix/atomix | protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/AntiEntropyMapDelegate.java | AntiEntropyMapDelegate.antiEntropyCheckLocalItems | private List<MapDelegateEvent<K, V>> antiEntropyCheckLocalItems(AntiEntropyAdvertisement ad) {
"""
Processes anti-entropy ad from peer by taking following actions: 1. If peer has an old entry, updates peer. 2. If
peer indicates an entry is removed and has a more recent timestamp than the local entry, update local state.
"""
final List<MapDelegateEvent<K, V>> externalEvents = Lists.newLinkedList();
final MemberId sender = ad.sender();
final List<MemberId> peers = ImmutableList.of(sender);
Set<String> staleOrMissing = new HashSet<>();
Set<String> locallyUnknown = new HashSet<>(ad.digest().keySet());
items.forEach((key, localValue) -> {
locallyUnknown.remove(key);
MapValue.Digest remoteValueDigest = ad.digest().get(key);
if (remoteValueDigest == null || localValue.isNewerThan(remoteValueDigest.timestamp())) {
// local value is more recent, push to sender
queueUpdate(new UpdateEntry(key, localValue), peers);
} else if (remoteValueDigest.isNewerThan(localValue.digest()) && remoteValueDigest.isTombstone()) {
// remote value is more recent and a tombstone: update local value
MapValue tombstone = MapValue.tombstone(remoteValueDigest.timestamp());
MapValue previousValue = removeInternal(key,
Optional.empty(),
Optional.of(tombstone));
if (previousValue != null && previousValue.isAlive()) {
externalEvents.add(new MapDelegateEvent<>(REMOVE, decodeKey(key), previousValue.get(this::decodeValue)));
}
} else if (remoteValueDigest.isNewerThan(localValue.digest())) {
// Not a tombstone and remote is newer
staleOrMissing.add(key);
}
});
// Keys missing in local map
staleOrMissing.addAll(locallyUnknown);
// Request updates that we missed out on
sendUpdateRequestToPeer(sender, staleOrMissing);
return externalEvents;
} | java | private List<MapDelegateEvent<K, V>> antiEntropyCheckLocalItems(AntiEntropyAdvertisement ad) {
final List<MapDelegateEvent<K, V>> externalEvents = Lists.newLinkedList();
final MemberId sender = ad.sender();
final List<MemberId> peers = ImmutableList.of(sender);
Set<String> staleOrMissing = new HashSet<>();
Set<String> locallyUnknown = new HashSet<>(ad.digest().keySet());
items.forEach((key, localValue) -> {
locallyUnknown.remove(key);
MapValue.Digest remoteValueDigest = ad.digest().get(key);
if (remoteValueDigest == null || localValue.isNewerThan(remoteValueDigest.timestamp())) {
// local value is more recent, push to sender
queueUpdate(new UpdateEntry(key, localValue), peers);
} else if (remoteValueDigest.isNewerThan(localValue.digest()) && remoteValueDigest.isTombstone()) {
// remote value is more recent and a tombstone: update local value
MapValue tombstone = MapValue.tombstone(remoteValueDigest.timestamp());
MapValue previousValue = removeInternal(key,
Optional.empty(),
Optional.of(tombstone));
if (previousValue != null && previousValue.isAlive()) {
externalEvents.add(new MapDelegateEvent<>(REMOVE, decodeKey(key), previousValue.get(this::decodeValue)));
}
} else if (remoteValueDigest.isNewerThan(localValue.digest())) {
// Not a tombstone and remote is newer
staleOrMissing.add(key);
}
});
// Keys missing in local map
staleOrMissing.addAll(locallyUnknown);
// Request updates that we missed out on
sendUpdateRequestToPeer(sender, staleOrMissing);
return externalEvents;
} | [
"private",
"List",
"<",
"MapDelegateEvent",
"<",
"K",
",",
"V",
">",
">",
"antiEntropyCheckLocalItems",
"(",
"AntiEntropyAdvertisement",
"ad",
")",
"{",
"final",
"List",
"<",
"MapDelegateEvent",
"<",
"K",
",",
"V",
">",
">",
"externalEvents",
"=",
"Lists",
"... | Processes anti-entropy ad from peer by taking following actions: 1. If peer has an old entry, updates peer. 2. If
peer indicates an entry is removed and has a more recent timestamp than the local entry, update local state. | [
"Processes",
"anti",
"-",
"entropy",
"ad",
"from",
"peer",
"by",
"taking",
"following",
"actions",
":",
"1",
".",
"If",
"peer",
"has",
"an",
"old",
"entry",
"updates",
"peer",
".",
"2",
".",
"If",
"peer",
"indicates",
"an",
"entry",
"is",
"removed",
"a... | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/gossip/src/main/java/io/atomix/protocols/gossip/map/AntiEntropyMapDelegate.java#L613-L645 |
PvdBerg1998/PNet | src/main/java/nl/pvdberg/pnet/event/PacketDistributer.java | PacketDistributer.onReceive | public synchronized void onReceive(final Packet packet, final Client client) throws IOException {
"""
Calls specified handler for Packet ID, or the default handler (if set)
@param packet New incoming Packet
"""
if (globalHandler != null) globalHandler.onReceive(packet, client);
final PacketHandler packetHandler = registry.get(packet.getPacketID());
if (packetHandler == null)
{
if (defaultHandler != null) defaultHandler.handlePacket(packet, client);
}
else packetHandler.handlePacket(packet, client);
} | java | public synchronized void onReceive(final Packet packet, final Client client) throws IOException
{
if (globalHandler != null) globalHandler.onReceive(packet, client);
final PacketHandler packetHandler = registry.get(packet.getPacketID());
if (packetHandler == null)
{
if (defaultHandler != null) defaultHandler.handlePacket(packet, client);
}
else packetHandler.handlePacket(packet, client);
} | [
"public",
"synchronized",
"void",
"onReceive",
"(",
"final",
"Packet",
"packet",
",",
"final",
"Client",
"client",
")",
"throws",
"IOException",
"{",
"if",
"(",
"globalHandler",
"!=",
"null",
")",
"globalHandler",
".",
"onReceive",
"(",
"packet",
",",
"client"... | Calls specified handler for Packet ID, or the default handler (if set)
@param packet New incoming Packet | [
"Calls",
"specified",
"handler",
"for",
"Packet",
"ID",
"or",
"the",
"default",
"handler",
"(",
"if",
"set",
")"
] | train | https://github.com/PvdBerg1998/PNet/blob/d3dfff2ceaf69c244e0593e3f7606f171ec718bb/src/main/java/nl/pvdberg/pnet/event/PacketDistributer.java#L52-L62 |
ddf-project/DDF | core/src/main/java/io/ddf/DDF.java | DDF.validateName | private void validateName(String name) throws DDFException {
"""
Also only allow alphanumberic and dash "-" and underscore "_"
"""
Boolean isNameExisted;
try {
this.getManager().getDDFByName(name);
isNameExisted = true;
} catch (DDFException e) {
isNameExisted = false;
}
if(isNameExisted) {
throw new DDFException(String.format("DDF with name %s already exists", name));
}
Pattern p = Pattern.compile("^[a-zA-Z0-9_-]*$");
Matcher m = p.matcher(name);
if(!m.find()) {
throw new DDFException(String.format("Invalid name %s, only allow alphanumeric (uppercase and lowercase a-z, " +
"numbers 0-9) and dash (\"-\") and underscore (\"_\")", name));
}
} | java | private void validateName(String name) throws DDFException {
Boolean isNameExisted;
try {
this.getManager().getDDFByName(name);
isNameExisted = true;
} catch (DDFException e) {
isNameExisted = false;
}
if(isNameExisted) {
throw new DDFException(String.format("DDF with name %s already exists", name));
}
Pattern p = Pattern.compile("^[a-zA-Z0-9_-]*$");
Matcher m = p.matcher(name);
if(!m.find()) {
throw new DDFException(String.format("Invalid name %s, only allow alphanumeric (uppercase and lowercase a-z, " +
"numbers 0-9) and dash (\"-\") and underscore (\"_\")", name));
}
} | [
"private",
"void",
"validateName",
"(",
"String",
"name",
")",
"throws",
"DDFException",
"{",
"Boolean",
"isNameExisted",
";",
"try",
"{",
"this",
".",
"getManager",
"(",
")",
".",
"getDDFByName",
"(",
"name",
")",
";",
"isNameExisted",
"=",
"true",
";",
"... | Also only allow alphanumberic and dash "-" and underscore "_" | [
"Also",
"only",
"allow",
"alphanumberic",
"and",
"dash",
"-",
"and",
"underscore",
"_"
] | train | https://github.com/ddf-project/DDF/blob/e4e68315dcec1ed8b287bf1ee73baa88e7e41eba/core/src/main/java/io/ddf/DDF.java#L241-L259 |
looly/hutool | hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java | ExcelWriter.setRowHeight | public ExcelWriter setRowHeight(int rownum, int height) {
"""
设置行高,值为一个点的高度
@param rownum 行号(从0开始计数,-1表示所有行的默认高度)
@param height 高度
@return this
@since 4.0.8
"""
if (rownum < 0) {
this.sheet.setDefaultRowHeightInPoints(height);
} else {
this.sheet.getRow(rownum).setHeightInPoints(height);
}
return this;
} | java | public ExcelWriter setRowHeight(int rownum, int height) {
if (rownum < 0) {
this.sheet.setDefaultRowHeightInPoints(height);
} else {
this.sheet.getRow(rownum).setHeightInPoints(height);
}
return this;
} | [
"public",
"ExcelWriter",
"setRowHeight",
"(",
"int",
"rownum",
",",
"int",
"height",
")",
"{",
"if",
"(",
"rownum",
"<",
"0",
")",
"{",
"this",
".",
"sheet",
".",
"setDefaultRowHeightInPoints",
"(",
"height",
")",
";",
"}",
"else",
"{",
"this",
".",
"s... | 设置行高,值为一个点的高度
@param rownum 行号(从0开始计数,-1表示所有行的默认高度)
@param height 高度
@return this
@since 4.0.8 | [
"设置行高,值为一个点的高度"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-poi/src/main/java/cn/hutool/poi/excel/ExcelWriter.java#L447-L454 |
steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/FstInputOutput.java | FstInputOutput.readFstFromBinaryStream | public static MutableFst readFstFromBinaryStream(ObjectInput in) throws IOException,
ClassNotFoundException {
"""
Deserializes an Fst from an ObjectInput
@param in the ObjectInput. It should be already be initialized by the caller.
"""
int version = in.readInt();
if (version < FIRST_VERSION && version > CURRENT_VERSION) {
throw new IllegalArgumentException("cant read version fst model " + version);
}
MutableSymbolTable is = readStringMap(in);
MutableSymbolTable os = readStringMap(in);
MutableSymbolTable ss = null;
if (in.readBoolean()) {
ss = readStringMap(in);
}
return readFstWithTables(in, is, os, ss);
} | java | public static MutableFst readFstFromBinaryStream(ObjectInput in) throws IOException,
ClassNotFoundException {
int version = in.readInt();
if (version < FIRST_VERSION && version > CURRENT_VERSION) {
throw new IllegalArgumentException("cant read version fst model " + version);
}
MutableSymbolTable is = readStringMap(in);
MutableSymbolTable os = readStringMap(in);
MutableSymbolTable ss = null;
if (in.readBoolean()) {
ss = readStringMap(in);
}
return readFstWithTables(in, is, os, ss);
} | [
"public",
"static",
"MutableFst",
"readFstFromBinaryStream",
"(",
"ObjectInput",
"in",
")",
"throws",
"IOException",
",",
"ClassNotFoundException",
"{",
"int",
"version",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"if",
"(",
"version",
"<",
"FIRST_VERSION",
"&&",... | Deserializes an Fst from an ObjectInput
@param in the ObjectInput. It should be already be initialized by the caller. | [
"Deserializes",
"an",
"Fst",
"from",
"an",
"ObjectInput"
] | train | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/FstInputOutput.java#L77-L92 |
tzaeschke/zoodb | src/org/zoodb/internal/server/DiskAccessOneFile.java | DiskAccessOneFile.defineIndex | @Override
public void defineIndex(ZooClassDef def, ZooFieldDef field, boolean isUnique) {
"""
Defines an index and populates it. All objects are put into the cache. This is not
necessarily useful, but it is a one-off operation. Otherwise we would need a special
purpose implementation of the deserializer, which would have the need for a cache removed.
"""
SchemaIndexEntry se = schemaIndex.getSchema(def);
LongLongIndex fieldInd = se.defineIndex(field, isUnique);
//fill index with existing objects
PagedPosIndex ind = se.getObjectIndexLatestSchemaVersion();
PagedPosIndex.ObjectPosIterator iter = ind.iteratorObjects();
DataDeSerializerNoClass dds = new DataDeSerializerNoClass(fileInAP);
if (field.isPrimitiveType()) {
while (iter.hasNext()) {
long pos = iter.nextPos();
dds.seekPos(pos);
//first read the key, then afterwards the field!
long key = dds.getAttrAsLong(def, field);
if (isUnique) {
if (!fieldInd.insertLongIfNotSet(key, dds.getLastOid())) {
throw DBLogger.newUser("Duplicate entry in unique index: " +
Util.oidToString(dds.getLastOid()) + " v=" + key);
}
} else {
fieldInd.insertLong(key, dds.getLastOid());
}
}
} else {
while (iter.hasNext()) {
long pos = iter.nextPos();
dds.seekPos(pos);
//first read the key, then afterwards the field!
long key = dds.getAttrAsLongObjectNotNull(def, field);
fieldInd.insertLong(key, dds.getLastOid());
//TODO handle null values:
//-ignore them?
//-use special value?
}
//DatabaseLogger.debugPrintln(0, "FIXME defineIndex()");
}
iter.close();
} | java | @Override
public void defineIndex(ZooClassDef def, ZooFieldDef field, boolean isUnique) {
SchemaIndexEntry se = schemaIndex.getSchema(def);
LongLongIndex fieldInd = se.defineIndex(field, isUnique);
//fill index with existing objects
PagedPosIndex ind = se.getObjectIndexLatestSchemaVersion();
PagedPosIndex.ObjectPosIterator iter = ind.iteratorObjects();
DataDeSerializerNoClass dds = new DataDeSerializerNoClass(fileInAP);
if (field.isPrimitiveType()) {
while (iter.hasNext()) {
long pos = iter.nextPos();
dds.seekPos(pos);
//first read the key, then afterwards the field!
long key = dds.getAttrAsLong(def, field);
if (isUnique) {
if (!fieldInd.insertLongIfNotSet(key, dds.getLastOid())) {
throw DBLogger.newUser("Duplicate entry in unique index: " +
Util.oidToString(dds.getLastOid()) + " v=" + key);
}
} else {
fieldInd.insertLong(key, dds.getLastOid());
}
}
} else {
while (iter.hasNext()) {
long pos = iter.nextPos();
dds.seekPos(pos);
//first read the key, then afterwards the field!
long key = dds.getAttrAsLongObjectNotNull(def, field);
fieldInd.insertLong(key, dds.getLastOid());
//TODO handle null values:
//-ignore them?
//-use special value?
}
//DatabaseLogger.debugPrintln(0, "FIXME defineIndex()");
}
iter.close();
} | [
"@",
"Override",
"public",
"void",
"defineIndex",
"(",
"ZooClassDef",
"def",
",",
"ZooFieldDef",
"field",
",",
"boolean",
"isUnique",
")",
"{",
"SchemaIndexEntry",
"se",
"=",
"schemaIndex",
".",
"getSchema",
"(",
"def",
")",
";",
"LongLongIndex",
"fieldInd",
"... | Defines an index and populates it. All objects are put into the cache. This is not
necessarily useful, but it is a one-off operation. Otherwise we would need a special
purpose implementation of the deserializer, which would have the need for a cache removed. | [
"Defines",
"an",
"index",
"and",
"populates",
"it",
".",
"All",
"objects",
"are",
"put",
"into",
"the",
"cache",
".",
"This",
"is",
"not",
"necessarily",
"useful",
"but",
"it",
"is",
"a",
"one",
"-",
"off",
"operation",
".",
"Otherwise",
"we",
"would",
... | train | https://github.com/tzaeschke/zoodb/blob/058d0ff161a8ee9d53244c433aca97ee9c654410/src/org/zoodb/internal/server/DiskAccessOneFile.java#L609-L647 |
Tourenathan-G5organisation/SiliCompressor | silicompressor/src/main/java/com/iceteck/silicompressorr/SiliCompressor.java | SiliCompressor.getFilename | private String getFilename(String filename, File file) {
"""
Get the file path of the compressed file
@param filename
@param file Destination directory
@return
"""
if (!file.exists()) {
file.mkdirs();
}
String ext = ".jpg";
//get extension
/*if (Pattern.matches("^[.][p][n][g]", filename)){
ext = ".png";
}*/
return (file.getAbsolutePath() + "/IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ext);
} | java | private String getFilename(String filename, File file) {
if (!file.exists()) {
file.mkdirs();
}
String ext = ".jpg";
//get extension
/*if (Pattern.matches("^[.][p][n][g]", filename)){
ext = ".png";
}*/
return (file.getAbsolutePath() + "/IMG_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()) + ext);
} | [
"private",
"String",
"getFilename",
"(",
"String",
"filename",
",",
"File",
"file",
")",
"{",
"if",
"(",
"!",
"file",
".",
"exists",
"(",
")",
")",
"{",
"file",
".",
"mkdirs",
"(",
")",
";",
"}",
"String",
"ext",
"=",
"\".jpg\"",
";",
"//get extensio... | Get the file path of the compressed file
@param filename
@param file Destination directory
@return | [
"Get",
"the",
"file",
"path",
"of",
"the",
"compressed",
"file"
] | train | https://github.com/Tourenathan-G5organisation/SiliCompressor/blob/546f6cd7b2a7a783e1122df46c1e237f8938fe72/silicompressor/src/main/java/com/iceteck/silicompressorr/SiliCompressor.java#L371-L383 |
knowm/XChart | xchart/src/main/java/org/knowm/xchart/XYChart.java | XYChart.addSeries | public XYSeries addSeries(String seriesName, int[] xData, int[] yData) {
"""
Add a series for a X-Y type chart using using int arrays
@param seriesName
@param xData the X-Axis data
@param yData the Y-Axis data
@return A Series object that you can set properties on
"""
return addSeries(seriesName, xData, yData, null);
} | java | public XYSeries addSeries(String seriesName, int[] xData, int[] yData) {
return addSeries(seriesName, xData, yData, null);
} | [
"public",
"XYSeries",
"addSeries",
"(",
"String",
"seriesName",
",",
"int",
"[",
"]",
"xData",
",",
"int",
"[",
"]",
"yData",
")",
"{",
"return",
"addSeries",
"(",
"seriesName",
",",
"xData",
",",
"yData",
",",
"null",
")",
";",
"}"
] | Add a series for a X-Y type chart using using int arrays
@param seriesName
@param xData the X-Axis data
@param yData the Y-Axis data
@return A Series object that you can set properties on | [
"Add",
"a",
"series",
"for",
"a",
"X",
"-",
"Y",
"type",
"chart",
"using",
"using",
"int",
"arrays"
] | train | https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/XYChart.java#L165-L168 |
JosePaumard/streams-utils | src/main/java/org/paumard/streams/StreamsUtils.java | StreamsUtils.filteringAllMax | public static <E extends Comparable<? super E>> Stream<E> filteringAllMax(Stream<E> stream) {
"""
<p>Generates a stream only composed of the greatest elements of the provided stream, compared using their
natural order. </p>
<p>A <code>NullPointerException</code> will be thrown if the provided stream is null. </p>
@param stream the processed stream
@param <E> the type of the provided stream
@return a filtered stream
"""
Objects.requireNonNull(stream);
return filteringAllMax(stream, Comparator.naturalOrder());
} | java | public static <E extends Comparable<? super E>> Stream<E> filteringAllMax(Stream<E> stream) {
Objects.requireNonNull(stream);
return filteringAllMax(stream, Comparator.naturalOrder());
} | [
"public",
"static",
"<",
"E",
"extends",
"Comparable",
"<",
"?",
"super",
"E",
">",
">",
"Stream",
"<",
"E",
">",
"filteringAllMax",
"(",
"Stream",
"<",
"E",
">",
"stream",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"stream",
")",
";",
"return",
... | <p>Generates a stream only composed of the greatest elements of the provided stream, compared using their
natural order. </p>
<p>A <code>NullPointerException</code> will be thrown if the provided stream is null. </p>
@param stream the processed stream
@param <E> the type of the provided stream
@return a filtered stream | [
"<p",
">",
"Generates",
"a",
"stream",
"only",
"composed",
"of",
"the",
"greatest",
"elements",
"of",
"the",
"provided",
"stream",
"compared",
"using",
"their",
"natural",
"order",
".",
"<",
"/",
"p",
">",
"<p",
">",
"A",
"<code",
">",
"NullPointerExceptio... | train | https://github.com/JosePaumard/streams-utils/blob/56152574af0aca44c5f679761202a8f90984ab73/src/main/java/org/paumard/streams/StreamsUtils.java#L957-L962 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/stat/protocol/protocoltcp_stats.java | protocoltcp_stats.get_nitro_response | protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
"""
<pre>
converts nitro response into object and returns the object array in case of get request.
</pre>
"""
protocoltcp_stats[] resources = new protocoltcp_stats[1];
protocoltcp_response result = (protocoltcp_response) service.get_payload_formatter().string_to_resource(protocoltcp_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.protocoltcp;
return resources;
} | java | protected base_resource[] get_nitro_response(nitro_service service, String response) throws Exception {
protocoltcp_stats[] resources = new protocoltcp_stats[1];
protocoltcp_response result = (protocoltcp_response) service.get_payload_formatter().string_to_resource(protocoltcp_response.class, response);
if(result.errorcode != 0) {
if (result.errorcode == 444) {
service.clear_session();
}
if(result.severity != null)
{
if (result.severity.equals("ERROR"))
throw new nitro_exception(result.message,result.errorcode);
}
else
{
throw new nitro_exception(result.message,result.errorcode);
}
}
resources[0] = result.protocoltcp;
return resources;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"protocoltcp_stats",
"[",
"]",
"resources",
"=",
"new",
"protocoltcp_stats",
"[",
"1",
"]",
";",
"protocoltcp... | <pre>
converts nitro response into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"converts",
"nitro",
"response",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/protocol/protocoltcp_stats.java#L1530-L1549 |
katharsis-project/katharsis-framework | katharsis-jpa/src/main/java/io/katharsis/jpa/JpaModule.java | JpaModule.newServerModule | public static JpaModule newServerModule(EntityManager em, TransactionRunner transactionRunner) {
"""
Creates a new JpaModule for a Katharsis server. No entities are by
default exposed as JSON API resources. Make use of
{@link #addEntityClass(Class)} andd
{@link #addMappedEntityClass(Class, Class, JpaMapper)} to add resources.
@param em
to use
@param transactionRunner
to use
@return created module
"""
return new JpaModule(null, em, transactionRunner);
} | java | public static JpaModule newServerModule(EntityManager em, TransactionRunner transactionRunner) {
return new JpaModule(null, em, transactionRunner);
} | [
"public",
"static",
"JpaModule",
"newServerModule",
"(",
"EntityManager",
"em",
",",
"TransactionRunner",
"transactionRunner",
")",
"{",
"return",
"new",
"JpaModule",
"(",
"null",
",",
"em",
",",
"transactionRunner",
")",
";",
"}"
] | Creates a new JpaModule for a Katharsis server. No entities are by
default exposed as JSON API resources. Make use of
{@link #addEntityClass(Class)} andd
{@link #addMappedEntityClass(Class, Class, JpaMapper)} to add resources.
@param em
to use
@param transactionRunner
to use
@return created module | [
"Creates",
"a",
"new",
"JpaModule",
"for",
"a",
"Katharsis",
"server",
".",
"No",
"entities",
"are",
"by",
"default",
"exposed",
"as",
"JSON",
"API",
"resources",
".",
"Make",
"use",
"of",
"{",
"@link",
"#addEntityClass",
"(",
"Class",
")",
"}",
"andd",
... | train | https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-jpa/src/main/java/io/katharsis/jpa/JpaModule.java#L186-L188 |
looly/hutool | hutool-crypto/src/main/java/cn/hutool/crypto/SmUtil.java | SmUtil.rsAsn1ToPlain | public static byte[] rsAsn1ToPlain(byte[] rsDer) {
"""
BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s<br>
来自:https://blog.csdn.net/pridas/article/details/86118774
@param rsDer rs in asn1 format
@return sign result in plain byte array
@since 4.5.0
"""
ASN1Sequence seq = ASN1Sequence.getInstance(rsDer);
byte[] r = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue());
byte[] s = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(1)).getValue());
byte[] result = new byte[RS_LEN * 2];
System.arraycopy(r, 0, result, 0, r.length);
System.arraycopy(s, 0, result, RS_LEN, s.length);
return result;
} | java | public static byte[] rsAsn1ToPlain(byte[] rsDer) {
ASN1Sequence seq = ASN1Sequence.getInstance(rsDer);
byte[] r = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(0)).getValue());
byte[] s = bigIntToFixexLengthBytes(ASN1Integer.getInstance(seq.getObjectAt(1)).getValue());
byte[] result = new byte[RS_LEN * 2];
System.arraycopy(r, 0, result, 0, r.length);
System.arraycopy(s, 0, result, RS_LEN, s.length);
return result;
} | [
"public",
"static",
"byte",
"[",
"]",
"rsAsn1ToPlain",
"(",
"byte",
"[",
"]",
"rsDer",
")",
"{",
"ASN1Sequence",
"seq",
"=",
"ASN1Sequence",
".",
"getInstance",
"(",
"rsDer",
")",
";",
"byte",
"[",
"]",
"r",
"=",
"bigIntToFixexLengthBytes",
"(",
"ASN1Integ... | BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s<br>
来自:https://blog.csdn.net/pridas/article/details/86118774
@param rsDer rs in asn1 format
@return sign result in plain byte array
@since 4.5.0 | [
"BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s<br",
">",
"来自:https",
":",
"//",
"blog",
".",
"csdn",
".",
"net",
"/",
"pridas",
"/",
"article",
"/",
"details",
"/",
"86118774"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/SmUtil.java#L188-L196 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/seo/CmsAliasList.java | CmsAliasList.addAlias | public void addAlias(final CmsAliasBean alias) {
"""
Adds the controls for a single alias to the widget.<p>
@param alias the alias for which the controls should be added
"""
final HorizontalPanel hp = new HorizontalPanel();
hp.getElement().getStyle().setMargin(2, Unit.PX);
final CmsTextBox textbox = createTextBox();
textbox.setFormValueAsString(alias.getSitePath());
hp.add(textbox);
CmsSelectBox selectbox = createSelectBox();
selectbox.setFormValueAsString(alias.getMode().toString());
hp.add(selectbox);
PushButton deleteButton = createDeleteButton();
hp.add(deleteButton);
final AliasControls controls = new AliasControls(alias, textbox, selectbox);
m_aliasControls.put(controls.getId(), controls);
selectbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
onChangePath(controls);
}
});
deleteButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
m_aliasControls.remove(controls.getId());
hp.removeFromParent();
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> e) {
onChangePath(controls);
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
onChangePath(controls);
}
});
m_changeBox.add(hp);
CmsDomUtil.resizeAncestor(this);
} | java | public void addAlias(final CmsAliasBean alias) {
final HorizontalPanel hp = new HorizontalPanel();
hp.getElement().getStyle().setMargin(2, Unit.PX);
final CmsTextBox textbox = createTextBox();
textbox.setFormValueAsString(alias.getSitePath());
hp.add(textbox);
CmsSelectBox selectbox = createSelectBox();
selectbox.setFormValueAsString(alias.getMode().toString());
hp.add(selectbox);
PushButton deleteButton = createDeleteButton();
hp.add(deleteButton);
final AliasControls controls = new AliasControls(alias, textbox, selectbox);
m_aliasControls.put(controls.getId(), controls);
selectbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> event) {
onChangePath(controls);
}
});
deleteButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent e) {
m_aliasControls.remove(controls.getId());
hp.removeFromParent();
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addValueChangeHandler(new ValueChangeHandler<String>() {
public void onValueChange(ValueChangeEvent<String> e) {
onChangePath(controls);
validateFull(m_structureId, getAliasPaths(), m_defaultValidationHandler);
}
});
textbox.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
onChangePath(controls);
}
});
m_changeBox.add(hp);
CmsDomUtil.resizeAncestor(this);
} | [
"public",
"void",
"addAlias",
"(",
"final",
"CmsAliasBean",
"alias",
")",
"{",
"final",
"HorizontalPanel",
"hp",
"=",
"new",
"HorizontalPanel",
"(",
")",
";",
"hp",
".",
"getElement",
"(",
")",
".",
"getStyle",
"(",
")",
".",
"setMargin",
"(",
"2",
",",
... | Adds the controls for a single alias to the widget.<p>
@param alias the alias for which the controls should be added | [
"Adds",
"the",
"controls",
"for",
"a",
"single",
"alias",
"to",
"the",
"widget",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/seo/CmsAliasList.java#L219-L271 |
verhas/License3j | src/main/java/javax0/license3j/License.java | License.isOK | public boolean isOK(byte[] key) {
"""
See {@link #isOK(PublicKey)}.
@param key serialized encryption key to check the authenticity of the license signature
@return see {@link #isOK(PublicKey)}
"""
try {
return isOK(LicenseKeyPair.Create.from(key, Modifier.PUBLIC).getPair().getPublic());
} catch (Exception e) {
return false;
}
} | java | public boolean isOK(byte[] key) {
try {
return isOK(LicenseKeyPair.Create.from(key, Modifier.PUBLIC).getPair().getPublic());
} catch (Exception e) {
return false;
}
} | [
"public",
"boolean",
"isOK",
"(",
"byte",
"[",
"]",
"key",
")",
"{",
"try",
"{",
"return",
"isOK",
"(",
"LicenseKeyPair",
".",
"Create",
".",
"from",
"(",
"key",
",",
"Modifier",
".",
"PUBLIC",
")",
".",
"getPair",
"(",
")",
".",
"getPublic",
"(",
... | See {@link #isOK(PublicKey)}.
@param key serialized encryption key to check the authenticity of the license signature
@return see {@link #isOK(PublicKey)} | [
"See",
"{",
"@link",
"#isOK",
"(",
"PublicKey",
")",
"}",
"."
] | train | https://github.com/verhas/License3j/blob/f44c6e81b3eb59ab591cc757792749d3556b4afb/src/main/java/javax0/license3j/License.java#L119-L125 |
alkacon/opencms-core | src/org/opencms/search/fields/CmsSearchFieldConfiguration.java | CmsSearchFieldConfiguration.getLocaleExtendedName | public static final String getLocaleExtendedName(String lookup, Locale locale) {
"""
Returns the locale extended name for the given lookup String.<p>
@param lookup the lookup String
@param locale the locale
@return the locale extended name for the given lookup String
"""
if (locale == null) {
return lookup;
}
return getLocaleExtendedName(lookup, locale.toString());
} | java | public static final String getLocaleExtendedName(String lookup, Locale locale) {
if (locale == null) {
return lookup;
}
return getLocaleExtendedName(lookup, locale.toString());
} | [
"public",
"static",
"final",
"String",
"getLocaleExtendedName",
"(",
"String",
"lookup",
",",
"Locale",
"locale",
")",
"{",
"if",
"(",
"locale",
"==",
"null",
")",
"{",
"return",
"lookup",
";",
"}",
"return",
"getLocaleExtendedName",
"(",
"lookup",
",",
"loc... | Returns the locale extended name for the given lookup String.<p>
@param lookup the lookup String
@param locale the locale
@return the locale extended name for the given lookup String | [
"Returns",
"the",
"locale",
"extended",
"name",
"for",
"the",
"given",
"lookup",
"String",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/fields/CmsSearchFieldConfiguration.java#L95-L101 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/EvaluationUtils.java | EvaluationUtils.fBeta | public static double fBeta(double beta, long tp, long fp, long fn) {
"""
Calculate the F beta value from counts
@param beta Beta of value to use
@param tp True positive count
@param fp False positive count
@param fn False negative count
@return F beta
"""
double prec = tp / ((double) tp + fp);
double recall = tp / ((double) tp + fn);
return fBeta(beta, prec, recall);
} | java | public static double fBeta(double beta, long tp, long fp, long fn) {
double prec = tp / ((double) tp + fp);
double recall = tp / ((double) tp + fn);
return fBeta(beta, prec, recall);
} | [
"public",
"static",
"double",
"fBeta",
"(",
"double",
"beta",
",",
"long",
"tp",
",",
"long",
"fp",
",",
"long",
"fn",
")",
"{",
"double",
"prec",
"=",
"tp",
"/",
"(",
"(",
"double",
")",
"tp",
"+",
"fp",
")",
";",
"double",
"recall",
"=",
"tp",
... | Calculate the F beta value from counts
@param beta Beta of value to use
@param tp True positive count
@param fp False positive count
@param fn False negative count
@return F beta | [
"Calculate",
"the",
"F",
"beta",
"value",
"from",
"counts"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/evaluation/EvaluationUtils.java#L109-L113 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/LocationInventoryUrl.java | LocationInventoryUrl.deleteLocationInventoryUrl | public static MozuUrl deleteLocationInventoryUrl(String locationCode, String productCode) {
"""
Get Resource Url for DeleteLocationInventory
@param locationCode The unique, user-defined code that identifies a location.
@param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product.
@return String Resource Url
"""
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/locationinventory/{locationCode}/{productCode}");
formatter.formatUrl("locationCode", locationCode);
formatter.formatUrl("productCode", productCode);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl deleteLocationInventoryUrl(String locationCode, String productCode)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/locationinventory/{locationCode}/{productCode}");
formatter.formatUrl("locationCode", locationCode);
formatter.formatUrl("productCode", productCode);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"deleteLocationInventoryUrl",
"(",
"String",
"locationCode",
",",
"String",
"productCode",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/catalog/admin/locationinventory/{locationCode}/{productCode}\"",
")... | Get Resource Url for DeleteLocationInventory
@param locationCode The unique, user-defined code that identifies a location.
@param productCode The unique, user-defined product code of a product, used throughout to reference and associate to a product.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"DeleteLocationInventory"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/LocationInventoryUrl.java#L88-L94 |
ow2-chameleon/fuchsia | importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/protocol/ZWaveController.java | ZWaveController.requestBatteryLevel | public void requestBatteryLevel(int nodeId, int endpoint) {
"""
Request the battery level from the node / endpoint;
@param nodeId the node id to request the battery level for.
@param endpoint the endpoint to request the battery level for.
"""
ZWaveNode node = this.getNode(nodeId);
SerialMessage serialMessage = null;
ZWaveBatteryCommandClass zwaveBatteryCommandClass = (ZWaveBatteryCommandClass)node.resolveCommandClass(ZWaveCommandClass.CommandClass.BATTERY, endpoint);
if (zwaveBatteryCommandClass == null) {
logger.error("No Command Class BATTERY found on node {}, instance/endpoint {} to request value.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveBatteryCommandClass.getValueMessage(), zwaveBatteryCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
} | java | public void requestBatteryLevel(int nodeId, int endpoint) {
ZWaveNode node = this.getNode(nodeId);
SerialMessage serialMessage = null;
ZWaveBatteryCommandClass zwaveBatteryCommandClass = (ZWaveBatteryCommandClass)node.resolveCommandClass(ZWaveCommandClass.CommandClass.BATTERY, endpoint);
if (zwaveBatteryCommandClass == null) {
logger.error("No Command Class BATTERY found on node {}, instance/endpoint {} to request value.", nodeId, endpoint);
return;
}
serialMessage = node.encapsulate(zwaveBatteryCommandClass.getValueMessage(), zwaveBatteryCommandClass, endpoint);
if (serialMessage != null)
this.sendData(serialMessage);
} | [
"public",
"void",
"requestBatteryLevel",
"(",
"int",
"nodeId",
",",
"int",
"endpoint",
")",
"{",
"ZWaveNode",
"node",
"=",
"this",
".",
"getNode",
"(",
"nodeId",
")",
";",
"SerialMessage",
"serialMessage",
"=",
"null",
";",
"ZWaveBatteryCommandClass",
"zwaveBatt... | Request the battery level from the node / endpoint;
@param nodeId the node id to request the battery level for.
@param endpoint the endpoint to request the battery level for. | [
"Request",
"the",
"battery",
"level",
"from",
"the",
"node",
"/",
"endpoint",
";"
] | train | https://github.com/ow2-chameleon/fuchsia/blob/4e9318eadbdeb945e529789f573b45386e619bed/importers/zwave/src/main/java/org/ow2/chameleon/fuchsia/importer/zwave/internal/protocol/ZWaveController.java#L881-L896 |
facebook/fresco | fbcore/src/main/java/com/facebook/common/util/Hex.java | Hex.encodeHex | public static String encodeHex(byte[] array, boolean zeroTerminated) {
"""
Quickly converts a byte array to a hexadecimal string representation.
@param array byte array, possibly zero-terminated.
"""
char[] cArray = new char[array.length * 2];
int j = 0;
for (int i = 0; i < array.length; i++) {
int index = array[i] & 0xFF;
if (index == 0 && zeroTerminated) {
break;
}
cArray[j++] = FIRST_CHAR[index];
cArray[j++] = SECOND_CHAR[index];
}
return new String(cArray, 0, j);
} | java | public static String encodeHex(byte[] array, boolean zeroTerminated) {
char[] cArray = new char[array.length * 2];
int j = 0;
for (int i = 0; i < array.length; i++) {
int index = array[i] & 0xFF;
if (index == 0 && zeroTerminated) {
break;
}
cArray[j++] = FIRST_CHAR[index];
cArray[j++] = SECOND_CHAR[index];
}
return new String(cArray, 0, j);
} | [
"public",
"static",
"String",
"encodeHex",
"(",
"byte",
"[",
"]",
"array",
",",
"boolean",
"zeroTerminated",
")",
"{",
"char",
"[",
"]",
"cArray",
"=",
"new",
"char",
"[",
"array",
".",
"length",
"*",
"2",
"]",
";",
"int",
"j",
"=",
"0",
";",
"for"... | Quickly converts a byte array to a hexadecimal string representation.
@param array byte array, possibly zero-terminated. | [
"Quickly",
"converts",
"a",
"byte",
"array",
"to",
"a",
"hexadecimal",
"string",
"representation",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/fbcore/src/main/java/com/facebook/common/util/Hex.java#L68-L83 |
haraldk/TwelveMonkeys | servlet/src/main/java/com/twelvemonkeys/servlet/image/ImageFilter.java | ImageFilter.doFilterImpl | protected void doFilterImpl(final ServletRequest pRequest, final ServletResponse pResponse, final FilterChain pChain)
throws IOException, ServletException {
"""
The {@code doFilterImpl} method is called once, or each time a
request/response pair is passed through the chain, depending on the
{@link #oncePerRequest} member variable.
@see #oncePerRequest
@see com.twelvemonkeys.servlet.GenericFilter#doFilterImpl(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) doFilter
@see Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) Filter.doFilter
@param pRequest the servlet request
@param pResponse the servlet response
@param pChain the filter chain
@throws IOException
@throws ServletException
"""
//System.out.println("Starting filtering...");
// Test for trigger params
if (!trigger(pRequest)) {
//System.out.println("Passing request on to next in chain (skipping " + getFilterName() + ")...");
// Pass the request on
pChain.doFilter(pRequest, pResponse);
}
else {
// If already wrapped, the image will be encoded later in the chain
// Or, if this is first filter in chain, we must encode when done
boolean encode = !(pResponse instanceof ImageServletResponse);
// For images, we do post filtering only and need to wrap the response
ImageServletResponse imageResponse = createImageServletResponse(pRequest, pResponse);
//System.out.println("Passing request on to next in chain...");
// Pass the request on
pChain.doFilter(pRequest, imageResponse);
//System.out.println("Post filtering...");
// Get image
//System.out.println("Getting image from ImageServletResponse...");
// Get the image from the wrapped response
RenderedImage image = imageResponse.getImage();
//System.out.println("Got image: " + image);
// Note: Image will be null if this is a HEAD request, the
// If-Modified-Since header is present, or similar.
if (image != null) {
// Do the image filtering
//System.out.println("Filtering image (" + getFilterName() + ")...");
image = doFilter(ImageUtil.toBuffered(image), pRequest, imageResponse);
//System.out.println("Done filtering.");
//System.out.println("Making image available...");
// Make image available to other filters (avoid unnecessary serializing/deserializing)
imageResponse.setImage(image);
//System.out.println("Done.");
}
if (encode) {
//System.out.println("Encoding image...");
// Encode image to original response
if (image != null) {
// TODO: Be smarter than this...
// TODO: Make sure ETag is same, if image content is the same...
// Use ETag of original response (or derived from)
// Use last modified of original response? Or keep original resource's, don't set at all?
// TODO: Why weak ETag?
String etag = "W/\"" + Integer.toHexString(hashCode()) + "-" + Integer.toHexString(image.hashCode()) + "\"";
// TODO: This breaks for wrapped instances, need to either unwrap or test for HttpSR...
((HttpServletResponse) pResponse).setHeader("ETag", etag);
((HttpServletResponse) pResponse).setDateHeader("Last-Modified", (System.currentTimeMillis() / 1000) * 1000);
}
imageResponse.flush();
//System.out.println("Done encoding.");
}
}
//System.out.println("Filtering done.");
} | java | protected void doFilterImpl(final ServletRequest pRequest, final ServletResponse pResponse, final FilterChain pChain)
throws IOException, ServletException {
//System.out.println("Starting filtering...");
// Test for trigger params
if (!trigger(pRequest)) {
//System.out.println("Passing request on to next in chain (skipping " + getFilterName() + ")...");
// Pass the request on
pChain.doFilter(pRequest, pResponse);
}
else {
// If already wrapped, the image will be encoded later in the chain
// Or, if this is first filter in chain, we must encode when done
boolean encode = !(pResponse instanceof ImageServletResponse);
// For images, we do post filtering only and need to wrap the response
ImageServletResponse imageResponse = createImageServletResponse(pRequest, pResponse);
//System.out.println("Passing request on to next in chain...");
// Pass the request on
pChain.doFilter(pRequest, imageResponse);
//System.out.println("Post filtering...");
// Get image
//System.out.println("Getting image from ImageServletResponse...");
// Get the image from the wrapped response
RenderedImage image = imageResponse.getImage();
//System.out.println("Got image: " + image);
// Note: Image will be null if this is a HEAD request, the
// If-Modified-Since header is present, or similar.
if (image != null) {
// Do the image filtering
//System.out.println("Filtering image (" + getFilterName() + ")...");
image = doFilter(ImageUtil.toBuffered(image), pRequest, imageResponse);
//System.out.println("Done filtering.");
//System.out.println("Making image available...");
// Make image available to other filters (avoid unnecessary serializing/deserializing)
imageResponse.setImage(image);
//System.out.println("Done.");
}
if (encode) {
//System.out.println("Encoding image...");
// Encode image to original response
if (image != null) {
// TODO: Be smarter than this...
// TODO: Make sure ETag is same, if image content is the same...
// Use ETag of original response (or derived from)
// Use last modified of original response? Or keep original resource's, don't set at all?
// TODO: Why weak ETag?
String etag = "W/\"" + Integer.toHexString(hashCode()) + "-" + Integer.toHexString(image.hashCode()) + "\"";
// TODO: This breaks for wrapped instances, need to either unwrap or test for HttpSR...
((HttpServletResponse) pResponse).setHeader("ETag", etag);
((HttpServletResponse) pResponse).setDateHeader("Last-Modified", (System.currentTimeMillis() / 1000) * 1000);
}
imageResponse.flush();
//System.out.println("Done encoding.");
}
}
//System.out.println("Filtering done.");
} | [
"protected",
"void",
"doFilterImpl",
"(",
"final",
"ServletRequest",
"pRequest",
",",
"final",
"ServletResponse",
"pResponse",
",",
"final",
"FilterChain",
"pChain",
")",
"throws",
"IOException",
",",
"ServletException",
"{",
"//System.out.println(\"Starting filtering...\")... | The {@code doFilterImpl} method is called once, or each time a
request/response pair is passed through the chain, depending on the
{@link #oncePerRequest} member variable.
@see #oncePerRequest
@see com.twelvemonkeys.servlet.GenericFilter#doFilterImpl(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) doFilter
@see Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) Filter.doFilter
@param pRequest the servlet request
@param pResponse the servlet response
@param pChain the filter chain
@throws IOException
@throws ServletException | [
"The",
"{",
"@code",
"doFilterImpl",
"}",
"method",
"is",
"called",
"once",
"or",
"each",
"time",
"a",
"request",
"/",
"response",
"pair",
"is",
"passed",
"through",
"the",
"chain",
"depending",
"on",
"the",
"{",
"@link",
"#oncePerRequest",
"}",
"member",
... | train | https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ImageFilter.java#L77-L140 |
landawn/AbacusUtil | src/com/landawn/abacus/util/DateUtil.java | DateUtil.setMilliseconds | public static <T extends java.util.Date> T setMilliseconds(final T date, final int amount) {
"""
Copied from Apache Commons Lang under Apache License v2.
<br />
Sets the milliseconds field to a date returning a new object.
The original {@code Date} is unchanged.
@param date the date, not null
@param amount the amount to set
@return a new {@code Date} set with the specified value
@throws IllegalArgumentException if the date is null
@since 2.4
"""
return set(date, Calendar.MILLISECOND, amount);
} | java | public static <T extends java.util.Date> T setMilliseconds(final T date, final int amount) {
return set(date, Calendar.MILLISECOND, amount);
} | [
"public",
"static",
"<",
"T",
"extends",
"java",
".",
"util",
".",
"Date",
">",
"T",
"setMilliseconds",
"(",
"final",
"T",
"date",
",",
"final",
"int",
"amount",
")",
"{",
"return",
"set",
"(",
"date",
",",
"Calendar",
".",
"MILLISECOND",
",",
"amount"... | Copied from Apache Commons Lang under Apache License v2.
<br />
Sets the milliseconds field to a date returning a new object.
The original {@code Date} is unchanged.
@param date the date, not null
@param amount the amount to set
@return a new {@code Date} set with the specified value
@throws IllegalArgumentException if the date is null
@since 2.4 | [
"Copied",
"from",
"Apache",
"Commons",
"Lang",
"under",
"Apache",
"License",
"v2",
".",
"<br",
"/",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/DateUtil.java#L805-L807 |
zaproxy/zaproxy | src/org/zaproxy/zap/view/JCheckBoxTree.java | JCheckBoxTree.addSubtreeToCheckingStateTracking | private void addSubtreeToCheckingStateTracking(DefaultMutableTreeNode node) {
"""
Creating data structure of the current model for the checking mechanism
"""
TreeNode[] path = node.getPath();
TreePath tp = new TreePath(path);
CheckedNode cn = new CheckedNode(false, node.getChildCount() > 0, false);
nodesCheckingState.put(tp, cn);
for (int i = 0 ; i < node.getChildCount() ; i++) {
addSubtreeToCheckingStateTracking((DefaultMutableTreeNode) tp.pathByAddingChild(node.getChildAt(i)).getLastPathComponent());
}
} | java | private void addSubtreeToCheckingStateTracking(DefaultMutableTreeNode node) {
TreeNode[] path = node.getPath();
TreePath tp = new TreePath(path);
CheckedNode cn = new CheckedNode(false, node.getChildCount() > 0, false);
nodesCheckingState.put(tp, cn);
for (int i = 0 ; i < node.getChildCount() ; i++) {
addSubtreeToCheckingStateTracking((DefaultMutableTreeNode) tp.pathByAddingChild(node.getChildAt(i)).getLastPathComponent());
}
} | [
"private",
"void",
"addSubtreeToCheckingStateTracking",
"(",
"DefaultMutableTreeNode",
"node",
")",
"{",
"TreeNode",
"[",
"]",
"path",
"=",
"node",
".",
"getPath",
"(",
")",
";",
"TreePath",
"tp",
"=",
"new",
"TreePath",
"(",
"path",
")",
";",
"CheckedNode",
... | Creating data structure of the current model for the checking mechanism | [
"Creating",
"data",
"structure",
"of",
"the",
"current",
"model",
"for",
"the",
"checking",
"mechanism"
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/JCheckBoxTree.java#L127-L135 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/authentication/ExtensionAuthentication.java | ExtensionAuthentication.getPopupFlagLoggedInIndicatorMenu | private PopupContextMenuItemFactory getPopupFlagLoggedInIndicatorMenu() {
"""
Gets the popup menu for flagging the "Logged in" pattern.
@return the popup menu
"""
if (this.popupFlagLoggedInIndicatorMenuFactory == null) {
popupFlagLoggedInIndicatorMenuFactory = new PopupContextMenuItemFactory("dd - "
+ Constant.messages.getString("context.flag.popup")) {
private static final long serialVersionUID = 2453839120088204122L;
@Override
public ExtensionPopupMenuItem getContextMenu(Context context, String parentMenu) {
return new PopupFlagLoggedInIndicatorMenu(context);
}
};
}
return this.popupFlagLoggedInIndicatorMenuFactory;
} | java | private PopupContextMenuItemFactory getPopupFlagLoggedInIndicatorMenu() {
if (this.popupFlagLoggedInIndicatorMenuFactory == null) {
popupFlagLoggedInIndicatorMenuFactory = new PopupContextMenuItemFactory("dd - "
+ Constant.messages.getString("context.flag.popup")) {
private static final long serialVersionUID = 2453839120088204122L;
@Override
public ExtensionPopupMenuItem getContextMenu(Context context, String parentMenu) {
return new PopupFlagLoggedInIndicatorMenu(context);
}
};
}
return this.popupFlagLoggedInIndicatorMenuFactory;
} | [
"private",
"PopupContextMenuItemFactory",
"getPopupFlagLoggedInIndicatorMenu",
"(",
")",
"{",
"if",
"(",
"this",
".",
"popupFlagLoggedInIndicatorMenuFactory",
"==",
"null",
")",
"{",
"popupFlagLoggedInIndicatorMenuFactory",
"=",
"new",
"PopupContextMenuItemFactory",
"(",
"\"d... | Gets the popup menu for flagging the "Logged in" pattern.
@return the popup menu | [
"Gets",
"the",
"popup",
"menu",
"for",
"flagging",
"the",
"Logged",
"in",
"pattern",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/authentication/ExtensionAuthentication.java#L156-L171 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/math/NumberUtils.java | NumberUtils.toByte | public static byte toByte(final String str, final byte defaultValue) {
"""
<p>Convert a <code>String</code> to a <code>byte</code>, returning a
default value if the conversion fails.</p>
<p>If the string is <code>null</code>, the default value is returned.</p>
<pre>
NumberUtils.toByte(null, 1) = 1
NumberUtils.toByte("", 1) = 1
NumberUtils.toByte("1", 0) = 1
</pre>
@param str the string to convert, may be null
@param defaultValue the default value
@return the byte represented by the string, or the default if conversion fails
@since 2.5
"""
if(str == null) {
return defaultValue;
}
try {
return Byte.parseByte(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
} | java | public static byte toByte(final String str, final byte defaultValue) {
if(str == null) {
return defaultValue;
}
try {
return Byte.parseByte(str);
} catch (final NumberFormatException nfe) {
return defaultValue;
}
} | [
"public",
"static",
"byte",
"toByte",
"(",
"final",
"String",
"str",
",",
"final",
"byte",
"defaultValue",
")",
"{",
"if",
"(",
"str",
"==",
"null",
")",
"{",
"return",
"defaultValue",
";",
"}",
"try",
"{",
"return",
"Byte",
".",
"parseByte",
"(",
"str... | <p>Convert a <code>String</code> to a <code>byte</code>, returning a
default value if the conversion fails.</p>
<p>If the string is <code>null</code>, the default value is returned.</p>
<pre>
NumberUtils.toByte(null, 1) = 1
NumberUtils.toByte("", 1) = 1
NumberUtils.toByte("1", 0) = 1
</pre>
@param str the string to convert, may be null
@param defaultValue the default value
@return the byte represented by the string, or the default if conversion fails
@since 2.5 | [
"<p",
">",
"Convert",
"a",
"<code",
">",
"String<",
"/",
"code",
">",
"to",
"a",
"<code",
">",
"byte<",
"/",
"code",
">",
"returning",
"a",
"default",
"value",
"if",
"the",
"conversion",
"fails",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/math/NumberUtils.java#L323-L332 |
tango-controls/JTango | server/src/main/java/org/tango/server/properties/AttributePropertiesManager.java | AttributePropertiesManager.setAttributePropertyInDB | public void setAttributePropertyInDB(final String attributeName, final String propertyName, final String value)
throws DevFailed {
"""
Set attribute property in tango db
@param attributeName
@param propertyName
@param value
@throws DevFailed
"""
xlogger.entry(propertyName);
// insert value in db only if input value is different and not a
// default value
// if (checkCurrentValue) {
// final String presentValue = getAttributePropertyFromDB(attributeName, propertyName);
// final boolean isADefaultValue = presentValue.isEmpty()
// && (value.equalsIgnoreCase(AttributePropertiesImpl.NOT_SPECIFIED)
// || value.equalsIgnoreCase(AttributePropertiesImpl.NO_DIPLAY_UNIT)
// || value.equalsIgnoreCase(AttributePropertiesImpl.NO_UNIT) || value
// .equalsIgnoreCase(AttributePropertiesImpl.NO_STD_UNIT));
// if (!isADefaultValue && !presentValue.equals(value) && !value.isEmpty() && !value.equals("NaN")) {
// LOGGER.debug("update in DB {}, property {}= {}", new Object[] { attributeName, propertyName, value });
// final Map<String, String[]> propInsert = new HashMap<String, String[]>();
// propInsert.put(propertyName, new String[] { value });
// DatabaseFactory.getDatabase().setAttributeProperties(deviceName, attributeName, propInsert);
// }
// } else {
logger.debug("update in DB {}, property {}= {}", new Object[] { attributeName, propertyName, value });
final Map<String, String[]> propInsert = new HashMap<String, String[]>();
propInsert.put(propertyName, new String[] { value });
DatabaseFactory.getDatabase().setAttributeProperties(deviceName, attributeName, propInsert);
// }
xlogger.exit();
} | java | public void setAttributePropertyInDB(final String attributeName, final String propertyName, final String value)
throws DevFailed {
xlogger.entry(propertyName);
// insert value in db only if input value is different and not a
// default value
// if (checkCurrentValue) {
// final String presentValue = getAttributePropertyFromDB(attributeName, propertyName);
// final boolean isADefaultValue = presentValue.isEmpty()
// && (value.equalsIgnoreCase(AttributePropertiesImpl.NOT_SPECIFIED)
// || value.equalsIgnoreCase(AttributePropertiesImpl.NO_DIPLAY_UNIT)
// || value.equalsIgnoreCase(AttributePropertiesImpl.NO_UNIT) || value
// .equalsIgnoreCase(AttributePropertiesImpl.NO_STD_UNIT));
// if (!isADefaultValue && !presentValue.equals(value) && !value.isEmpty() && !value.equals("NaN")) {
// LOGGER.debug("update in DB {}, property {}= {}", new Object[] { attributeName, propertyName, value });
// final Map<String, String[]> propInsert = new HashMap<String, String[]>();
// propInsert.put(propertyName, new String[] { value });
// DatabaseFactory.getDatabase().setAttributeProperties(deviceName, attributeName, propInsert);
// }
// } else {
logger.debug("update in DB {}, property {}= {}", new Object[] { attributeName, propertyName, value });
final Map<String, String[]> propInsert = new HashMap<String, String[]>();
propInsert.put(propertyName, new String[] { value });
DatabaseFactory.getDatabase().setAttributeProperties(deviceName, attributeName, propInsert);
// }
xlogger.exit();
} | [
"public",
"void",
"setAttributePropertyInDB",
"(",
"final",
"String",
"attributeName",
",",
"final",
"String",
"propertyName",
",",
"final",
"String",
"value",
")",
"throws",
"DevFailed",
"{",
"xlogger",
".",
"entry",
"(",
"propertyName",
")",
";",
"// insert valu... | Set attribute property in tango db
@param attributeName
@param propertyName
@param value
@throws DevFailed | [
"Set",
"attribute",
"property",
"in",
"tango",
"db"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/properties/AttributePropertiesManager.java#L134-L160 |
fcrepo4/fcrepo4 | fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/utils/FedoraTypesUtils.java | FedoraTypesUtils.isReferenceProperty | public static boolean isReferenceProperty(final Node node, final String propertyName) throws RepositoryException {
"""
Check if a property definition is a reference property
@param node the given node
@param propertyName the property name
@return whether a property definition is a reference property
@throws RepositoryException if repository exception occurred
"""
final Optional<PropertyDefinition> propertyDefinition = getDefinitionForPropertyName(node, propertyName);
return propertyDefinition.isPresent() &&
(propertyDefinition.get().getRequiredType() == REFERENCE
|| propertyDefinition.get().getRequiredType() == WEAKREFERENCE);
} | java | public static boolean isReferenceProperty(final Node node, final String propertyName) throws RepositoryException {
final Optional<PropertyDefinition> propertyDefinition = getDefinitionForPropertyName(node, propertyName);
return propertyDefinition.isPresent() &&
(propertyDefinition.get().getRequiredType() == REFERENCE
|| propertyDefinition.get().getRequiredType() == WEAKREFERENCE);
} | [
"public",
"static",
"boolean",
"isReferenceProperty",
"(",
"final",
"Node",
"node",
",",
"final",
"String",
"propertyName",
")",
"throws",
"RepositoryException",
"{",
"final",
"Optional",
"<",
"PropertyDefinition",
">",
"propertyDefinition",
"=",
"getDefinitionForProper... | Check if a property definition is a reference property
@param node the given node
@param propertyName the property name
@return whether a property definition is a reference property
@throws RepositoryException if repository exception occurred | [
"Check",
"if",
"a",
"property",
"definition",
"is",
"a",
"reference",
"property"
] | train | https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/utils/FedoraTypesUtils.java#L325-L331 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/AbstractWFieldIndicatorRenderer.java | AbstractWFieldIndicatorRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
"""
Paints the given AbstractWFieldIndicator.
@param component the WFieldErrorIndicator to paint.
@param renderContext the RenderContext to paint to.
"""
AbstractWFieldIndicator fieldIndicator = (AbstractWFieldIndicator) component;
XmlStringBuilder xml = renderContext.getWriter();
WComponent validationTarget = fieldIndicator.getTargetComponent();
// no need to render an indicator for nothing.
// Diagnosables takes care of thieir own messaging.
if (validationTarget == null || (validationTarget instanceof Diagnosable && !(validationTarget instanceof Input))) {
return;
}
if (validationTarget instanceof Input && !((Input) validationTarget).isReadOnly()) {
return;
}
List<Diagnostic> diags = fieldIndicator.getDiagnostics();
if (diags != null && !diags.isEmpty()) {
xml.appendTagOpen("ui:fieldindicator");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
switch (fieldIndicator.getFieldIndicatorType()) {
case INFO:
xml.appendAttribute("type", "info");
break;
case WARN:
xml.appendAttribute("type", "warn");
break;
case ERROR:
xml.appendAttribute("type", "error");
break;
default:
throw new SystemException("Cannot paint field indicator due to an invalid field indicator type: "
+ fieldIndicator.getFieldIndicatorType());
}
xml.appendAttribute("for", fieldIndicator.getRelatedFieldId());
xml.appendClose();
for (Diagnostic diag : diags) {
xml.appendTag("ui:message");
xml.appendEscaped(diag.getDescription());
xml.appendEndTag("ui:message");
}
xml.appendEndTag("ui:fieldindicator");
}
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
AbstractWFieldIndicator fieldIndicator = (AbstractWFieldIndicator) component;
XmlStringBuilder xml = renderContext.getWriter();
WComponent validationTarget = fieldIndicator.getTargetComponent();
// no need to render an indicator for nothing.
// Diagnosables takes care of thieir own messaging.
if (validationTarget == null || (validationTarget instanceof Diagnosable && !(validationTarget instanceof Input))) {
return;
}
if (validationTarget instanceof Input && !((Input) validationTarget).isReadOnly()) {
return;
}
List<Diagnostic> diags = fieldIndicator.getDiagnostics();
if (diags != null && !diags.isEmpty()) {
xml.appendTagOpen("ui:fieldindicator");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
switch (fieldIndicator.getFieldIndicatorType()) {
case INFO:
xml.appendAttribute("type", "info");
break;
case WARN:
xml.appendAttribute("type", "warn");
break;
case ERROR:
xml.appendAttribute("type", "error");
break;
default:
throw new SystemException("Cannot paint field indicator due to an invalid field indicator type: "
+ fieldIndicator.getFieldIndicatorType());
}
xml.appendAttribute("for", fieldIndicator.getRelatedFieldId());
xml.appendClose();
for (Diagnostic diag : diags) {
xml.appendTag("ui:message");
xml.appendEscaped(diag.getDescription());
xml.appendEndTag("ui:message");
}
xml.appendEndTag("ui:fieldindicator");
}
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"AbstractWFieldIndicator",
"fieldIndicator",
"=",
"(",
"AbstractWFieldIndicator",
")",
"component",
";",
"XmlStringBui... | Paints the given AbstractWFieldIndicator.
@param component the WFieldErrorIndicator to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"AbstractWFieldIndicator",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/AbstractWFieldIndicatorRenderer.java#L28-L81 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java | MemberSummaryBuilder.buildConstructorsSummary | public void buildConstructorsSummary(XMLNode node, Content memberSummaryTree) {
"""
Build the constructor summary.
@param node the XML element that specifies which components to document
@param memberSummaryTree the content tree to which the documentation will be added
"""
MemberSummaryWriter writer =
memberSummaryWriters[VisibleMemberMap.CONSTRUCTORS];
VisibleMemberMap visibleMemberMap =
visibleMemberMaps[VisibleMemberMap.CONSTRUCTORS];
addSummary(writer, visibleMemberMap, false, memberSummaryTree);
} | java | public void buildConstructorsSummary(XMLNode node, Content memberSummaryTree) {
MemberSummaryWriter writer =
memberSummaryWriters[VisibleMemberMap.CONSTRUCTORS];
VisibleMemberMap visibleMemberMap =
visibleMemberMaps[VisibleMemberMap.CONSTRUCTORS];
addSummary(writer, visibleMemberMap, false, memberSummaryTree);
} | [
"public",
"void",
"buildConstructorsSummary",
"(",
"XMLNode",
"node",
",",
"Content",
"memberSummaryTree",
")",
"{",
"MemberSummaryWriter",
"writer",
"=",
"memberSummaryWriters",
"[",
"VisibleMemberMap",
".",
"CONSTRUCTORS",
"]",
";",
"VisibleMemberMap",
"visibleMemberMap... | Build the constructor summary.
@param node the XML element that specifies which components to document
@param memberSummaryTree the content tree to which the documentation will be added | [
"Build",
"the",
"constructor",
"summary",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java#L317-L323 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.jwtsso_fat/fat/src/com/ibm/ws/security/jwtsso/fat/utils/CommonExpectations.java | CommonExpectations.getResponseTextExpectationsForLtpaCookie | public static Expectations getResponseTextExpectationsForLtpaCookie(String testAction, String username) {
"""
Sets expectations that will check:
<ol>
<li>Response text includes an LTPA cookie
<li>Response text includes expected remote user
<li>Subject principal is a WSPrincipal with the expected user
<li>Subject public credentials include appropriate access ID with registry realm
</ol>
"""
Expectations expectations = new Expectations();
expectations.addExpectations(responseTextIncludesCookie(testAction, JwtFatConstants.LTPA_COOKIE_NAME));
expectations.addExpectations(responseTextIncludesExpectedRemoteUser(testAction, username));
expectations.addExpectations(responseTextIncludesWSPrincipal(testAction, username));
expectations.addExpectations(responseTextIncludesExpectedAccessId(testAction, JwtFatConstants.BASIC_REALM, username));
return expectations;
} | java | public static Expectations getResponseTextExpectationsForLtpaCookie(String testAction, String username) {
Expectations expectations = new Expectations();
expectations.addExpectations(responseTextIncludesCookie(testAction, JwtFatConstants.LTPA_COOKIE_NAME));
expectations.addExpectations(responseTextIncludesExpectedRemoteUser(testAction, username));
expectations.addExpectations(responseTextIncludesWSPrincipal(testAction, username));
expectations.addExpectations(responseTextIncludesExpectedAccessId(testAction, JwtFatConstants.BASIC_REALM, username));
return expectations;
} | [
"public",
"static",
"Expectations",
"getResponseTextExpectationsForLtpaCookie",
"(",
"String",
"testAction",
",",
"String",
"username",
")",
"{",
"Expectations",
"expectations",
"=",
"new",
"Expectations",
"(",
")",
";",
"expectations",
".",
"addExpectations",
"(",
"r... | Sets expectations that will check:
<ol>
<li>Response text includes an LTPA cookie
<li>Response text includes expected remote user
<li>Subject principal is a WSPrincipal with the expected user
<li>Subject public credentials include appropriate access ID with registry realm
</ol> | [
"Sets",
"expectations",
"that",
"will",
"check",
":",
"<ol",
">",
"<li",
">",
"Response",
"text",
"includes",
"an",
"LTPA",
"cookie",
"<li",
">",
"Response",
"text",
"includes",
"expected",
"remote",
"user",
"<li",
">",
"Subject",
"principal",
"is",
"a",
"... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.jwtsso_fat/fat/src/com/ibm/ws/security/jwtsso/fat/utils/CommonExpectations.java#L134-L141 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jca.cm/src/com/ibm/ws/jca/cm/ConnectorService.java | ConnectorService.getMessage | public static final String getMessage(String key, Object... args) {
"""
Get a translated message from J2CAMessages file.
@param key message key.
@param args message parameters
@return a translated message.
"""
return NLS.getFormattedMessage(key, args, key);
} | java | public static final String getMessage(String key, Object... args) {
return NLS.getFormattedMessage(key, args, key);
} | [
"public",
"static",
"final",
"String",
"getMessage",
"(",
"String",
"key",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"NLS",
".",
"getFormattedMessage",
"(",
"key",
",",
"args",
",",
"key",
")",
";",
"}"
] | Get a translated message from J2CAMessages file.
@param key message key.
@param args message parameters
@return a translated message. | [
"Get",
"a",
"translated",
"message",
"from",
"J2CAMessages",
"file",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jca.cm/src/com/ibm/ws/jca/cm/ConnectorService.java#L79-L81 |
Netflix/ndbench | ndbench-dyno-plugins/src/main/java/com/netflix/ndbench/plugin/dyno/DynoJedisUtils.java | DynoJedisUtils.nonPipelineZRANGE | public String nonPipelineZRANGE(String key, int max_score) {
"""
Exercising ZRANGE to receive all keys between 0 and MAX_SCORE
@param key
"""
StringBuilder sb = new StringBuilder();
// Return all elements
Set<String> returnEntries = this.jedisClient.get().zrange(key, 0, -1);
if (returnEntries.isEmpty()) {
logger.error("The number of entries in the sorted set are less than the number of entries written");
return null;
}
returnEntries.forEach(sb::append);
return sb.toString();
} | java | public String nonPipelineZRANGE(String key, int max_score) {
StringBuilder sb = new StringBuilder();
// Return all elements
Set<String> returnEntries = this.jedisClient.get().zrange(key, 0, -1);
if (returnEntries.isEmpty()) {
logger.error("The number of entries in the sorted set are less than the number of entries written");
return null;
}
returnEntries.forEach(sb::append);
return sb.toString();
} | [
"public",
"String",
"nonPipelineZRANGE",
"(",
"String",
"key",
",",
"int",
"max_score",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"// Return all elements",
"Set",
"<",
"String",
">",
"returnEntries",
"=",
"this",
".",
"jedisC... | Exercising ZRANGE to receive all keys between 0 and MAX_SCORE
@param key | [
"Exercising",
"ZRANGE",
"to",
"receive",
"all",
"keys",
"between",
"0",
"and",
"MAX_SCORE"
] | train | https://github.com/Netflix/ndbench/blob/8d664244b5f9d01395248a296b86a3c822e6d764/ndbench-dyno-plugins/src/main/java/com/netflix/ndbench/plugin/dyno/DynoJedisUtils.java#L143-L154 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.waitForActivity | public boolean waitForActivity(String name, int timeout) {
"""
Waits for an Activity matching the specified name.
@param name the name of the {@link Activity} to wait for. Example is: {@code "MyActivity"}
@param timeout the amount of time in milliseconds to wait
@return {@code true} if {@link Activity} appears before the timeout and {@code false} if it does not
"""
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForActivity(\""+name+"\", "+timeout+")");
}
return waiter.waitForActivity(name, timeout);
} | java | public boolean waitForActivity(String name, int timeout)
{
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForActivity(\""+name+"\", "+timeout+")");
}
return waiter.waitForActivity(name, timeout);
} | [
"public",
"boolean",
"waitForActivity",
"(",
"String",
"name",
",",
"int",
"timeout",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"waitForActivity(\\\"\"",
"+",
"name",
"+",... | Waits for an Activity matching the specified name.
@param name the name of the {@link Activity} to wait for. Example is: {@code "MyActivity"}
@param timeout the amount of time in milliseconds to wait
@return {@code true} if {@link Activity} appears before the timeout and {@code false} if it does not | [
"Waits",
"for",
"an",
"Activity",
"matching",
"the",
"specified",
"name",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L3591-L3598 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java | SeaGlassLookAndFeel.defineProgressBars | private void defineProgressBars(UIDefaults d) {
"""
Initialize the progress bar settings.
@param d the UI defaults map.
"""
// Copied from nimbus
//Initialize ProgressBar
d.put("ProgressBar.contentMargins", new InsetsUIResource(0, 0, 0, 0));
d.put("ProgressBar.States", "Enabled,Disabled,Indeterminate,Finished");
d.put("ProgressBar.tileWhenIndeterminate", Boolean.TRUE);
d.put("ProgressBar.paintOutsideClip", Boolean.TRUE);
d.put("ProgressBar.rotateText", Boolean.TRUE);
d.put("ProgressBar.vertictalSize", new DimensionUIResource(19, 150));
d.put("ProgressBar.horizontalSize", new DimensionUIResource(150, 19));
addColor(d, "ProgressBar[Disabled].textForeground", "seaGlassDisabledText", 0.0f, 0.0f, 0.0f, 0);
d.put("ProgressBar[Disabled+Indeterminate].progressPadding", new Integer(3));
// Seaglass starts below.
d.put("progressBarTrackInterior", Color.WHITE);
d.put("progressBarTrackBase", new Color(0x4076bf));
d.put("ProgressBar.Indeterminate", new ProgressBarIndeterminateState());
d.put("ProgressBar.Finished", new ProgressBarFinishedState());
String p = "ProgressBar";
String c = PAINTER_PREFIX + "ProgressBarPainter";
d.put(p + ".cycleTime", 500);
d.put(p + ".progressPadding", new Integer(3));
d.put(p + ".trackThickness", new Integer(19));
d.put(p + ".tileWidth", new Integer(24));
d.put(p + ".backgroundFillColor", Color.WHITE);
d.put(p + ".font", new DerivedFont("defaultFont", 0.769f, null, null));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED));
d.put(p + "[Enabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_FINISHED));
d.put(p + "[Enabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_INDETERMINATE));
d.put(p + "[Disabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED));
d.put(p + "[Disabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_FINISHED));
d.put(p + "[Disabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_INDETERMINATE));
} | java | private void defineProgressBars(UIDefaults d) {
// Copied from nimbus
//Initialize ProgressBar
d.put("ProgressBar.contentMargins", new InsetsUIResource(0, 0, 0, 0));
d.put("ProgressBar.States", "Enabled,Disabled,Indeterminate,Finished");
d.put("ProgressBar.tileWhenIndeterminate", Boolean.TRUE);
d.put("ProgressBar.paintOutsideClip", Boolean.TRUE);
d.put("ProgressBar.rotateText", Boolean.TRUE);
d.put("ProgressBar.vertictalSize", new DimensionUIResource(19, 150));
d.put("ProgressBar.horizontalSize", new DimensionUIResource(150, 19));
addColor(d, "ProgressBar[Disabled].textForeground", "seaGlassDisabledText", 0.0f, 0.0f, 0.0f, 0);
d.put("ProgressBar[Disabled+Indeterminate].progressPadding", new Integer(3));
// Seaglass starts below.
d.put("progressBarTrackInterior", Color.WHITE);
d.put("progressBarTrackBase", new Color(0x4076bf));
d.put("ProgressBar.Indeterminate", new ProgressBarIndeterminateState());
d.put("ProgressBar.Finished", new ProgressBarFinishedState());
String p = "ProgressBar";
String c = PAINTER_PREFIX + "ProgressBarPainter";
d.put(p + ".cycleTime", 500);
d.put(p + ".progressPadding", new Integer(3));
d.put(p + ".trackThickness", new Integer(19));
d.put(p + ".tileWidth", new Integer(24));
d.put(p + ".backgroundFillColor", Color.WHITE);
d.put(p + ".font", new DerivedFont("defaultFont", 0.769f, null, null));
d.put(p + "[Enabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_ENABLED));
d.put(p + "[Disabled].backgroundPainter", new LazyPainter(c, ProgressBarPainter.Which.BACKGROUND_DISABLED));
d.put(p + "[Enabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED));
d.put(p + "[Enabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_FINISHED));
d.put(p + "[Enabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_ENABLED_INDETERMINATE));
d.put(p + "[Disabled].foregroundPainter", new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED));
d.put(p + "[Disabled+Finished].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_FINISHED));
d.put(p + "[Disabled+Indeterminate].foregroundPainter",
new LazyPainter(c, ProgressBarPainter.Which.FOREGROUND_DISABLED_INDETERMINATE));
} | [
"private",
"void",
"defineProgressBars",
"(",
"UIDefaults",
"d",
")",
"{",
"// Copied from nimbus",
"//Initialize ProgressBar",
"d",
".",
"put",
"(",
"\"ProgressBar.contentMargins\"",
",",
"new",
"InsetsUIResource",
"(",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"... | Initialize the progress bar settings.
@param d the UI defaults map. | [
"Initialize",
"the",
"progress",
"bar",
"settings",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/SeaGlassLookAndFeel.java#L1601-L1644 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/MessageRouterImpl.java | MessageRouterImpl.routeTo | protected void routeTo(String msg, LogRecord logRecord, String logHandlerId) {
"""
Route the message to the LogHandler identified by the given logHandlerId.
@param msg The fully formatted message.
@param logRecord The associated LogRecord, in case the LogHandler needs it.
@param logHandlerId The LogHandler ID in which to route.
"""
LogHandler logHandler = logHandlerServices.get(logHandlerId);
if (logHandler != null) {
logHandler.publish(msg, logRecord);
}
} | java | protected void routeTo(String msg, LogRecord logRecord, String logHandlerId) {
LogHandler logHandler = logHandlerServices.get(logHandlerId);
if (logHandler != null) {
logHandler.publish(msg, logRecord);
}
} | [
"protected",
"void",
"routeTo",
"(",
"String",
"msg",
",",
"LogRecord",
"logRecord",
",",
"String",
"logHandlerId",
")",
"{",
"LogHandler",
"logHandler",
"=",
"logHandlerServices",
".",
"get",
"(",
"logHandlerId",
")",
";",
"if",
"(",
"logHandler",
"!=",
"null... | Route the message to the LogHandler identified by the given logHandlerId.
@param msg The fully formatted message.
@param logRecord The associated LogRecord, in case the LogHandler needs it.
@param logHandlerId The LogHandler ID in which to route. | [
"Route",
"the",
"message",
"to",
"the",
"LogHandler",
"identified",
"by",
"the",
"given",
"logHandlerId",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.osgi/src/com/ibm/ws/logging/internal/osgi/MessageRouterImpl.java#L279-L284 |
lessthanoptimal/ejml | main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java | CommonOps_DSCC.multTransB | public static void multTransB(DMatrixSparseCSC A , DMatrixSparseCSC B , DMatrixSparseCSC C ,
@Nullable IGrowArray gw, @Nullable DGrowArray gx ) {
"""
Performs matrix multiplication. C = A*B<sup>T</sup>. B needs to be sorted and will be sorted if it
has not already been sorted.
@param A (Input) Matrix. Not modified.
@param B (Input) Matrix. Value not modified but indicies will be sorted if not sorted already.
@param C (Output) Storage for results. Data length is increased if increased if insufficient.
@param gw (Optional) Storage for internal workspace. Can be null.
@param gx (Optional) Storage for internal workspace. Can be null.
"""
if( A.numCols != B.numCols )
throw new MatrixDimensionException("Inconsistent matrix shapes. "+stringShapes(A,B));
C.reshape(A.numRows,B.numRows);
if( !B.isIndicesSorted() )
B.sortIndices(null);
ImplSparseSparseMult_DSCC.multTransB(A,B,C,gw,gx);
} | java | public static void multTransB(DMatrixSparseCSC A , DMatrixSparseCSC B , DMatrixSparseCSC C ,
@Nullable IGrowArray gw, @Nullable DGrowArray gx )
{
if( A.numCols != B.numCols )
throw new MatrixDimensionException("Inconsistent matrix shapes. "+stringShapes(A,B));
C.reshape(A.numRows,B.numRows);
if( !B.isIndicesSorted() )
B.sortIndices(null);
ImplSparseSparseMult_DSCC.multTransB(A,B,C,gw,gx);
} | [
"public",
"static",
"void",
"multTransB",
"(",
"DMatrixSparseCSC",
"A",
",",
"DMatrixSparseCSC",
"B",
",",
"DMatrixSparseCSC",
"C",
",",
"@",
"Nullable",
"IGrowArray",
"gw",
",",
"@",
"Nullable",
"DGrowArray",
"gx",
")",
"{",
"if",
"(",
"A",
".",
"numCols",
... | Performs matrix multiplication. C = A*B<sup>T</sup>. B needs to be sorted and will be sorted if it
has not already been sorted.
@param A (Input) Matrix. Not modified.
@param B (Input) Matrix. Value not modified but indicies will be sorted if not sorted already.
@param C (Output) Storage for results. Data length is increased if increased if insufficient.
@param gw (Optional) Storage for internal workspace. Can be null.
@param gx (Optional) Storage for internal workspace. Can be null. | [
"Performs",
"matrix",
"multiplication",
".",
"C",
"=",
"A",
"*",
"B<sup",
">",
"T<",
"/",
"sup",
">",
".",
"B",
"needs",
"to",
"be",
"sorted",
"and",
"will",
"be",
"sorted",
"if",
"it",
"has",
"not",
"already",
"been",
"sorted",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L174-L185 |
jmrozanec/cron-utils | src/main/java/com/cronutils/utils/Preconditions.java | Preconditions.checkNotNullNorEmpty | public static String checkNotNullNorEmpty(final String reference, final Object errorMessage) {
"""
Ensures that a string reference passed as a parameter to the calling method is not null.
nor empty.
@param reference a string reference
@param errorMessage the exception message to use if the check fails; will be converted to a
string using {@link String#valueOf(Object)}
@return the non-null reference that was validated
@throws NullPointerException if {@code reference} is null
@throws IllegalArgumentException if {@code reference} is empty
"""
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
if (reference.isEmpty()) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
return reference;
} | java | public static String checkNotNullNorEmpty(final String reference, final Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
if (reference.isEmpty()) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
return reference;
} | [
"public",
"static",
"String",
"checkNotNullNorEmpty",
"(",
"final",
"String",
"reference",
",",
"final",
"Object",
"errorMessage",
")",
"{",
"if",
"(",
"reference",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"String",
".",
"valueOf",
... | Ensures that a string reference passed as a parameter to the calling method is not null.
nor empty.
@param reference a string reference
@param errorMessage the exception message to use if the check fails; will be converted to a
string using {@link String#valueOf(Object)}
@return the non-null reference that was validated
@throws NullPointerException if {@code reference} is null
@throws IllegalArgumentException if {@code reference} is empty | [
"Ensures",
"that",
"a",
"string",
"reference",
"passed",
"as",
"a",
"parameter",
"to",
"the",
"calling",
"method",
"is",
"not",
"null",
".",
"nor",
"empty",
"."
] | train | https://github.com/jmrozanec/cron-utils/blob/adac5ec8fd9160b082f9762a6eedea0715731170/src/main/java/com/cronutils/utils/Preconditions.java#L201-L209 |
jenkinsci/jenkins | core/src/main/java/hudson/model/queue/WorkUnitContext.java | WorkUnitContext.createWorkUnit | public WorkUnit createWorkUnit(SubTask execUnit) {
"""
Called within the queue maintenance process to create a {@link WorkUnit} for the given {@link SubTask}
"""
WorkUnit wu = new WorkUnit(this, execUnit);
workUnits.add(wu);
return wu;
} | java | public WorkUnit createWorkUnit(SubTask execUnit) {
WorkUnit wu = new WorkUnit(this, execUnit);
workUnits.add(wu);
return wu;
} | [
"public",
"WorkUnit",
"createWorkUnit",
"(",
"SubTask",
"execUnit",
")",
"{",
"WorkUnit",
"wu",
"=",
"new",
"WorkUnit",
"(",
"this",
",",
"execUnit",
")",
";",
"workUnits",
".",
"add",
"(",
"wu",
")",
";",
"return",
"wu",
";",
"}"
] | Called within the queue maintenance process to create a {@link WorkUnit} for the given {@link SubTask} | [
"Called",
"within",
"the",
"queue",
"maintenance",
"process",
"to",
"create",
"a",
"{"
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/queue/WorkUnitContext.java#L93-L97 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBindingFactory.java | SwingBindingFactory.createBoundList | public Binding createBoundList(String selectionFormProperty, ValueModel selectableItemsHolder,
String renderedProperty) {
"""
Binds the values specified in the collection contained within
<code>selectableItemsHolder</code> to a {@link JList}, with any
user selection being placed in the form property referred to by
<code>selectionFormProperty</code>. Each item in the list will be
rendered by looking up a property on the item by the name contained
in <code>renderedProperty</code>, retrieving the value of the property,
and rendering that value in the UI. Note that the selection in the
bound list will track any changes to the
<code>selectionFormProperty</code>. This is especially useful to
preselect items in the list - if <code>selectionFormProperty</code>
is not empty when the list is bound, then its content will be used
for the initial selection. This method uses default behavior to
determine the selection mode of the resulting <code>JList</code>:
if <code>selectionFormProperty</code> refers to a
{@link java.util.Collection} type property, then
{@link javax.swing.ListSelectionModel#MULTIPLE_INTERVAL_SELECTION} will
be used, otherwise
{@link javax.swing.ListSelectionModel#SINGLE_SELECTION} will be used.
@param selectionFormProperty form property to hold user's selection.
This property must either be compatible
with the item objects contained in
<code>selectableItemsHolder</code> (in
which case only single selection makes
sense), or must be a
<code>Collection</code> type, which allows
for multiple selection.
@param selectableItemsHolder <code>ValueModel</code> containing the
items with which to populate the list.
@param renderedProperty the property to be queried for each item
in the list, the result of which will be
used to render that item in the UI
@return
"""
return createBoundList(selectionFormProperty, selectableItemsHolder, renderedProperty, null);
} | java | public Binding createBoundList(String selectionFormProperty, ValueModel selectableItemsHolder,
String renderedProperty) {
return createBoundList(selectionFormProperty, selectableItemsHolder, renderedProperty, null);
} | [
"public",
"Binding",
"createBoundList",
"(",
"String",
"selectionFormProperty",
",",
"ValueModel",
"selectableItemsHolder",
",",
"String",
"renderedProperty",
")",
"{",
"return",
"createBoundList",
"(",
"selectionFormProperty",
",",
"selectableItemsHolder",
",",
"renderedPr... | Binds the values specified in the collection contained within
<code>selectableItemsHolder</code> to a {@link JList}, with any
user selection being placed in the form property referred to by
<code>selectionFormProperty</code>. Each item in the list will be
rendered by looking up a property on the item by the name contained
in <code>renderedProperty</code>, retrieving the value of the property,
and rendering that value in the UI. Note that the selection in the
bound list will track any changes to the
<code>selectionFormProperty</code>. This is especially useful to
preselect items in the list - if <code>selectionFormProperty</code>
is not empty when the list is bound, then its content will be used
for the initial selection. This method uses default behavior to
determine the selection mode of the resulting <code>JList</code>:
if <code>selectionFormProperty</code> refers to a
{@link java.util.Collection} type property, then
{@link javax.swing.ListSelectionModel#MULTIPLE_INTERVAL_SELECTION} will
be used, otherwise
{@link javax.swing.ListSelectionModel#SINGLE_SELECTION} will be used.
@param selectionFormProperty form property to hold user's selection.
This property must either be compatible
with the item objects contained in
<code>selectableItemsHolder</code> (in
which case only single selection makes
sense), or must be a
<code>Collection</code> type, which allows
for multiple selection.
@param selectableItemsHolder <code>ValueModel</code> containing the
items with which to populate the list.
@param renderedProperty the property to be queried for each item
in the list, the result of which will be
used to render that item in the UI
@return | [
"Binds",
"the",
"values",
"specified",
"in",
"the",
"collection",
"contained",
"within",
"<code",
">",
"selectableItemsHolder<",
"/",
"code",
">",
"to",
"a",
"{",
"@link",
"JList",
"}",
"with",
"any",
"user",
"selection",
"being",
"placed",
"in",
"the",
"for... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBindingFactory.java#L224-L227 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/auth/ProcessCredentialsProvider.java | ProcessCredentialsProvider.getText | private String getText(JsonNode jsonObject, String nodeName) {
"""
Get a textual value from a json object, throwing an exception if the node is missing or not textual.
"""
JsonNode subNode = jsonObject.get(nodeName);
if (subNode == null) {
return null;
}
if (!subNode.isTextual()) {
throw new IllegalStateException(nodeName + " from credential process should be textual, but was " +
subNode.getNodeType());
}
return subNode.asText();
} | java | private String getText(JsonNode jsonObject, String nodeName) {
JsonNode subNode = jsonObject.get(nodeName);
if (subNode == null) {
return null;
}
if (!subNode.isTextual()) {
throw new IllegalStateException(nodeName + " from credential process should be textual, but was " +
subNode.getNodeType());
}
return subNode.asText();
} | [
"private",
"String",
"getText",
"(",
"JsonNode",
"jsonObject",
",",
"String",
"nodeName",
")",
"{",
"JsonNode",
"subNode",
"=",
"jsonObject",
".",
"get",
"(",
"nodeName",
")",
";",
"if",
"(",
"subNode",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",... | Get a textual value from a json object, throwing an exception if the node is missing or not textual. | [
"Get",
"a",
"textual",
"value",
"from",
"a",
"json",
"object",
"throwing",
"an",
"exception",
"if",
"the",
"node",
"is",
"missing",
"or",
"not",
"textual",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/auth/ProcessCredentialsProvider.java#L191-L204 |
att/AAF | authz/authz-cass/src/main/java/com/att/dao/aaf/cass/UserRoleDAO.java | UserRoleDAO.wasModified | @Override
protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
"""
Log Modification statements to History
@param modified which CRUD action was done
@param data entity data that needs a log entry
@param overrideMessage if this is specified, we use it rather than crafting a history message based on data
"""
boolean memo = override.length>0 && override[0]!=null;
boolean subject = override.length>1 && override[1]!=null;
HistoryDAO.Data hd = HistoryDAO.newInitedData();
HistoryDAO.Data hdRole = HistoryDAO.newInitedData();
hd.user = hdRole.user = trans.user();
hd.action = modified.name();
// Modifying User/Role is an Update to Role, not a Create. JG, 07-14-2015
hdRole.action = CRUD.update.name();
hd.target = TABLE;
hdRole.target = RoleDAO.TABLE;
hd.subject = subject?override[1] : (data.user + '|'+data.role);
hdRole.subject = data.role;
switch(modified) {
case create:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: String.format("%s added to %s",data.user,data.role);
break;
case update:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: String.format("%s - %s was updated",data.user,data.role);
break;
case delete:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: String.format("%s removed from %s",data.user,data.role);
try {
hd.reconstruct = hdRole.reconstruct = data.bytify();
} catch (IOException e) {
trans.warn().log(e,"Deleted UserRole could not be serialized");
}
break;
default:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: "n/a";
}
if(historyDAO.create(trans, hd).status!=Status.OK) {
trans.error().log("Cannot log to History");
}
if(historyDAO.create(trans, hdRole).status!=Status.OK) {
trans.error().log("Cannot log to History");
}
// uses User as Segment
if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
trans.error().log("Cannot touch CacheInfo");
}
} | java | @Override
protected void wasModified(AuthzTrans trans, CRUD modified, Data data, String ... override) {
boolean memo = override.length>0 && override[0]!=null;
boolean subject = override.length>1 && override[1]!=null;
HistoryDAO.Data hd = HistoryDAO.newInitedData();
HistoryDAO.Data hdRole = HistoryDAO.newInitedData();
hd.user = hdRole.user = trans.user();
hd.action = modified.name();
// Modifying User/Role is an Update to Role, not a Create. JG, 07-14-2015
hdRole.action = CRUD.update.name();
hd.target = TABLE;
hdRole.target = RoleDAO.TABLE;
hd.subject = subject?override[1] : (data.user + '|'+data.role);
hdRole.subject = data.role;
switch(modified) {
case create:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: String.format("%s added to %s",data.user,data.role);
break;
case update:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: String.format("%s - %s was updated",data.user,data.role);
break;
case delete:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: String.format("%s removed from %s",data.user,data.role);
try {
hd.reconstruct = hdRole.reconstruct = data.bytify();
} catch (IOException e) {
trans.warn().log(e,"Deleted UserRole could not be serialized");
}
break;
default:
hd.memo = hdRole.memo = memo
? String.format("%s by %s", override[0], hd.user)
: "n/a";
}
if(historyDAO.create(trans, hd).status!=Status.OK) {
trans.error().log("Cannot log to History");
}
if(historyDAO.create(trans, hdRole).status!=Status.OK) {
trans.error().log("Cannot log to History");
}
// uses User as Segment
if(infoDAO.touch(trans, TABLE,data.invalidate(cache)).notOK()) {
trans.error().log("Cannot touch CacheInfo");
}
} | [
"@",
"Override",
"protected",
"void",
"wasModified",
"(",
"AuthzTrans",
"trans",
",",
"CRUD",
"modified",
",",
"Data",
"data",
",",
"String",
"...",
"override",
")",
"{",
"boolean",
"memo",
"=",
"override",
".",
"length",
">",
"0",
"&&",
"override",
"[",
... | Log Modification statements to History
@param modified which CRUD action was done
@param data entity data that needs a log entry
@param overrideMessage if this is specified, we use it rather than crafting a history message based on data | [
"Log",
"Modification",
"statements",
"to",
"History"
] | train | https://github.com/att/AAF/blob/090562e956c0035db972aafba844dc6d3fc948ee/authz/authz-cass/src/main/java/com/att/dao/aaf/cass/UserRoleDAO.java#L245-L299 |
lecousin/java-framework-core | net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/AsyncWork.java | AsyncWork.listenInline | public final void listenInline(AsyncWorkListener<T,TError> listener) {
"""
Add a listener to be called when this AsyncWork is unblocked.
"""
synchronized (this) {
if (!unblocked || listenersInline != null) {
if (listenersInline == null) listenersInline = new ArrayList<>(5);
listenersInline.add(listener);
return;
}
}
if (error != null) listener.error(error);
else if (cancel != null) listener.cancelled(cancel);
else listener.ready(result);
} | java | public final void listenInline(AsyncWorkListener<T,TError> listener) {
synchronized (this) {
if (!unblocked || listenersInline != null) {
if (listenersInline == null) listenersInline = new ArrayList<>(5);
listenersInline.add(listener);
return;
}
}
if (error != null) listener.error(error);
else if (cancel != null) listener.cancelled(cancel);
else listener.ready(result);
} | [
"public",
"final",
"void",
"listenInline",
"(",
"AsyncWorkListener",
"<",
"T",
",",
"TError",
">",
"listener",
")",
"{",
"synchronized",
"(",
"this",
")",
"{",
"if",
"(",
"!",
"unblocked",
"||",
"listenersInline",
"!=",
"null",
")",
"{",
"if",
"(",
"list... | Add a listener to be called when this AsyncWork is unblocked. | [
"Add",
"a",
"listener",
"to",
"be",
"called",
"when",
"this",
"AsyncWork",
"is",
"unblocked",
"."
] | train | https://github.com/lecousin/java-framework-core/blob/b0c893b44bfde2c03f90ea846a49ef5749d598f3/net.lecousin.core/src/main/java/net/lecousin/framework/concurrent/synch/AsyncWork.java#L136-L147 |
ben-manes/caffeine | caffeine/src/main/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueue.java | UnsafeRefArrayAccess.spElement | public static <E> void spElement(E[] buffer, long offset, E e) {
"""
A plain store (no ordering/fences) of an element to a given offset
@param buffer this.buffer
@param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)}
@param e an orderly kitty
"""
UNSAFE.putObject(buffer, offset, e);
} | java | public static <E> void spElement(E[] buffer, long offset, E e) {
UNSAFE.putObject(buffer, offset, e);
} | [
"public",
"static",
"<",
"E",
">",
"void",
"spElement",
"(",
"E",
"[",
"]",
"buffer",
",",
"long",
"offset",
",",
"E",
"e",
")",
"{",
"UNSAFE",
".",
"putObject",
"(",
"buffer",
",",
"offset",
",",
"e",
")",
";",
"}"
] | A plain store (no ordering/fences) of an element to a given offset
@param buffer this.buffer
@param offset computed via {@link UnsafeRefArrayAccess#calcElementOffset(long)}
@param e an orderly kitty | [
"A",
"plain",
"store",
"(",
"no",
"ordering",
"/",
"fences",
")",
"of",
"an",
"element",
"to",
"a",
"given",
"offset"
] | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/MpscGrowableArrayQueue.java#L618-L620 |
telly/MrVector | library/src/main/java/com/telly/mrvector/PathParser.java | PathParser.updateNodes | public static void updateNodes(PathDataNode[] target, PathDataNode[] source) {
"""
Update the target's data to match the source.
Before calling this, make sure canMorph(target, source) is true.
@param target The target path represented in an array of PathDataNode
@param source The source path represented in an array of PathDataNode
"""
for (int i = 0; i < source.length; i ++) {
target[i].mType = source[i].mType;
for (int j = 0; j < source[i].mParams.length; j ++) {
target[i].mParams[j] = source[i].mParams[j];
}
}
} | java | public static void updateNodes(PathDataNode[] target, PathDataNode[] source) {
for (int i = 0; i < source.length; i ++) {
target[i].mType = source[i].mType;
for (int j = 0; j < source[i].mParams.length; j ++) {
target[i].mParams[j] = source[i].mParams[j];
}
}
} | [
"public",
"static",
"void",
"updateNodes",
"(",
"PathDataNode",
"[",
"]",
"target",
",",
"PathDataNode",
"[",
"]",
"source",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"source",
".",
"length",
";",
"i",
"++",
")",
"{",
"target",
"["... | Update the target's data to match the source.
Before calling this, make sure canMorph(target, source) is true.
@param target The target path represented in an array of PathDataNode
@param source The source path represented in an array of PathDataNode | [
"Update",
"the",
"target",
"s",
"data",
"to",
"match",
"the",
"source",
".",
"Before",
"calling",
"this",
"make",
"sure",
"canMorph",
"(",
"target",
"source",
")",
"is",
"true",
"."
] | train | https://github.com/telly/MrVector/blob/846cd05ab6e57dcdc1cae28e796ac84b1d6365d5/library/src/main/java/com/telly/mrvector/PathParser.java#L119-L126 |
forge/furnace | container/src/main/java/org/jboss/forge/furnace/impl/addons/AddonStateManager.java | AddonStateManager.getAddonForView | public Addon getAddonForView(final AddonView view, final AddonId id) {
"""
Return an {@link Addon} compatible with the given {@link AddonView}, if it is already registered (this occurs when
{@link AddonView} instances share {@link Addon} sub-graphs.
"""
return lock.performLocked(LockMode.READ, new Callable<Addon>()
{
@Override
public Addon call() throws Exception
{
for (AddonVertex vertex : getCurrentGraph().getGraph().vertexSet())
{
if (vertex.getAddonId().equals(id) && vertex.getViews().contains(view))
{
return vertex.getAddon();
}
}
return null;
}
});
} | java | public Addon getAddonForView(final AddonView view, final AddonId id)
{
return lock.performLocked(LockMode.READ, new Callable<Addon>()
{
@Override
public Addon call() throws Exception
{
for (AddonVertex vertex : getCurrentGraph().getGraph().vertexSet())
{
if (vertex.getAddonId().equals(id) && vertex.getViews().contains(view))
{
return vertex.getAddon();
}
}
return null;
}
});
} | [
"public",
"Addon",
"getAddonForView",
"(",
"final",
"AddonView",
"view",
",",
"final",
"AddonId",
"id",
")",
"{",
"return",
"lock",
".",
"performLocked",
"(",
"LockMode",
".",
"READ",
",",
"new",
"Callable",
"<",
"Addon",
">",
"(",
")",
"{",
"@",
"Overri... | Return an {@link Addon} compatible with the given {@link AddonView}, if it is already registered (this occurs when
{@link AddonView} instances share {@link Addon} sub-graphs. | [
"Return",
"an",
"{"
] | train | https://github.com/forge/furnace/blob/bbe6deaa3c0d85ba43daa3e2f7d486f2dad21e0a/container/src/main/java/org/jboss/forge/furnace/impl/addons/AddonStateManager.java#L113-L130 |
wso2/transport-http | components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/listener/HttpServerChannelInitializer.java | HttpServerChannelInitializer.configureH2cPipeline | private void configureH2cPipeline(ChannelPipeline pipeline) {
"""
Configures HTTP/2 clear text pipeline.
@param pipeline the channel pipeline
"""
// Add handler to handle http2 requests without an upgrade
pipeline.addLast(new Http2WithPriorKnowledgeHandler(
interfaceId, serverName, serverConnectorFuture, this));
// Add http2 upgrade decoder and upgrade handler
final HttpServerCodec sourceCodec = new HttpServerCodec(reqSizeValidationConfig.getMaxUriLength(),
reqSizeValidationConfig.getMaxHeaderSize(),
reqSizeValidationConfig.getMaxChunkSize());
final HttpServerUpgradeHandler.UpgradeCodecFactory upgradeCodecFactory = protocol -> {
if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
return new Http2ServerUpgradeCodec(
Constants.HTTP2_SOURCE_CONNECTION_HANDLER,
new Http2SourceConnectionHandlerBuilder(
interfaceId, serverConnectorFuture, serverName, this).build());
} else {
return null;
}
};
pipeline.addLast(Constants.HTTP_SERVER_CODEC, sourceCodec);
pipeline.addLast(Constants.HTTP_COMPRESSOR, new CustomHttpContentCompressor());
if (httpTraceLogEnabled) {
pipeline.addLast(HTTP_TRACE_LOG_HANDLER,
new HttpTraceLoggingHandler(TRACE_LOG_DOWNSTREAM));
}
if (httpAccessLogEnabled) {
pipeline.addLast(HTTP_ACCESS_LOG_HANDLER, new HttpAccessLoggingHandler(ACCESS_LOG));
}
pipeline.addLast(Constants.HTTP2_UPGRADE_HANDLER,
new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory, Integer.MAX_VALUE));
/* Max size of the upgrade request is limited to 2GB. Need to see whether there is a better approach to handle
large upgrade requests. Requests will be propagated to next handlers if no upgrade has been attempted */
pipeline.addLast(Constants.HTTP2_TO_HTTP_FALLBACK_HANDLER,
new Http2ToHttpFallbackHandler(this));
} | java | private void configureH2cPipeline(ChannelPipeline pipeline) {
// Add handler to handle http2 requests without an upgrade
pipeline.addLast(new Http2WithPriorKnowledgeHandler(
interfaceId, serverName, serverConnectorFuture, this));
// Add http2 upgrade decoder and upgrade handler
final HttpServerCodec sourceCodec = new HttpServerCodec(reqSizeValidationConfig.getMaxUriLength(),
reqSizeValidationConfig.getMaxHeaderSize(),
reqSizeValidationConfig.getMaxChunkSize());
final HttpServerUpgradeHandler.UpgradeCodecFactory upgradeCodecFactory = protocol -> {
if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
return new Http2ServerUpgradeCodec(
Constants.HTTP2_SOURCE_CONNECTION_HANDLER,
new Http2SourceConnectionHandlerBuilder(
interfaceId, serverConnectorFuture, serverName, this).build());
} else {
return null;
}
};
pipeline.addLast(Constants.HTTP_SERVER_CODEC, sourceCodec);
pipeline.addLast(Constants.HTTP_COMPRESSOR, new CustomHttpContentCompressor());
if (httpTraceLogEnabled) {
pipeline.addLast(HTTP_TRACE_LOG_HANDLER,
new HttpTraceLoggingHandler(TRACE_LOG_DOWNSTREAM));
}
if (httpAccessLogEnabled) {
pipeline.addLast(HTTP_ACCESS_LOG_HANDLER, new HttpAccessLoggingHandler(ACCESS_LOG));
}
pipeline.addLast(Constants.HTTP2_UPGRADE_HANDLER,
new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory, Integer.MAX_VALUE));
/* Max size of the upgrade request is limited to 2GB. Need to see whether there is a better approach to handle
large upgrade requests. Requests will be propagated to next handlers if no upgrade has been attempted */
pipeline.addLast(Constants.HTTP2_TO_HTTP_FALLBACK_HANDLER,
new Http2ToHttpFallbackHandler(this));
} | [
"private",
"void",
"configureH2cPipeline",
"(",
"ChannelPipeline",
"pipeline",
")",
"{",
"// Add handler to handle http2 requests without an upgrade",
"pipeline",
".",
"addLast",
"(",
"new",
"Http2WithPriorKnowledgeHandler",
"(",
"interfaceId",
",",
"serverName",
",",
"server... | Configures HTTP/2 clear text pipeline.
@param pipeline the channel pipeline | [
"Configures",
"HTTP",
"/",
"2",
"clear",
"text",
"pipeline",
"."
] | train | https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/contractimpl/listener/HttpServerChannelInitializer.java#L237-L271 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java | UtilMath.getRoundedC | public static int getRoundedC(double value, int round) {
"""
Get the rounded value with ceil.
@param value The value.
@param round The round factor (must not be equal to 0).
@return The rounded value.
@throws LionEngineException If invalid argument.
"""
Check.different(round, 0);
return (int) Math.ceil(value / round) * round;
} | java | public static int getRoundedC(double value, int round)
{
Check.different(round, 0);
return (int) Math.ceil(value / round) * round;
} | [
"public",
"static",
"int",
"getRoundedC",
"(",
"double",
"value",
",",
"int",
"round",
")",
"{",
"Check",
".",
"different",
"(",
"round",
",",
"0",
")",
";",
"return",
"(",
"int",
")",
"Math",
".",
"ceil",
"(",
"value",
"/",
"round",
")",
"*",
"rou... | Get the rounded value with ceil.
@param value The value.
@param round The round factor (must not be equal to 0).
@return The rounded value.
@throws LionEngineException If invalid argument. | [
"Get",
"the",
"rounded",
"value",
"with",
"ceil",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java#L320-L325 |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.chmod | public void chmod(int permissions, String path) throws SftpStatusException,
SshException {
"""
<p>
Changes the access permissions or modes of the specified file or
directory.
</p>
<p>
Modes determine who can read, change or execute a file.
</p>
<blockquote>
<pre>
Absolute modes are octal numbers specifying the complete list of
attributes for the files; you specify attributes by OR'ing together
these bits.
0400 Individual read
0200 Individual write
0100 Individual execute (or list directory)
0040 Group read
0020 Group write
0010 Group execute
0004 Other read
0002 Other write
0001 Other execute
</pre>
</blockquote>
@param permissions
the absolute mode of the file/directory
@param path
the path to the file/directory on the remote server
@throws SftpStatusException
@throws SshException
"""
String actual = resolveRemotePath(path);
sftp.changePermissions(actual, permissions);
} | java | public void chmod(int permissions, String path) throws SftpStatusException,
SshException {
String actual = resolveRemotePath(path);
sftp.changePermissions(actual, permissions);
} | [
"public",
"void",
"chmod",
"(",
"int",
"permissions",
",",
"String",
"path",
")",
"throws",
"SftpStatusException",
",",
"SshException",
"{",
"String",
"actual",
"=",
"resolveRemotePath",
"(",
"path",
")",
";",
"sftp",
".",
"changePermissions",
"(",
"actual",
"... | <p>
Changes the access permissions or modes of the specified file or
directory.
</p>
<p>
Modes determine who can read, change or execute a file.
</p>
<blockquote>
<pre>
Absolute modes are octal numbers specifying the complete list of
attributes for the files; you specify attributes by OR'ing together
these bits.
0400 Individual read
0200 Individual write
0100 Individual execute (or list directory)
0040 Group read
0020 Group write
0010 Group execute
0004 Other read
0002 Other write
0001 Other execute
</pre>
</blockquote>
@param permissions
the absolute mode of the file/directory
@param path
the path to the file/directory on the remote server
@throws SftpStatusException
@throws SshException | [
"<p",
">",
"Changes",
"the",
"access",
"permissions",
"or",
"modes",
"of",
"the",
"specified",
"file",
"or",
"directory",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L2071-L2075 |
Alluxio/alluxio | core/server/common/src/main/java/alluxio/master/PrimarySelectorClient.java | PrimarySelectorClient.getNewCuratorClient | private CuratorFramework getNewCuratorClient() {
"""
Returns a new client for the zookeeper connection. The client is already started before
returning.
@return a new {@link CuratorFramework} client to use for leader selection
"""
CuratorFramework client = CuratorFrameworkFactory.newClient(mZookeeperAddress,
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT),
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_CONNECTION_TIMEOUT),
new ExponentialBackoffRetry(Constants.SECOND_MS, 3));
client.start();
// Sometimes, if the master crashes and restarts too quickly (faster than the zookeeper
// timeout), zookeeper thinks the new client is still an old one. In order to ensure a clean
// state, explicitly close the "old" client and recreate a new one.
client.close();
client = CuratorFrameworkFactory.newClient(mZookeeperAddress,
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT),
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_CONNECTION_TIMEOUT),
new ExponentialBackoffRetry(Constants.SECOND_MS, 3));
client.start();
return client;
} | java | private CuratorFramework getNewCuratorClient() {
CuratorFramework client = CuratorFrameworkFactory.newClient(mZookeeperAddress,
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT),
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_CONNECTION_TIMEOUT),
new ExponentialBackoffRetry(Constants.SECOND_MS, 3));
client.start();
// Sometimes, if the master crashes and restarts too quickly (faster than the zookeeper
// timeout), zookeeper thinks the new client is still an old one. In order to ensure a clean
// state, explicitly close the "old" client and recreate a new one.
client.close();
client = CuratorFrameworkFactory.newClient(mZookeeperAddress,
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_SESSION_TIMEOUT),
(int) ServerConfiguration.getMs(PropertyKey.ZOOKEEPER_CONNECTION_TIMEOUT),
new ExponentialBackoffRetry(Constants.SECOND_MS, 3));
client.start();
return client;
} | [
"private",
"CuratorFramework",
"getNewCuratorClient",
"(",
")",
"{",
"CuratorFramework",
"client",
"=",
"CuratorFrameworkFactory",
".",
"newClient",
"(",
"mZookeeperAddress",
",",
"(",
"int",
")",
"ServerConfiguration",
".",
"getMs",
"(",
"PropertyKey",
".",
"ZOOKEEPE... | Returns a new client for the zookeeper connection. The client is already started before
returning.
@return a new {@link CuratorFramework} client to use for leader selection | [
"Returns",
"a",
"new",
"client",
"for",
"the",
"zookeeper",
"connection",
".",
"The",
"client",
"is",
"already",
"started",
"before",
"returning",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/master/PrimarySelectorClient.java#L176-L193 |
dain/leveldb | leveldb/src/main/java/org/iq80/leveldb/util/Slice.java | Slice.setShort | public void setShort(int index, int value) {
"""
Sets the specified 16-bit short integer at the specified absolute
{@code index} in this buffer. The 16 high-order bits of the specified
value are ignored.
@throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or
{@code index + 2} is greater than {@code this.capacity}
"""
checkPositionIndexes(index, index + SIZE_OF_SHORT, this.length);
index += offset;
data[index] = (byte) (value);
data[index + 1] = (byte) (value >>> 8);
} | java | public void setShort(int index, int value)
{
checkPositionIndexes(index, index + SIZE_OF_SHORT, this.length);
index += offset;
data[index] = (byte) (value);
data[index + 1] = (byte) (value >>> 8);
} | [
"public",
"void",
"setShort",
"(",
"int",
"index",
",",
"int",
"value",
")",
"{",
"checkPositionIndexes",
"(",
"index",
",",
"index",
"+",
"SIZE_OF_SHORT",
",",
"this",
".",
"length",
")",
";",
"index",
"+=",
"offset",
";",
"data",
"[",
"index",
"]",
"... | Sets the specified 16-bit short integer at the specified absolute
{@code index} in this buffer. The 16 high-order bits of the specified
value are ignored.
@throws IndexOutOfBoundsException if the specified {@code index} is less than {@code 0} or
{@code index + 2} is greater than {@code this.capacity} | [
"Sets",
"the",
"specified",
"16",
"-",
"bit",
"short",
"integer",
"at",
"the",
"specified",
"absolute",
"{",
"@code",
"index",
"}",
"in",
"this",
"buffer",
".",
"The",
"16",
"high",
"-",
"order",
"bits",
"of",
"the",
"specified",
"value",
"are",
"ignored... | train | https://github.com/dain/leveldb/blob/7994065b48eada2ef29e7fefd172c2ad1e0110eb/leveldb/src/main/java/org/iq80/leveldb/util/Slice.java#L294-L300 |
sarl/sarl | main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/externalspec/pygments/PygmentsGenerator2.java | PygmentsGenerator2.generatePythonPackage | protected void generatePythonPackage(IStyleAppendable it, String basename) {
"""
Create the content of the "__init__.py" file.
@param it the content.
@param basename the basename.
"""
it.appendNl("# -*- coding: {0} -*-", getCodeConfig().getEncoding().toLowerCase()); //$NON-NLS-1$
it.appendHeader();
it.newLine();
it.append("__all__ = [ ]"); //$NON-NLS-1$
it.newLine();
} | java | protected void generatePythonPackage(IStyleAppendable it, String basename) {
it.appendNl("# -*- coding: {0} -*-", getCodeConfig().getEncoding().toLowerCase()); //$NON-NLS-1$
it.appendHeader();
it.newLine();
it.append("__all__ = [ ]"); //$NON-NLS-1$
it.newLine();
} | [
"protected",
"void",
"generatePythonPackage",
"(",
"IStyleAppendable",
"it",
",",
"String",
"basename",
")",
"{",
"it",
".",
"appendNl",
"(",
"\"# -*- coding: {0} -*-\"",
",",
"getCodeConfig",
"(",
")",
".",
"getEncoding",
"(",
")",
".",
"toLowerCase",
"(",
")",... | Create the content of the "__init__.py" file.
@param it the content.
@param basename the basename. | [
"Create",
"the",
"content",
"of",
"the",
"__init__",
".",
"py",
"file",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/externalspec/pygments/PygmentsGenerator2.java#L288-L294 |
glyptodon/guacamole-client | extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/AuthenticationProviderService.java | AuthenticationProviderService.getAttributeTokens | private Map<String, String> getAttributeTokens(LDAPConnection ldapConnection,
String username) throws GuacamoleException {
"""
Returns parameter tokens generated from LDAP attributes on the user
currently bound under the given LDAP connection. The attributes to be
converted into parameter tokens must be explicitly listed in
guacamole.properties. If no attributes are specified or none are
found on the LDAP user object, an empty map is returned.
@param ldapConnection
LDAP connection to use to read the attributes of the user.
@param username
The username of the user whose attributes are to be queried.
@return
A map of parameter tokens generated from attributes on the user
currently bound under the given LDAP connection, as a map of token
name to corresponding value, or an empty map if no attributes are
specified or none are found on the user object.
@throws GuacamoleException
If an error occurs retrieving the user DN or the attributes.
"""
// Get attributes from configuration information
List<String> attrList = confService.getAttributes();
// If there are no attributes there is no reason to search LDAP
if (attrList.isEmpty())
return Collections.<String, String>emptyMap();
// Build LDAP query parameters
String[] attrArray = attrList.toArray(new String[attrList.size()]);
String userDN = getUserBindDN(username);
Map<String, String> tokens = new HashMap<String, String>();
try {
// Get LDAP attributes by querying LDAP
LDAPEntry userEntry = ldapConnection.read(userDN, attrArray);
if (userEntry == null)
return Collections.<String, String>emptyMap();
LDAPAttributeSet attrSet = userEntry.getAttributeSet();
if (attrSet == null)
return Collections.<String, String>emptyMap();
// Convert each retrieved attribute into a corresponding token
for (Object attrObj : attrSet) {
LDAPAttribute attr = (LDAPAttribute)attrObj;
tokens.put(TokenName.fromAttribute(attr.getName()), attr.getStringValue());
}
}
catch (LDAPException e) {
throw new GuacamoleServerException("Could not query LDAP user attributes.", e);
}
return tokens;
} | java | private Map<String, String> getAttributeTokens(LDAPConnection ldapConnection,
String username) throws GuacamoleException {
// Get attributes from configuration information
List<String> attrList = confService.getAttributes();
// If there are no attributes there is no reason to search LDAP
if (attrList.isEmpty())
return Collections.<String, String>emptyMap();
// Build LDAP query parameters
String[] attrArray = attrList.toArray(new String[attrList.size()]);
String userDN = getUserBindDN(username);
Map<String, String> tokens = new HashMap<String, String>();
try {
// Get LDAP attributes by querying LDAP
LDAPEntry userEntry = ldapConnection.read(userDN, attrArray);
if (userEntry == null)
return Collections.<String, String>emptyMap();
LDAPAttributeSet attrSet = userEntry.getAttributeSet();
if (attrSet == null)
return Collections.<String, String>emptyMap();
// Convert each retrieved attribute into a corresponding token
for (Object attrObj : attrSet) {
LDAPAttribute attr = (LDAPAttribute)attrObj;
tokens.put(TokenName.fromAttribute(attr.getName()), attr.getStringValue());
}
}
catch (LDAPException e) {
throw new GuacamoleServerException("Could not query LDAP user attributes.", e);
}
return tokens;
} | [
"private",
"Map",
"<",
"String",
",",
"String",
">",
"getAttributeTokens",
"(",
"LDAPConnection",
"ldapConnection",
",",
"String",
"username",
")",
"throws",
"GuacamoleException",
"{",
"// Get attributes from configuration information",
"List",
"<",
"String",
">",
"attr... | Returns parameter tokens generated from LDAP attributes on the user
currently bound under the given LDAP connection. The attributes to be
converted into parameter tokens must be explicitly listed in
guacamole.properties. If no attributes are specified or none are
found on the LDAP user object, an empty map is returned.
@param ldapConnection
LDAP connection to use to read the attributes of the user.
@param username
The username of the user whose attributes are to be queried.
@return
A map of parameter tokens generated from attributes on the user
currently bound under the given LDAP connection, as a map of token
name to corresponding value, or an empty map if no attributes are
specified or none are found on the user object.
@throws GuacamoleException
If an error occurs retrieving the user DN or the attributes. | [
"Returns",
"parameter",
"tokens",
"generated",
"from",
"LDAP",
"attributes",
"on",
"the",
"user",
"currently",
"bound",
"under",
"the",
"given",
"LDAP",
"connection",
".",
"The",
"attributes",
"to",
"be",
"converted",
"into",
"parameter",
"tokens",
"must",
"be",... | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/AuthenticationProviderService.java#L283-L322 |
dnsjava/dnsjava | org/xbill/DNS/Cache.java | Cache.findRecords | public RRset []
findRecords(Name name, int type) {
"""
Looks up credible Records in the Cache (a wrapper around lookupRecords).
Unlike lookupRecords, this given no indication of why failure occurred.
@param name The name to look up
@param type The type to look up
@return An array of RRsets, or null
@see Credibility
"""
return findRecords(name, type, Credibility.NORMAL);
} | java | public RRset []
findRecords(Name name, int type) {
return findRecords(name, type, Credibility.NORMAL);
} | [
"public",
"RRset",
"[",
"]",
"findRecords",
"(",
"Name",
"name",
",",
"int",
"type",
")",
"{",
"return",
"findRecords",
"(",
"name",
",",
"type",
",",
"Credibility",
".",
"NORMAL",
")",
";",
"}"
] | Looks up credible Records in the Cache (a wrapper around lookupRecords).
Unlike lookupRecords, this given no indication of why failure occurred.
@param name The name to look up
@param type The type to look up
@return An array of RRsets, or null
@see Credibility | [
"Looks",
"up",
"credible",
"Records",
"in",
"the",
"Cache",
"(",
"a",
"wrapper",
"around",
"lookupRecords",
")",
".",
"Unlike",
"lookupRecords",
"this",
"given",
"no",
"indication",
"of",
"why",
"failure",
"occurred",
"."
] | train | https://github.com/dnsjava/dnsjava/blob/d97b6a0685d59143372bb392ab591dd8dd840b61/org/xbill/DNS/Cache.java#L533-L536 |
Azure/azure-sdk-for-java | hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java | ExtensionsInner.enableMonitoringAsync | public Observable<Void> enableMonitoringAsync(String resourceGroupName, String clusterName, ClusterMonitoringRequest parameters) {
"""
Enables the Operations Management Suite (OMS) on the HDInsight cluster.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param parameters The Operations Management Suite (OMS) workspace parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return enableMonitoringWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> enableMonitoringAsync(String resourceGroupName, String clusterName, ClusterMonitoringRequest parameters) {
return enableMonitoringWithServiceResponseAsync(resourceGroupName, clusterName, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"enableMonitoringAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"ClusterMonitoringRequest",
"parameters",
")",
"{",
"return",
"enableMonitoringWithServiceResponseAsync",
"(",
"resourceGroupName",
",",... | Enables the Operations Management Suite (OMS) on the HDInsight cluster.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@param parameters The Operations Management Suite (OMS) workspace parameters.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Enables",
"the",
"Operations",
"Management",
"Suite",
"(",
"OMS",
")",
"on",
"the",
"HDInsight",
"cluster",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ExtensionsInner.java#L138-L145 |
VoltDB/voltdb | src/hsqldb19b3/org/hsqldb_voltpatches/lib/DoubleIntIndex.java | DoubleIntIndex.setValue | public synchronized void setValue(int i, int value) {
"""
Modifies an existing pair.
@param i the index
@param value the value
"""
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
if (sortOnValues) {
sorted = false;
}
values[i] = value;
} | java | public synchronized void setValue(int i, int value) {
if (i < 0 || i >= count) {
throw new IndexOutOfBoundsException();
}
if (sortOnValues) {
sorted = false;
}
values[i] = value;
} | [
"public",
"synchronized",
"void",
"setValue",
"(",
"int",
"i",
",",
"int",
"value",
")",
"{",
"if",
"(",
"i",
"<",
"0",
"||",
"i",
">=",
"count",
")",
"{",
"throw",
"new",
"IndexOutOfBoundsException",
"(",
")",
";",
"}",
"if",
"(",
"sortOnValues",
")... | Modifies an existing pair.
@param i the index
@param value the value | [
"Modifies",
"an",
"existing",
"pair",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/DoubleIntIndex.java#L117-L128 |
looly/hutool | hutool-log/src/main/java/cn/hutool/log/dialect/slf4j/Slf4jLog.java | Slf4jLog.locationAwareLog | private boolean locationAwareLog(int level_int, String msgTemplate, Object[] arguments) {
"""
打印日志<br>
此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题
@param level_int 日志级别,使用LocationAwareLogger中的常量
@param msgTemplate 消息模板
@param arguments 参数
@return 是否支持 LocationAwareLogger对象,如果不支持需要日志方法调用被包装类的相应方法
"""
return locationAwareLog(level_int, null, msgTemplate, arguments);
} | java | private boolean locationAwareLog(int level_int, String msgTemplate, Object[] arguments) {
return locationAwareLog(level_int, null, msgTemplate, arguments);
} | [
"private",
"boolean",
"locationAwareLog",
"(",
"int",
"level_int",
",",
"String",
"msgTemplate",
",",
"Object",
"[",
"]",
"arguments",
")",
"{",
"return",
"locationAwareLog",
"(",
"level_int",
",",
"null",
",",
"msgTemplate",
",",
"arguments",
")",
";",
"}"
] | 打印日志<br>
此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题
@param level_int 日志级别,使用LocationAwareLogger中的常量
@param msgTemplate 消息模板
@param arguments 参数
@return 是否支持 LocationAwareLogger对象,如果不支持需要日志方法调用被包装类的相应方法 | [
"打印日志<br",
">",
"此方法用于兼容底层日志实现,通过传入当前包装类名,以解决打印日志中行号错误问题"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-log/src/main/java/cn/hutool/log/dialect/slf4j/Slf4jLog.java#L187-L189 |
looly/hutool | hutool-captcha/src/main/java/cn/hutool/captcha/CaptchaUtil.java | CaptchaUtil.createShearCaptcha | public static ShearCaptcha createShearCaptcha(int width, int height, int codeCount, int thickness) {
"""
创建扭曲干扰的验证码,默认5位验证码
@param width 图片宽
@param height 图片高
@param codeCount 字符个数
@param thickness 干扰线宽度
@return {@link ShearCaptcha}
@since 3.3.0
"""
return new ShearCaptcha(width, height, codeCount, thickness);
} | java | public static ShearCaptcha createShearCaptcha(int width, int height, int codeCount, int thickness) {
return new ShearCaptcha(width, height, codeCount, thickness);
} | [
"public",
"static",
"ShearCaptcha",
"createShearCaptcha",
"(",
"int",
"width",
",",
"int",
"height",
",",
"int",
"codeCount",
",",
"int",
"thickness",
")",
"{",
"return",
"new",
"ShearCaptcha",
"(",
"width",
",",
"height",
",",
"codeCount",
",",
"thickness",
... | 创建扭曲干扰的验证码,默认5位验证码
@param width 图片宽
@param height 图片高
@param codeCount 字符个数
@param thickness 干扰线宽度
@return {@link ShearCaptcha}
@since 3.3.0 | [
"创建扭曲干扰的验证码,默认5位验证码"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-captcha/src/main/java/cn/hutool/captcha/CaptchaUtil.java#L83-L85 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/reflect/TypeReflector.java | TypeReflector.createInstance | public static Object createInstance(String name, Object... args) throws Exception {
"""
Creates an instance of an object type specified by its name.
@param name an object type name.
@param args arguments for the object constructor.
@return the created object instance.
@throws Exception when type of instance not found
@see #getType(String, String)
@see #createInstanceByType(Class, Object...)
"""
return createInstance(name, (String) null, args);
} | java | public static Object createInstance(String name, Object... args) throws Exception {
return createInstance(name, (String) null, args);
} | [
"public",
"static",
"Object",
"createInstance",
"(",
"String",
"name",
",",
"Object",
"...",
"args",
")",
"throws",
"Exception",
"{",
"return",
"createInstance",
"(",
"name",
",",
"(",
"String",
")",
"null",
",",
"args",
")",
";",
"}"
] | Creates an instance of an object type specified by its name.
@param name an object type name.
@param args arguments for the object constructor.
@return the created object instance.
@throws Exception when type of instance not found
@see #getType(String, String)
@see #createInstanceByType(Class, Object...) | [
"Creates",
"an",
"instance",
"of",
"an",
"object",
"type",
"specified",
"by",
"its",
"name",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/reflect/TypeReflector.java#L133-L135 |
Coveros/selenified | src/main/java/com/coveros/selenified/Selenified.java | Selenified.setAuthor | protected static void setAuthor(Selenified clazz, ITestContext context, String author) {
"""
Sets the author of the current test suite being executed.
@param clazz - the test suite class, used for making threadsafe storage of
application, allowing suites to have independent applications
under test, run at the same time
@param context - the TestNG context associated with the test suite, used for
storing app url information
@param author - the author of the test suite
"""
context.setAttribute(clazz.getClass().getName() + "Author", author);
} | java | protected static void setAuthor(Selenified clazz, ITestContext context, String author) {
context.setAttribute(clazz.getClass().getName() + "Author", author);
} | [
"protected",
"static",
"void",
"setAuthor",
"(",
"Selenified",
"clazz",
",",
"ITestContext",
"context",
",",
"String",
"author",
")",
"{",
"context",
".",
"setAttribute",
"(",
"clazz",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"Author\"",
... | Sets the author of the current test suite being executed.
@param clazz - the test suite class, used for making threadsafe storage of
application, allowing suites to have independent applications
under test, run at the same time
@param context - the TestNG context associated with the test suite, used for
storing app url information
@param author - the author of the test suite | [
"Sets",
"the",
"author",
"of",
"the",
"current",
"test",
"suite",
"being",
"executed",
"."
] | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/Selenified.java#L164-L166 |
Azure/azure-sdk-for-java | kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java | DatabasesInner.beginCreateOrUpdate | public DatabaseInner beginCreateOrUpdate(String resourceGroupName, String clusterName, String databaseName, DatabaseInner parameters) {
"""
Creates or updates a database.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@param databaseName The name of the database in the Kusto cluster.
@param parameters The database parameters supplied to the CreateOrUpdate operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DatabaseInner object if successful.
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, parameters).toBlocking().single().body();
} | java | public DatabaseInner beginCreateOrUpdate(String resourceGroupName, String clusterName, String databaseName, DatabaseInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, clusterName, databaseName, parameters).toBlocking().single().body();
} | [
"public",
"DatabaseInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
",",
"String",
"databaseName",
",",
"DatabaseInner",
"parameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
... | Creates or updates a database.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@param databaseName The name of the database in the Kusto cluster.
@param parameters The database parameters supplied to the CreateOrUpdate operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DatabaseInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"database",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/DatabasesInner.java#L489-L491 |
lessthanoptimal/ejml | main/ejml-simple/src/org/ejml/equation/Equation.java | Equation.process | public Equation process( String equation , boolean debug ) {
"""
Compiles and performs the provided equation.
@param equation String in simple equation format
"""
compile(equation,true,debug).perform();
return this;
} | java | public Equation process( String equation , boolean debug ) {
compile(equation,true,debug).perform();
return this;
} | [
"public",
"Equation",
"process",
"(",
"String",
"equation",
",",
"boolean",
"debug",
")",
"{",
"compile",
"(",
"equation",
",",
"true",
",",
"debug",
")",
".",
"perform",
"(",
")",
";",
"return",
"this",
";",
"}"
] | Compiles and performs the provided equation.
@param equation String in simple equation format | [
"Compiles",
"and",
"performs",
"the",
"provided",
"equation",
"."
] | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-simple/src/org/ejml/equation/Equation.java#L1670-L1673 |
Netflix/conductor | mysql-persistence/src/main/java/com/netflix/conductor/dao/mysql/Query.java | Query.executeQuery | public ResultSet executeQuery() {
"""
Execute a query from the PreparedStatement and return the ResultSet.
<p>
<em>NOTE:</em> The returned ResultSet must be closed/managed by the calling methods.
@return {@link PreparedStatement#executeQuery()}
@throws ApplicationException If any SQL errors occur.
"""
Long start = null;
if (logger.isTraceEnabled()) {
start = System.currentTimeMillis();
}
try {
return this.statement.executeQuery();
} catch (SQLException ex) {
throw new ApplicationException(Code.BACKEND_ERROR, ex);
} finally {
if (null != start && logger.isTraceEnabled()) {
long end = System.currentTimeMillis();
logger.trace("[{}ms] {}", (end - start), rawQuery);
}
}
} | java | public ResultSet executeQuery(){
Long start = null;
if (logger.isTraceEnabled()) {
start = System.currentTimeMillis();
}
try {
return this.statement.executeQuery();
} catch (SQLException ex) {
throw new ApplicationException(Code.BACKEND_ERROR, ex);
} finally {
if (null != start && logger.isTraceEnabled()) {
long end = System.currentTimeMillis();
logger.trace("[{}ms] {}", (end - start), rawQuery);
}
}
} | [
"public",
"ResultSet",
"executeQuery",
"(",
")",
"{",
"Long",
"start",
"=",
"null",
";",
"if",
"(",
"logger",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"start",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"}",
"try",
"{",
"return",
"this",... | Execute a query from the PreparedStatement and return the ResultSet.
<p>
<em>NOTE:</em> The returned ResultSet must be closed/managed by the calling methods.
@return {@link PreparedStatement#executeQuery()}
@throws ApplicationException If any SQL errors occur. | [
"Execute",
"a",
"query",
"from",
"the",
"PreparedStatement",
"and",
"return",
"the",
"ResultSet",
".",
"<p",
">"
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/mysql-persistence/src/main/java/com/netflix/conductor/dao/mysql/Query.java#L290-L306 |
thymeleaf/thymeleaf | src/main/java/org/thymeleaf/expression/Uris.java | Uris.escapeQueryParam | public String escapeQueryParam(final String text, final String encoding) {
"""
<p>
Perform am URI query parameter (name or value) <strong>escape</strong> operation
on a {@code String} input.
</p>
<p>
This method simply calls the equivalent method in the {@code UriEscape} class from the
<a href="http://www.unbescape.org">Unbescape</a> library.
</p>
<p>
The following are the only allowed chars in an URI query parameter (will not be escaped):
</p>
<ul>
<li>{@code A-Z a-z 0-9}</li>
<li>{@code - . _ ~}</li>
<li>{@code ! $ ' ( ) * , ;}</li>
<li>{@code : @}</li>
<li>{@code / ?}</li>
</ul>
<p>
All other chars will be escaped by converting them to the sequence of bytes that
represents them in the specified <em>encoding</em> and then representing each byte
in {@code %HH} syntax, being {@code HH} the hexadecimal representation of the byte.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the {@code String} to be escaped.
@param encoding the encoding to be used for escaping.
@return The escaped result {@code String}. As a memory-performance improvement, will return the exact
same object as the {@code text} input argument if no escaping modifications were required (and
no additional {@code String} objects will be created during processing). Will
return {@code null} if {@code text} is {@code null}.
"""
return UriEscape.escapeUriQueryParam(text, encoding);
} | java | public String escapeQueryParam(final String text, final String encoding) {
return UriEscape.escapeUriQueryParam(text, encoding);
} | [
"public",
"String",
"escapeQueryParam",
"(",
"final",
"String",
"text",
",",
"final",
"String",
"encoding",
")",
"{",
"return",
"UriEscape",
".",
"escapeUriQueryParam",
"(",
"text",
",",
"encoding",
")",
";",
"}"
] | <p>
Perform am URI query parameter (name or value) <strong>escape</strong> operation
on a {@code String} input.
</p>
<p>
This method simply calls the equivalent method in the {@code UriEscape} class from the
<a href="http://www.unbescape.org">Unbescape</a> library.
</p>
<p>
The following are the only allowed chars in an URI query parameter (will not be escaped):
</p>
<ul>
<li>{@code A-Z a-z 0-9}</li>
<li>{@code - . _ ~}</li>
<li>{@code ! $ ' ( ) * , ;}</li>
<li>{@code : @}</li>
<li>{@code / ?}</li>
</ul>
<p>
All other chars will be escaped by converting them to the sequence of bytes that
represents them in the specified <em>encoding</em> and then representing each byte
in {@code %HH} syntax, being {@code HH} the hexadecimal representation of the byte.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the {@code String} to be escaped.
@param encoding the encoding to be used for escaping.
@return The escaped result {@code String}. As a memory-performance improvement, will return the exact
same object as the {@code text} input argument if no escaping modifications were required (and
no additional {@code String} objects will be created during processing). Will
return {@code null} if {@code text} is {@code null}. | [
"<p",
">",
"Perform",
"am",
"URI",
"query",
"parameter",
"(",
"name",
"or",
"value",
")",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"{",
"@code",
"String",
"}",
"input",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"meth... | train | https://github.com/thymeleaf/thymeleaf/blob/2b0e6d6d7571fbe638904b5fd222fc9e77188879/src/main/java/org/thymeleaf/expression/Uris.java#L589-L591 |
ddf-project/DDF | core/src/main/java/io/ddf/DDF.java | DDF.validateSchema | private void validateSchema(Schema schema) throws DDFException {
"""
////// MetaData that deserves to be right here at the top level ////////
"""
Set<String> columnSet = new HashSet<String>();
if(schema != null && schema.getColumns() != null) {
for (Column column : schema.getColumns()) {
if (columnSet.contains(column.getName())) {
throw new DDFException(String.format("Duplicated column name %s", column.getName()));
} else {
columnSet.add(column.getName());
}
}
}
} | java | private void validateSchema(Schema schema) throws DDFException {
Set<String> columnSet = new HashSet<String>();
if(schema != null && schema.getColumns() != null) {
for (Column column : schema.getColumns()) {
if (columnSet.contains(column.getName())) {
throw new DDFException(String.format("Duplicated column name %s", column.getName()));
} else {
columnSet.add(column.getName());
}
}
}
} | [
"private",
"void",
"validateSchema",
"(",
"Schema",
"schema",
")",
"throws",
"DDFException",
"{",
"Set",
"<",
"String",
">",
"columnSet",
"=",
"new",
"HashSet",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
"schema",
"!=",
"null",
"&&",
"schema",
".",
... | ////// MetaData that deserves to be right here at the top level //////// | [
"//////",
"MetaData",
"that",
"deserves",
"to",
"be",
"right",
"here",
"at",
"the",
"top",
"level",
"////////"
] | train | https://github.com/ddf-project/DDF/blob/e4e68315dcec1ed8b287bf1ee73baa88e7e41eba/core/src/main/java/io/ddf/DDF.java#L296-L307 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WPartialDateField.java | WPartialDateField.handleRequestValue | protected void handleRequestValue(final String value, final boolean valid, final String text) {
"""
Set the request value.
@param value the date value
@param valid true if valid value
@param text the user text
"""
// As setData() clears the text value (if valid), this must be called first so it can be set after
setData(value);
PartialDateFieldModel model = getOrCreateComponentModel();
model.validDate = valid;
model.text = text;
} | java | protected void handleRequestValue(final String value, final boolean valid, final String text) {
// As setData() clears the text value (if valid), this must be called first so it can be set after
setData(value);
PartialDateFieldModel model = getOrCreateComponentModel();
model.validDate = valid;
model.text = text;
} | [
"protected",
"void",
"handleRequestValue",
"(",
"final",
"String",
"value",
",",
"final",
"boolean",
"valid",
",",
"final",
"String",
"text",
")",
"{",
"// As setData() clears the text value (if valid), this must be called first so it can be set after",
"setData",
"(",
"value... | Set the request value.
@param value the date value
@param valid true if valid value
@param text the user text | [
"Set",
"the",
"request",
"value",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/WPartialDateField.java#L334-L340 |
Azure/azure-sdk-for-java | sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServerAzureADAdministratorsInner.java | ServerAzureADAdministratorsInner.beginDeleteAsync | public Observable<ServerAzureADAdministratorInner> beginDeleteAsync(String resourceGroupName, String serverName) {
"""
Deletes an existing server Active Directory Administrator.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ServerAzureADAdministratorInner object
"""
return beginDeleteWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<ServerAzureADAdministratorInner>, ServerAzureADAdministratorInner>() {
@Override
public ServerAzureADAdministratorInner call(ServiceResponse<ServerAzureADAdministratorInner> response) {
return response.body();
}
});
} | java | public Observable<ServerAzureADAdministratorInner> beginDeleteAsync(String resourceGroupName, String serverName) {
return beginDeleteWithServiceResponseAsync(resourceGroupName, serverName).map(new Func1<ServiceResponse<ServerAzureADAdministratorInner>, ServerAzureADAdministratorInner>() {
@Override
public ServerAzureADAdministratorInner call(ServiceResponse<ServerAzureADAdministratorInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ServerAzureADAdministratorInner",
">",
"beginDeleteAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
")",
"{",
"return",
"beginDeleteWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"serverName",
")",
".",
"map... | Deletes an existing server Active Directory Administrator.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ServerAzureADAdministratorInner object | [
"Deletes",
"an",
"existing",
"server",
"Active",
"Directory",
"Administrator",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServerAzureADAdministratorsInner.java#L366-L373 |
tzaeschke/zoodb | src/org/zoodb/internal/util/FormattedStringBuilder.java | FormattedStringBuilder.fillOrCut | public FormattedStringBuilder fillOrCut(int newLength, char c) {
"""
Attempts to append <tt>c</tt> until the line gets the length <tt>
newLength</tt>. If the line is already longer than <tt>newLength</tt>,
then the internal strings is cut to <tt>newLength</tt>.
@param newLength New length of the last line.
@param c Character to append.
@return The updated instance of FormattedStringBuilder.
"""
if (newLength < 0) {
throw new IllegalArgumentException();
}
int lineStart = _delegate.lastIndexOf(NL);
if (lineStart == -1) {
lineStart = 0;
} else {
lineStart += NL.length();
}
int lineLen = _delegate.length() - lineStart;
if (newLength < lineLen) {
_delegate = new StringBuilder(_delegate.substring(0, lineStart + newLength));
return this;
}
return fill(newLength, c);
} | java | public FormattedStringBuilder fillOrCut(int newLength, char c) {
if (newLength < 0) {
throw new IllegalArgumentException();
}
int lineStart = _delegate.lastIndexOf(NL);
if (lineStart == -1) {
lineStart = 0;
} else {
lineStart += NL.length();
}
int lineLen = _delegate.length() - lineStart;
if (newLength < lineLen) {
_delegate = new StringBuilder(_delegate.substring(0, lineStart + newLength));
return this;
}
return fill(newLength, c);
} | [
"public",
"FormattedStringBuilder",
"fillOrCut",
"(",
"int",
"newLength",
",",
"char",
"c",
")",
"{",
"if",
"(",
"newLength",
"<",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
")",
";",
"}",
"int",
"lineStart",
"=",
"_delegate",
".",
"la... | Attempts to append <tt>c</tt> until the line gets the length <tt>
newLength</tt>. If the line is already longer than <tt>newLength</tt>,
then the internal strings is cut to <tt>newLength</tt>.
@param newLength New length of the last line.
@param c Character to append.
@return The updated instance of FormattedStringBuilder. | [
"Attempts",
"to",
"append",
"<tt",
">",
"c<",
"/",
"tt",
">",
"until",
"the",
"line",
"gets",
"the",
"length",
"<tt",
">",
"newLength<",
"/",
"tt",
">",
".",
"If",
"the",
"line",
"is",
"already",
"longer",
"than",
"<tt",
">",
"newLength<",
"/",
"tt",... | train | https://github.com/tzaeschke/zoodb/blob/058d0ff161a8ee9d53244c433aca97ee9c654410/src/org/zoodb/internal/util/FormattedStringBuilder.java#L220-L237 |
infinispan/infinispan | core/src/main/java/org/infinispan/configuration/parsing/ParseUtils.java | ParseUtils.readStringAttributeElement | public static String readStringAttributeElement(final XMLStreamReader reader, final String attributeName)
throws XMLStreamException {
"""
Read an element which contains only a single string attribute.
@param reader the reader
@param attributeName the attribute name, usually "value" or "name"
@return the string value
@throws javax.xml.stream.XMLStreamException if an error occurs or if the
element does not contain the specified attribute, contains other
attributes, or contains child elements.
"""
final String value = requireSingleAttribute(reader, attributeName);
requireNoContent(reader);
return value;
} | java | public static String readStringAttributeElement(final XMLStreamReader reader, final String attributeName)
throws XMLStreamException {
final String value = requireSingleAttribute(reader, attributeName);
requireNoContent(reader);
return value;
} | [
"public",
"static",
"String",
"readStringAttributeElement",
"(",
"final",
"XMLStreamReader",
"reader",
",",
"final",
"String",
"attributeName",
")",
"throws",
"XMLStreamException",
"{",
"final",
"String",
"value",
"=",
"requireSingleAttribute",
"(",
"reader",
",",
"at... | Read an element which contains only a single string attribute.
@param reader the reader
@param attributeName the attribute name, usually "value" or "name"
@return the string value
@throws javax.xml.stream.XMLStreamException if an error occurs or if the
element does not contain the specified attribute, contains other
attributes, or contains child elements. | [
"Read",
"an",
"element",
"which",
"contains",
"only",
"a",
"single",
"string",
"attribute",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/configuration/parsing/ParseUtils.java#L196-L201 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRTransform.java | GVRTransform.setRotation | public GVRTransform setRotation(float w, float x, float y, float z) {
"""
Set rotation, as a quaternion.
Sets the transform's current rotation in quaternion terms. Overrides any
previous rotations using {@link #rotate(float, float, float, float)
rotate()}, {@link #rotateByAxis(float, float, float, float)
rotateByAxis()} , or
{@link #rotateByAxisWithPivot(float, float, float, float, float, float, float)
rotateByAxisWithPivot()} .
@param w
'W' component of the quaternion.
@param x
'X' component of the quaternion.
@param y
'Y' component of the quaternion.
@param z
'Z' component of the quaternion.
"""
NativeTransform.setRotation(getNative(), w, x, y, z);
return this;
} | java | public GVRTransform setRotation(float w, float x, float y, float z) {
NativeTransform.setRotation(getNative(), w, x, y, z);
return this;
} | [
"public",
"GVRTransform",
"setRotation",
"(",
"float",
"w",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"NativeTransform",
".",
"setRotation",
"(",
"getNative",
"(",
")",
",",
"w",
",",
"x",
",",
"y",
",",
"z",
")",
";",
"ret... | Set rotation, as a quaternion.
Sets the transform's current rotation in quaternion terms. Overrides any
previous rotations using {@link #rotate(float, float, float, float)
rotate()}, {@link #rotateByAxis(float, float, float, float)
rotateByAxis()} , or
{@link #rotateByAxisWithPivot(float, float, float, float, float, float, float)
rotateByAxisWithPivot()} .
@param w
'W' component of the quaternion.
@param x
'X' component of the quaternion.
@param y
'Y' component of the quaternion.
@param z
'Z' component of the quaternion. | [
"Set",
"rotation",
"as",
"a",
"quaternion",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRTransform.java#L221-L224 |
Waikato/moa | moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java | MTree.getNearestByLimit | public Query getNearestByLimit(DATA queryData, int limit) {
"""
Performs a nearest-neighbors query on the M-Tree, constrained by the
number of neighbors.
@param queryData The query data object.
@param limit The maximum number of neighbors to fetch.
@return A {@link Query} object used to iterate on the results.
"""
return getNearest(queryData, Double.POSITIVE_INFINITY, limit);
} | java | public Query getNearestByLimit(DATA queryData, int limit) {
return getNearest(queryData, Double.POSITIVE_INFINITY, limit);
} | [
"public",
"Query",
"getNearestByLimit",
"(",
"DATA",
"queryData",
",",
"int",
"limit",
")",
"{",
"return",
"getNearest",
"(",
"queryData",
",",
"Double",
".",
"POSITIVE_INFINITY",
",",
"limit",
")",
";",
"}"
] | Performs a nearest-neighbors query on the M-Tree, constrained by the
number of neighbors.
@param queryData The query data object.
@param limit The maximum number of neighbors to fetch.
@return A {@link Query} object used to iterate on the results. | [
"Performs",
"a",
"nearest",
"-",
"neighbors",
"query",
"on",
"the",
"M",
"-",
"Tree",
"constrained",
"by",
"the",
"number",
"of",
"neighbors",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/outliers/utils/mtree/MTree.java#L422-L424 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.removeAt | public static <E> E removeAt(List<E> self, int index) {
"""
Modifies this list by removing the element at the specified position
in this list. Returns the removed element. Essentially an alias for
{@link List#remove(int)} but with no ambiguity for List<Integer>.
<p/>
Example:
<pre class="groovyTestCase">
def list = [1, 2, 3]
list.removeAt(1)
assert [1, 3] == list
</pre>
@param self a List
@param index the index of the element to be removed
@return the element previously at the specified position
@since 2.4.0
"""
return self.remove(index);
} | java | public static <E> E removeAt(List<E> self, int index) {
return self.remove(index);
} | [
"public",
"static",
"<",
"E",
">",
"E",
"removeAt",
"(",
"List",
"<",
"E",
">",
"self",
",",
"int",
"index",
")",
"{",
"return",
"self",
".",
"remove",
"(",
"index",
")",
";",
"}"
] | Modifies this list by removing the element at the specified position
in this list. Returns the removed element. Essentially an alias for
{@link List#remove(int)} but with no ambiguity for List<Integer>.
<p/>
Example:
<pre class="groovyTestCase">
def list = [1, 2, 3]
list.removeAt(1)
assert [1, 3] == list
</pre>
@param self a List
@param index the index of the element to be removed
@return the element previously at the specified position
@since 2.4.0 | [
"Modifies",
"this",
"list",
"by",
"removing",
"the",
"element",
"at",
"the",
"specified",
"position",
"in",
"this",
"list",
".",
"Returns",
"the",
"removed",
"element",
".",
"Essentially",
"an",
"alias",
"for",
"{",
"@link",
"List#remove",
"(",
"int",
")",
... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L17846-L17848 |
michael-rapp/AndroidMaterialValidation | library/src/main/java/de/mrapp/android/validation/Validators.java | Validators.minLength | public static Validator<CharSequence> minLength(@NonNull final Context context,
final int minLength) {
"""
Creates and returns a validator, which allows to validate texts to ensure, that they have at
least a specific length.
@param context
The context, which should be used to retrieve the error message, as an instance of
the class {@link Context}. The context may not be null
@param minLength
The minimum length a text must have as an {@link Integer} value. The minimum length
must be at least 1
@return @return The validator, which has been created, as an instance of the type {@link
Validator}
"""
return new MinLengthValidator(context, R.string.default_error_message, minLength);
} | java | public static Validator<CharSequence> minLength(@NonNull final Context context,
final int minLength) {
return new MinLengthValidator(context, R.string.default_error_message, minLength);
} | [
"public",
"static",
"Validator",
"<",
"CharSequence",
">",
"minLength",
"(",
"@",
"NonNull",
"final",
"Context",
"context",
",",
"final",
"int",
"minLength",
")",
"{",
"return",
"new",
"MinLengthValidator",
"(",
"context",
",",
"R",
".",
"string",
".",
"defa... | Creates and returns a validator, which allows to validate texts to ensure, that they have at
least a specific length.
@param context
The context, which should be used to retrieve the error message, as an instance of
the class {@link Context}. The context may not be null
@param minLength
The minimum length a text must have as an {@link Integer} value. The minimum length
must be at least 1
@return @return The validator, which has been created, as an instance of the type {@link
Validator} | [
"Creates",
"and",
"returns",
"a",
"validator",
"which",
"allows",
"to",
"validate",
"texts",
"to",
"ensure",
"that",
"they",
"have",
"at",
"least",
"a",
"specific",
"length",
"."
] | train | https://github.com/michael-rapp/AndroidMaterialValidation/blob/ac8693baeac7abddf2e38a47da4c1849d4661a8b/library/src/main/java/de/mrapp/android/validation/Validators.java#L444-L447 |
Azure/azure-sdk-for-java | authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleAssignmentsInner.java | RoleAssignmentsInner.createByIdAsync | public ServiceFuture<RoleAssignmentInner> createByIdAsync(String roleAssignmentId, RoleAssignmentProperties properties, final ServiceCallback<RoleAssignmentInner> serviceCallback) {
"""
Creates a role assignment by ID.
@param roleAssignmentId The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}.
@param properties Role assignment properties.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object
"""
return ServiceFuture.fromResponse(createByIdWithServiceResponseAsync(roleAssignmentId, properties), serviceCallback);
} | java | public ServiceFuture<RoleAssignmentInner> createByIdAsync(String roleAssignmentId, RoleAssignmentProperties properties, final ServiceCallback<RoleAssignmentInner> serviceCallback) {
return ServiceFuture.fromResponse(createByIdWithServiceResponseAsync(roleAssignmentId, properties), serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"RoleAssignmentInner",
">",
"createByIdAsync",
"(",
"String",
"roleAssignmentId",
",",
"RoleAssignmentProperties",
"properties",
",",
"final",
"ServiceCallback",
"<",
"RoleAssignmentInner",
">",
"serviceCallback",
")",
"{",
"return",
"Servi... | Creates a role assignment by ID.
@param roleAssignmentId The fully qualified ID of the role assignment, including the scope, resource name and resource type. Use the format, /{scope}/providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}. Example: /subscriptions/{subId}/resourcegroups/{rgname}//providers/Microsoft.Authorization/roleAssignments/{roleAssignmentName}.
@param properties Role assignment properties.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Creates",
"a",
"role",
"assignment",
"by",
"ID",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleAssignmentsInner.java#L1006-L1008 |
lucee/Lucee | core/src/main/java/lucee/runtime/op/Caster.java | Caster.toNull | public static Object toNull(Object value) throws PageException {
"""
casts a Object to null
@param value
@return to null from Object
@throws PageException
"""
if (value == null) return null;
if (value instanceof String && Caster.toString(value).trim().length() == 0) return null;
if (value instanceof Number && ((Number) value).intValue() == 0) return null;
throw new CasterException(value, "null");
} | java | public static Object toNull(Object value) throws PageException {
if (value == null) return null;
if (value instanceof String && Caster.toString(value).trim().length() == 0) return null;
if (value instanceof Number && ((Number) value).intValue() == 0) return null;
throw new CasterException(value, "null");
} | [
"public",
"static",
"Object",
"toNull",
"(",
"Object",
"value",
")",
"throws",
"PageException",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"value",
"instanceof",
"String",
"&&",
"Caster",
".",
"toString",
"(",
"value",
... | casts a Object to null
@param value
@return to null from Object
@throws PageException | [
"casts",
"a",
"Object",
"to",
"null"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/op/Caster.java#L4414-L4419 |
aws/aws-sdk-java | aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java | StepFunctionBuilder.lt | public static TimestampLessThanCondition.Builder lt(String variable, Date expectedValue) {
"""
Binary condition for Timestamp less than comparison. Dates are converted to ISO8601 UTC timestamps.
@param variable The JSONPath expression that determines which piece of the input document is used for the comparison.
@param expectedValue The expected value for this condition.
@see <a href="https://states-language.net/spec.html#choice-state">https://states-language.net/spec.html#choice-state</a>
@see com.amazonaws.services.stepfunctions.builder.states.Choice
"""
return TimestampLessThanCondition.builder().variable(variable).expectedValue(expectedValue);
} | java | public static TimestampLessThanCondition.Builder lt(String variable, Date expectedValue) {
return TimestampLessThanCondition.builder().variable(variable).expectedValue(expectedValue);
} | [
"public",
"static",
"TimestampLessThanCondition",
".",
"Builder",
"lt",
"(",
"String",
"variable",
",",
"Date",
"expectedValue",
")",
"{",
"return",
"TimestampLessThanCondition",
".",
"builder",
"(",
")",
".",
"variable",
"(",
"variable",
")",
".",
"expectedValue"... | Binary condition for Timestamp less than comparison. Dates are converted to ISO8601 UTC timestamps.
@param variable The JSONPath expression that determines which piece of the input document is used for the comparison.
@param expectedValue The expected value for this condition.
@see <a href="https://states-language.net/spec.html#choice-state">https://states-language.net/spec.html#choice-state</a>
@see com.amazonaws.services.stepfunctions.builder.states.Choice | [
"Binary",
"condition",
"for",
"Timestamp",
"less",
"than",
"comparison",
".",
"Dates",
"are",
"converted",
"to",
"ISO8601",
"UTC",
"timestamps",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-stepfunctions/src/main/java/com/amazonaws/services/stepfunctions/builder/StepFunctionBuilder.java#L404-L406 |
teatrove/teatrove | trove/src/main/java/org/teatrove/trove/classfile/MethodUtils.java | MethodUtils.addMethods | private static void addMethods(Set<MethodEntry> methods,
Class<?> clazz, Map<String, Class<?>> types,
Class<?> parent) {
"""
Recursive method that adds all applicable methods for the given class,
which is expected to be an interface. The tree is walked for the class
and all super interfaces in recursive fashion to get each available
method. Any method that is already defined by the given parent will be
ignored. Otherwise, the method, including any required bridged methods
will be added. The specified list of types define the optional type
parameters of the given interface class. These types will propogate up
the tree as necessary for any super-interfaces that match.
@param methods The set of existing methods
@param clazz The current interface class
@param types The set of named type variable
@param parent The optional parent class
"""
// validate interface
if (!clazz.isInterface()) {
throw new IllegalStateException("class must be interface: " + clazz);
}
// loop through each method (only those declared)
for (Method method : clazz.getDeclaredMethods()) {
addMethods(methods, clazz, types, parent, method);
}
// recursively add each super interface providing type info if valid
addParentMethods(methods, clazz, types, parent, null);
} | java | private static void addMethods(Set<MethodEntry> methods,
Class<?> clazz, Map<String, Class<?>> types,
Class<?> parent) {
// validate interface
if (!clazz.isInterface()) {
throw new IllegalStateException("class must be interface: " + clazz);
}
// loop through each method (only those declared)
for (Method method : clazz.getDeclaredMethods()) {
addMethods(methods, clazz, types, parent, method);
}
// recursively add each super interface providing type info if valid
addParentMethods(methods, clazz, types, parent, null);
} | [
"private",
"static",
"void",
"addMethods",
"(",
"Set",
"<",
"MethodEntry",
">",
"methods",
",",
"Class",
"<",
"?",
">",
"clazz",
",",
"Map",
"<",
"String",
",",
"Class",
"<",
"?",
">",
">",
"types",
",",
"Class",
"<",
"?",
">",
"parent",
")",
"{",
... | Recursive method that adds all applicable methods for the given class,
which is expected to be an interface. The tree is walked for the class
and all super interfaces in recursive fashion to get each available
method. Any method that is already defined by the given parent will be
ignored. Otherwise, the method, including any required bridged methods
will be added. The specified list of types define the optional type
parameters of the given interface class. These types will propogate up
the tree as necessary for any super-interfaces that match.
@param methods The set of existing methods
@param clazz The current interface class
@param types The set of named type variable
@param parent The optional parent class | [
"Recursive",
"method",
"that",
"adds",
"all",
"applicable",
"methods",
"for",
"the",
"given",
"class",
"which",
"is",
"expected",
"to",
"be",
"an",
"interface",
".",
"The",
"tree",
"is",
"walked",
"for",
"the",
"class",
"and",
"all",
"super",
"interfaces",
... | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/MethodUtils.java#L330-L346 |
metafacture/metafacture-core | metafacture-formeta/src/main/java/org/metafacture/formeta/parser/FormetaParser.java | FormetaParser.getErrorSnippet | private static String getErrorSnippet(final String record, final int pos) {
"""
Extracts a text snippet from the record for showing the position at
which an error occurred. The exact position additionally highlighted
with {@link POS_MARKER_LEFT} and {@link POS_MARKER_RIGHT}.
@param record the record currently being parsed
@param pos the position at which the error occurred
@return a text snippet.
"""
final StringBuilder snippet = new StringBuilder();
final int start = pos - SNIPPET_SIZE / 2;
if (start < 0) {
snippet.append(record.substring(0, pos));
} else {
snippet.append(SNIPPET_ELLIPSIS);
snippet.append(record.substring(start, pos));
}
snippet.append(POS_MARKER_LEFT);
snippet.append(record.charAt(pos));
snippet.append(POS_MARKER_RIGHT);
if (pos + 1 < record.length()) {
final int end = pos + SNIPPET_SIZE / 2;
if (end > record.length()) {
snippet.append(record.substring(pos + 1));
} else {
snippet.append(record.substring(pos + 1, end));
snippet.append(SNIPPET_ELLIPSIS);
}
}
return snippet.toString();
} | java | private static String getErrorSnippet(final String record, final int pos) {
final StringBuilder snippet = new StringBuilder();
final int start = pos - SNIPPET_SIZE / 2;
if (start < 0) {
snippet.append(record.substring(0, pos));
} else {
snippet.append(SNIPPET_ELLIPSIS);
snippet.append(record.substring(start, pos));
}
snippet.append(POS_MARKER_LEFT);
snippet.append(record.charAt(pos));
snippet.append(POS_MARKER_RIGHT);
if (pos + 1 < record.length()) {
final int end = pos + SNIPPET_SIZE / 2;
if (end > record.length()) {
snippet.append(record.substring(pos + 1));
} else {
snippet.append(record.substring(pos + 1, end));
snippet.append(SNIPPET_ELLIPSIS);
}
}
return snippet.toString();
} | [
"private",
"static",
"String",
"getErrorSnippet",
"(",
"final",
"String",
"record",
",",
"final",
"int",
"pos",
")",
"{",
"final",
"StringBuilder",
"snippet",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"final",
"int",
"start",
"=",
"pos",
"-",
"SNIPPET_SIZE... | Extracts a text snippet from the record for showing the position at
which an error occurred. The exact position additionally highlighted
with {@link POS_MARKER_LEFT} and {@link POS_MARKER_RIGHT}.
@param record the record currently being parsed
@param pos the position at which the error occurred
@return a text snippet. | [
"Extracts",
"a",
"text",
"snippet",
"from",
"the",
"record",
"for",
"showing",
"the",
"position",
"at",
"which",
"an",
"error",
"occurred",
".",
"The",
"exact",
"position",
"additionally",
"highlighted",
"with",
"{",
"@link",
"POS_MARKER_LEFT",
"}",
"and",
"{"... | train | https://github.com/metafacture/metafacture-core/blob/cb43933ec8eb01a4ddce4019c14b2415cc441918/metafacture-formeta/src/main/java/org/metafacture/formeta/parser/FormetaParser.java#L85-L111 |
peholmst/vaadin4spring | addons/i18n/src/main/java/org/vaadin/spring/i18n/I18N.java | I18N.getWithDefault | public String getWithDefault(String code, Locale locale, String defaultMessage, Object... arguments) {
"""
Tries to resolve the specified message for the given locale.
@param code the code to lookup up, such as 'calculator.noRateSet', never {@code null}.
@param locale The Locale for which it is tried to look up the code. Must not be null
@param defaultMessage string to return if the lookup fails, never {@code null}.
@param arguments Array of arguments that will be filled in for params within the message (params look like "{0}",
"{1,date}", "{2,time}"), or {@code null} if none.
@return the resolved message, or the {@code defaultMessage} if the lookup fails.
"""
if (locale == null) {
throw new IllegalArgumentException("Locale must not be null");
}
try {
return getMessage(code, locale, arguments);
} catch (NoSuchMessageException ex) {
return defaultMessage;
}
} | java | public String getWithDefault(String code, Locale locale, String defaultMessage, Object... arguments) {
if (locale == null) {
throw new IllegalArgumentException("Locale must not be null");
}
try {
return getMessage(code, locale, arguments);
} catch (NoSuchMessageException ex) {
return defaultMessage;
}
} | [
"public",
"String",
"getWithDefault",
"(",
"String",
"code",
",",
"Locale",
"locale",
",",
"String",
"defaultMessage",
",",
"Object",
"...",
"arguments",
")",
"{",
"if",
"(",
"locale",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
... | Tries to resolve the specified message for the given locale.
@param code the code to lookup up, such as 'calculator.noRateSet', never {@code null}.
@param locale The Locale for which it is tried to look up the code. Must not be null
@param defaultMessage string to return if the lookup fails, never {@code null}.
@param arguments Array of arguments that will be filled in for params within the message (params look like "{0}",
"{1,date}", "{2,time}"), or {@code null} if none.
@return the resolved message, or the {@code defaultMessage} if the lookup fails. | [
"Tries",
"to",
"resolve",
"the",
"specified",
"message",
"for",
"the",
"given",
"locale",
"."
] | train | https://github.com/peholmst/vaadin4spring/blob/ea896012f15d6abea6e6391def9a0001113a1f7a/addons/i18n/src/main/java/org/vaadin/spring/i18n/I18N.java#L171-L180 |
autermann/yaml | src/main/java/com/github/autermann/yaml/Yaml.java | Yaml.dumpAll | public void dumpAll(Iterator<? extends YamlNode> data, Writer output) {
"""
Dumps {@code data} into a {@code Writer}.
@param data the data
@param output the writer
@see org.yaml.snakeyaml.Yaml#dumpAll(Iterator, Writer)
"""
getDelegate().dumpAll(data, output);
} | java | public void dumpAll(Iterator<? extends YamlNode> data, Writer output) {
getDelegate().dumpAll(data, output);
} | [
"public",
"void",
"dumpAll",
"(",
"Iterator",
"<",
"?",
"extends",
"YamlNode",
">",
"data",
",",
"Writer",
"output",
")",
"{",
"getDelegate",
"(",
")",
".",
"dumpAll",
"(",
"data",
",",
"output",
")",
";",
"}"
] | Dumps {@code data} into a {@code Writer}.
@param data the data
@param output the writer
@see org.yaml.snakeyaml.Yaml#dumpAll(Iterator, Writer) | [
"Dumps",
"{",
"@code",
"data",
"}",
"into",
"a",
"{",
"@code",
"Writer",
"}",
"."
] | train | https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/Yaml.java#L148-L150 |
Netflix/eureka | eureka-core/src/main/java/com/netflix/eureka/registry/AbstractInstanceRegistry.java | AbstractInstanceRegistry.storeOverriddenStatusIfRequired | @Override
public void storeOverriddenStatusIfRequired(String appName, String id, InstanceStatus overriddenStatus) {
"""
Stores overridden status if it is not already there. This happens during
a reconciliation process during renewal requests.
@param appName the application name of the instance.
@param id the unique identifier of the instance.
@param overriddenStatus overridden status if any.
"""
InstanceStatus instanceStatus = overriddenInstanceStatusMap.get(id);
if ((instanceStatus == null) || (!overriddenStatus.equals(instanceStatus))) {
// We might not have the overridden status if the server got
// restarted -this will help us maintain the overridden state
// from the replica
logger.info("Adding overridden status for instance id {} and the value is {}",
id, overriddenStatus.name());
overriddenInstanceStatusMap.put(id, overriddenStatus);
InstanceInfo instanceInfo = this.getInstanceByAppAndId(appName, id, false);
instanceInfo.setOverriddenStatus(overriddenStatus);
logger.info("Set the overridden status for instance (appname:{}, id:{}} and the value is {} ",
appName, id, overriddenStatus.name());
}
} | java | @Override
public void storeOverriddenStatusIfRequired(String appName, String id, InstanceStatus overriddenStatus) {
InstanceStatus instanceStatus = overriddenInstanceStatusMap.get(id);
if ((instanceStatus == null) || (!overriddenStatus.equals(instanceStatus))) {
// We might not have the overridden status if the server got
// restarted -this will help us maintain the overridden state
// from the replica
logger.info("Adding overridden status for instance id {} and the value is {}",
id, overriddenStatus.name());
overriddenInstanceStatusMap.put(id, overriddenStatus);
InstanceInfo instanceInfo = this.getInstanceByAppAndId(appName, id, false);
instanceInfo.setOverriddenStatus(overriddenStatus);
logger.info("Set the overridden status for instance (appname:{}, id:{}} and the value is {} ",
appName, id, overriddenStatus.name());
}
} | [
"@",
"Override",
"public",
"void",
"storeOverriddenStatusIfRequired",
"(",
"String",
"appName",
",",
"String",
"id",
",",
"InstanceStatus",
"overriddenStatus",
")",
"{",
"InstanceStatus",
"instanceStatus",
"=",
"overriddenInstanceStatusMap",
".",
"get",
"(",
"id",
")"... | Stores overridden status if it is not already there. This happens during
a reconciliation process during renewal requests.
@param appName the application name of the instance.
@param id the unique identifier of the instance.
@param overriddenStatus overridden status if any. | [
"Stores",
"overridden",
"status",
"if",
"it",
"is",
"not",
"already",
"there",
".",
"This",
"happens",
"during",
"a",
"reconciliation",
"process",
"during",
"renewal",
"requests",
"."
] | train | https://github.com/Netflix/eureka/blob/48446d956be09df6650a3c00b7ebd7e2d1e1544f/eureka-core/src/main/java/com/netflix/eureka/registry/AbstractInstanceRegistry.java#L424-L439 |
FlyingHe/UtilsMaven | src/main/java/com/github/flyinghe/depdcy/AbstractExcelWriter.java | AbstractExcelWriter.createXLSXColor | public XSSFColor createXLSXColor(int r, int g, int b, int a) throws WriteExcelException {
"""
创建一个自定义颜色,仅适用于XLSX类型Excel文件。
你可以使用{@link XSSFCellStyle#setFillForegroundColor(XSSFColor)}
来使用自定义颜色
@param r red
@param g green
@param b blue
@param a alpha
@return 一个新的自定义颜色
@throws WriteExcelException 异常
@see #createXLSXCellStyle()
@see #createXLSXColor(int, int, int)
@see #getXLSPalette()
"""
if (XLSX != this.excelType) {
throw new WriteExcelException("此颜色仅适用于XLSX类型Excel文件使用");
}
return new XSSFColor(new java.awt.Color(r, g, b, a));
} | java | public XSSFColor createXLSXColor(int r, int g, int b, int a) throws WriteExcelException {
if (XLSX != this.excelType) {
throw new WriteExcelException("此颜色仅适用于XLSX类型Excel文件使用");
}
return new XSSFColor(new java.awt.Color(r, g, b, a));
} | [
"public",
"XSSFColor",
"createXLSXColor",
"(",
"int",
"r",
",",
"int",
"g",
",",
"int",
"b",
",",
"int",
"a",
")",
"throws",
"WriteExcelException",
"{",
"if",
"(",
"XLSX",
"!=",
"this",
".",
"excelType",
")",
"{",
"throw",
"new",
"WriteExcelException",
"... | 创建一个自定义颜色,仅适用于XLSX类型Excel文件。
你可以使用{@link XSSFCellStyle#setFillForegroundColor(XSSFColor)}
来使用自定义颜色
@param r red
@param g green
@param b blue
@param a alpha
@return 一个新的自定义颜色
@throws WriteExcelException 异常
@see #createXLSXCellStyle()
@see #createXLSXColor(int, int, int)
@see #getXLSPalette() | [
"创建一个自定义颜色",
"仅适用于XLSX类型Excel文件。",
"你可以使用",
"{",
"@link",
"XSSFCellStyle#setFillForegroundColor",
"(",
"XSSFColor",
")",
"}",
"来使用自定义颜色"
] | train | https://github.com/FlyingHe/UtilsMaven/blob/d9605b7bfe0c28a05289252e12d163e114080b4a/src/main/java/com/github/flyinghe/depdcy/AbstractExcelWriter.java#L656-L661 |
azkaban/azkaban | az-core/src/main/java/azkaban/utils/PluginUtils.java | PluginUtils.getPluginClass | public static Class<?> getPluginClass(final String pluginClass, final File pluginDir,
final List<String> extLibClassPaths, ClassLoader parentClassLoader) {
"""
Get Plugin Class
@param pluginClass plugin class name
@param pluginDir plugin root directory
@param extLibClassPaths external Library Class Paths
@param parentClassLoader parent class loader
@return Plugin class or Null
"""
URLClassLoader urlClassLoader =
getURLClassLoader(pluginDir, extLibClassPaths, parentClassLoader);
return getPluginClass(pluginClass, urlClassLoader);
} | java | public static Class<?> getPluginClass(final String pluginClass, final File pluginDir,
final List<String> extLibClassPaths, ClassLoader parentClassLoader) {
URLClassLoader urlClassLoader =
getURLClassLoader(pluginDir, extLibClassPaths, parentClassLoader);
return getPluginClass(pluginClass, urlClassLoader);
} | [
"public",
"static",
"Class",
"<",
"?",
">",
"getPluginClass",
"(",
"final",
"String",
"pluginClass",
",",
"final",
"File",
"pluginDir",
",",
"final",
"List",
"<",
"String",
">",
"extLibClassPaths",
",",
"ClassLoader",
"parentClassLoader",
")",
"{",
"URLClassLoad... | Get Plugin Class
@param pluginClass plugin class name
@param pluginDir plugin root directory
@param extLibClassPaths external Library Class Paths
@param parentClassLoader parent class loader
@return Plugin class or Null | [
"Get",
"Plugin",
"Class"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-core/src/main/java/azkaban/utils/PluginUtils.java#L113-L120 |
alkacon/opencms-core | src/org/opencms/acacia/shared/CmsWidgetUtil.java | CmsWidgetUtil.getBooleanOption | public static boolean getBooleanOption(Map<String, String> configOptions, String optionKey) {
"""
Returns a flag, indicating if a boolean option is set, i.e., it is in the map and has value null or (case-insensitive) "true".
@param configOptions the map with the config options.
@param optionKey the boolean option to check.
@return a flag, indicating if a boolean option is set
"""
if (configOptions.containsKey(optionKey)) {
String value = configOptions.get(optionKey);
if ((value == null) || Boolean.valueOf(value).booleanValue()) {
return true;
}
}
return false;
} | java | public static boolean getBooleanOption(Map<String, String> configOptions, String optionKey) {
if (configOptions.containsKey(optionKey)) {
String value = configOptions.get(optionKey);
if ((value == null) || Boolean.valueOf(value).booleanValue()) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"getBooleanOption",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"configOptions",
",",
"String",
"optionKey",
")",
"{",
"if",
"(",
"configOptions",
".",
"containsKey",
"(",
"optionKey",
")",
")",
"{",
"String",
"value",
"=",
... | Returns a flag, indicating if a boolean option is set, i.e., it is in the map and has value null or (case-insensitive) "true".
@param configOptions the map with the config options.
@param optionKey the boolean option to check.
@return a flag, indicating if a boolean option is set | [
"Returns",
"a",
"flag",
"indicating",
"if",
"a",
"boolean",
"option",
"is",
"set",
"i",
".",
"e",
".",
"it",
"is",
"in",
"the",
"map",
"and",
"has",
"value",
"null",
"or",
"(",
"case",
"-",
"insensitive",
")",
"true",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/acacia/shared/CmsWidgetUtil.java#L64-L73 |
pressgang-ccms/PressGangCCMSBuilder | src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java | DocBookBuilder.createDummyTranslatedTopicFromTopic | private TranslatedTopicWrapper createDummyTranslatedTopicFromTopic(final TopicWrapper topic, final LocaleWrapper locale) {
"""
Creates a dummy translated topic so that a book can be built using the same relationships as a normal build.
@param topic The topic to create the dummy topic from.
@param locale The locale to build the dummy translations for.
@return The dummy translated topic.
"""
final TranslatedTopicWrapper pushedTranslatedTopic = EntityUtilities.returnPushedTranslatedTopic(topic);
/*
* Try and use the untranslated default locale translated topic as the base for the dummy topic. If that fails then
* create a dummy topic from the passed RESTTopicV1.
*/
if (pushedTranslatedTopic != null) {
pushedTranslatedTopic.setTopic(topic);
pushedTranslatedTopic.setTags(topic.getTags());
pushedTranslatedTopic.setProperties(topic.getProperties());
return createDummyTranslatedTopicFromExisting(pushedTranslatedTopic, locale);
} else {
return createDummyTranslatedTopic(topic, locale);
}
} | java | private TranslatedTopicWrapper createDummyTranslatedTopicFromTopic(final TopicWrapper topic, final LocaleWrapper locale) {
final TranslatedTopicWrapper pushedTranslatedTopic = EntityUtilities.returnPushedTranslatedTopic(topic);
/*
* Try and use the untranslated default locale translated topic as the base for the dummy topic. If that fails then
* create a dummy topic from the passed RESTTopicV1.
*/
if (pushedTranslatedTopic != null) {
pushedTranslatedTopic.setTopic(topic);
pushedTranslatedTopic.setTags(topic.getTags());
pushedTranslatedTopic.setProperties(topic.getProperties());
return createDummyTranslatedTopicFromExisting(pushedTranslatedTopic, locale);
} else {
return createDummyTranslatedTopic(topic, locale);
}
} | [
"private",
"TranslatedTopicWrapper",
"createDummyTranslatedTopicFromTopic",
"(",
"final",
"TopicWrapper",
"topic",
",",
"final",
"LocaleWrapper",
"locale",
")",
"{",
"final",
"TranslatedTopicWrapper",
"pushedTranslatedTopic",
"=",
"EntityUtilities",
".",
"returnPushedTranslated... | Creates a dummy translated topic so that a book can be built using the same relationships as a normal build.
@param topic The topic to create the dummy topic from.
@param locale The locale to build the dummy translations for.
@return The dummy translated topic. | [
"Creates",
"a",
"dummy",
"translated",
"topic",
"so",
"that",
"a",
"book",
"can",
"be",
"built",
"using",
"the",
"same",
"relationships",
"as",
"a",
"normal",
"build",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java#L978-L993 |
zeroturnaround/zt-zip | src/main/java/org/zeroturnaround/zip/commons/FileUtilsV2_2.java | FileUtilsV2_2.copyFileToDirectory | public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {
"""
Copies a file to a directory preserving the file date.
<p>
This method copies the contents of the specified source file
to a file of the same name in the specified destination directory.
The destination directory is created if it does not exist.
If the destination file exists, then this method will overwrite it.
<p>
<strong>Note:</strong> This method tries to preserve the file's last
modified date/times using {@link File#setLastModified(long)}, however
it is not guaranteed that the operation will succeed.
If the modification operation fails, no indication is provided.
@param srcFile an existing file to copy, must not be <code>null</code>
@param destDir the directory to place the copy in, must not be <code>null</code>
@throws NullPointerException if source or destination is null
@throws IOException if source or destination is invalid
@throws IOException if an IO error occurs during copying
@see #copyFile(File, File, boolean)
"""
copyFileToDirectory(srcFile, destDir, true);
} | java | public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {
copyFileToDirectory(srcFile, destDir, true);
} | [
"public",
"static",
"void",
"copyFileToDirectory",
"(",
"File",
"srcFile",
",",
"File",
"destDir",
")",
"throws",
"IOException",
"{",
"copyFileToDirectory",
"(",
"srcFile",
",",
"destDir",
",",
"true",
")",
";",
"}"
] | Copies a file to a directory preserving the file date.
<p>
This method copies the contents of the specified source file
to a file of the same name in the specified destination directory.
The destination directory is created if it does not exist.
If the destination file exists, then this method will overwrite it.
<p>
<strong>Note:</strong> This method tries to preserve the file's last
modified date/times using {@link File#setLastModified(long)}, however
it is not guaranteed that the operation will succeed.
If the modification operation fails, no indication is provided.
@param srcFile an existing file to copy, must not be <code>null</code>
@param destDir the directory to place the copy in, must not be <code>null</code>
@throws NullPointerException if source or destination is null
@throws IOException if source or destination is invalid
@throws IOException if an IO error occurs during copying
@see #copyFile(File, File, boolean) | [
"Copies",
"a",
"file",
"to",
"a",
"directory",
"preserving",
"the",
"file",
"date",
".",
"<p",
">",
"This",
"method",
"copies",
"the",
"contents",
"of",
"the",
"specified",
"source",
"file",
"to",
"a",
"file",
"of",
"the",
"same",
"name",
"in",
"the",
... | train | https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/commons/FileUtilsV2_2.java#L291-L293 |
googleads/googleads-java-lib | examples/adwords_axis/src/main/java/adwords/axis/v201809/optimization/EstimateKeywordTraffic.java | EstimateKeywordTraffic.calculateMean | private static Double calculateMean(Number min, Number max) {
"""
Returns the mean of the two Number values if neither is null, else returns null.
"""
if (min == null || max == null) {
return null;
}
return (min.doubleValue() + max.doubleValue()) / 2;
} | java | private static Double calculateMean(Number min, Number max) {
if (min == null || max == null) {
return null;
}
return (min.doubleValue() + max.doubleValue()) / 2;
} | [
"private",
"static",
"Double",
"calculateMean",
"(",
"Number",
"min",
",",
"Number",
"max",
")",
"{",
"if",
"(",
"min",
"==",
"null",
"||",
"max",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"(",
"min",
".",
"doubleValue",
"(",
")",... | Returns the mean of the two Number values if neither is null, else returns null. | [
"Returns",
"the",
"mean",
"of",
"the",
"two",
"Number",
"values",
"if",
"neither",
"is",
"null",
"else",
"returns",
"null",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/adwords_axis/src/main/java/adwords/axis/v201809/optimization/EstimateKeywordTraffic.java#L293-L298 |
podio/podio-java | src/main/java/com/podio/org/OrgAPI.java | OrgAPI.getSpaceByURL | public Space getSpaceByURL(int orgId, String url) {
"""
Return the space with the given URL on the space. To get the space
related to http://company.podio.com/intranet, first lookup the
organization on "company" and then the space using this function using
the URL "intranet".
@param orgId
The id of the organization
@param url
The url fragment for the space
@return The matching space
"""
return getResourceFactory().getApiResource(
"/org/" + orgId + "/space/url/" + url).get(Space.class);
} | java | public Space getSpaceByURL(int orgId, String url) {
return getResourceFactory().getApiResource(
"/org/" + orgId + "/space/url/" + url).get(Space.class);
} | [
"public",
"Space",
"getSpaceByURL",
"(",
"int",
"orgId",
",",
"String",
"url",
")",
"{",
"return",
"getResourceFactory",
"(",
")",
".",
"getApiResource",
"(",
"\"/org/\"",
"+",
"orgId",
"+",
"\"/space/url/\"",
"+",
"url",
")",
".",
"get",
"(",
"Space",
"."... | Return the space with the given URL on the space. To get the space
related to http://company.podio.com/intranet, first lookup the
organization on "company" and then the space using this function using
the URL "intranet".
@param orgId
The id of the organization
@param url
The url fragment for the space
@return The matching space | [
"Return",
"the",
"space",
"with",
"the",
"given",
"URL",
"on",
"the",
"space",
".",
"To",
"get",
"the",
"space",
"related",
"to",
"http",
":",
"//",
"company",
".",
"podio",
".",
"com",
"/",
"intranet",
"first",
"lookup",
"the",
"organization",
"on",
"... | train | https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/org/OrgAPI.java#L109-L112 |
lotaris/rox-client-java | rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java | Configuration.getUid | public String getUid(String category, String projectName, String projectVersion) {
"""
Shortcut method to {@link Configuration#getUid(java.lang.String, java.lang.String, java.lang.String, boolean) }
@param category The category
@param projectName The project name
@param projectVersion The project version
@return The UID generated
"""
return getUid(category, projectName, projectVersion, false);
} | java | public String getUid(String category, String projectName, String projectVersion) {
return getUid(category, projectName, projectVersion, false);
} | [
"public",
"String",
"getUid",
"(",
"String",
"category",
",",
"String",
"projectName",
",",
"String",
"projectVersion",
")",
"{",
"return",
"getUid",
"(",
"category",
",",
"projectName",
",",
"projectVersion",
",",
"false",
")",
";",
"}"
] | Shortcut method to {@link Configuration#getUid(java.lang.String, java.lang.String, java.lang.String, boolean) }
@param category The category
@param projectName The project name
@param projectVersion The project version
@return The UID generated | [
"Shortcut",
"method",
"to",
"{",
"@link",
"Configuration#getUid",
"(",
"java",
".",
"lang",
".",
"String",
"java",
".",
"lang",
".",
"String",
"java",
".",
"lang",
".",
"String",
"boolean",
")",
"}"
] | train | https://github.com/lotaris/rox-client-java/blob/1b33f7560347c382c59a40c4037d175ab8127fde/rox-client-java/src/main/java/com/lotaris/rox/common/config/Configuration.java#L408-L410 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/features/FeatureUtilities.java | FeatureUtilities.envelopeToPolygon | public static Polygon envelopeToPolygon( Envelope2D envelope ) {
"""
Create a {@link Polygon} from an {@link Envelope}.
@param envelope the envelope to convert.
@return the created polygon.
"""
double w = envelope.getMinX();
double e = envelope.getMaxX();
double s = envelope.getMinY();
double n = envelope.getMaxY();
Coordinate[] coords = new Coordinate[5];
coords[0] = new Coordinate(w, n);
coords[1] = new Coordinate(e, n);
coords[2] = new Coordinate(e, s);
coords[3] = new Coordinate(w, s);
coords[4] = new Coordinate(w, n);
GeometryFactory gf = GeometryUtilities.gf();
LinearRing linearRing = gf.createLinearRing(coords);
Polygon polygon = gf.createPolygon(linearRing, null);
return polygon;
} | java | public static Polygon envelopeToPolygon( Envelope2D envelope ) {
double w = envelope.getMinX();
double e = envelope.getMaxX();
double s = envelope.getMinY();
double n = envelope.getMaxY();
Coordinate[] coords = new Coordinate[5];
coords[0] = new Coordinate(w, n);
coords[1] = new Coordinate(e, n);
coords[2] = new Coordinate(e, s);
coords[3] = new Coordinate(w, s);
coords[4] = new Coordinate(w, n);
GeometryFactory gf = GeometryUtilities.gf();
LinearRing linearRing = gf.createLinearRing(coords);
Polygon polygon = gf.createPolygon(linearRing, null);
return polygon;
} | [
"public",
"static",
"Polygon",
"envelopeToPolygon",
"(",
"Envelope2D",
"envelope",
")",
"{",
"double",
"w",
"=",
"envelope",
".",
"getMinX",
"(",
")",
";",
"double",
"e",
"=",
"envelope",
".",
"getMaxX",
"(",
")",
";",
"double",
"s",
"=",
"envelope",
"."... | Create a {@link Polygon} from an {@link Envelope}.
@param envelope the envelope to convert.
@return the created polygon. | [
"Create",
"a",
"{",
"@link",
"Polygon",
"}",
"from",
"an",
"{",
"@link",
"Envelope",
"}",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/features/FeatureUtilities.java#L634-L651 |
stephanenicolas/robospice | robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java | SpiceManager.isDataInCache | public Future<Boolean> isDataInCache(Class<?> clazz, final Object cacheKey, long cacheExpiryDuration) throws CacheCreationException {
"""
Tests whether some data is present in cache or not.
@param clazz
the class of the result to retrieve from cache.
@param cacheKey
the key used to store and retrieve the result of the request
in the cache
@param cacheExpiryDuration
duration in milliseconds after which the content of the cache
will be considered to be expired.
{@link DurationInMillis#ALWAYS_RETURNED} means data in cache
is always returned if it exists.
{@link DurationInMillis#ALWAYS_EXPIRED} means data in cache is
never returned.(see {@link DurationInMillis})
@return the data has it has been saved by an ObjectPersister in cache.
@throws CacheCreationException
Exception thrown when a problem occurs while looking for data
in cache.
"""
return executeCommand(new IsDataInCacheCommand(this, clazz, cacheKey, cacheExpiryDuration));
} | java | public Future<Boolean> isDataInCache(Class<?> clazz, final Object cacheKey, long cacheExpiryDuration) throws CacheCreationException {
return executeCommand(new IsDataInCacheCommand(this, clazz, cacheKey, cacheExpiryDuration));
} | [
"public",
"Future",
"<",
"Boolean",
">",
"isDataInCache",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"final",
"Object",
"cacheKey",
",",
"long",
"cacheExpiryDuration",
")",
"throws",
"CacheCreationException",
"{",
"return",
"executeCommand",
"(",
"new",
"IsDataI... | Tests whether some data is present in cache or not.
@param clazz
the class of the result to retrieve from cache.
@param cacheKey
the key used to store and retrieve the result of the request
in the cache
@param cacheExpiryDuration
duration in milliseconds after which the content of the cache
will be considered to be expired.
{@link DurationInMillis#ALWAYS_RETURNED} means data in cache
is always returned if it exists.
{@link DurationInMillis#ALWAYS_EXPIRED} means data in cache is
never returned.(see {@link DurationInMillis})
@return the data has it has been saved by an ObjectPersister in cache.
@throws CacheCreationException
Exception thrown when a problem occurs while looking for data
in cache. | [
"Tests",
"whether",
"some",
"data",
"is",
"present",
"in",
"cache",
"or",
"not",
"."
] | train | https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/SpiceManager.java#L948-L950 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/duration/Period.java | Period.lessThan | public static Period lessThan(float count, TimeUnit unit) {
"""
Constructs a Period representing a duration
less than count units extending into the past.
@param count the number of units. must be non-negative
@param unit the unit
@return the new Period
"""
checkCount(count);
return new Period(ETimeLimit.LT, false, count, unit);
} | java | public static Period lessThan(float count, TimeUnit unit) {
checkCount(count);
return new Period(ETimeLimit.LT, false, count, unit);
} | [
"public",
"static",
"Period",
"lessThan",
"(",
"float",
"count",
",",
"TimeUnit",
"unit",
")",
"{",
"checkCount",
"(",
"count",
")",
";",
"return",
"new",
"Period",
"(",
"ETimeLimit",
".",
"LT",
",",
"false",
",",
"count",
",",
"unit",
")",
";",
"}"
] | Constructs a Period representing a duration
less than count units extending into the past.
@param count the number of units. must be non-negative
@param unit the unit
@return the new Period | [
"Constructs",
"a",
"Period",
"representing",
"a",
"duration",
"less",
"than",
"count",
"units",
"extending",
"into",
"the",
"past",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/duration/Period.java#L67-L70 |
susom/database | src/main/java/com/github/susom/database/DatabaseProvider.java | DatabaseProvider.fromPropertyFileOrSystemProperties | public static Builder fromPropertyFileOrSystemProperties(String filename, CharsetDecoder decoder) {
"""
Configure the database from up to five properties read from the specified
properties file, or from the system properties (system properties will take
precedence over the file):
<br/>
<pre>
database.url=... Database connect string (required)
database.user=... Authenticate as this user (optional if provided in url)
database.password=... User password (optional if user and password provided in
url; prompted on standard input if user is provided and
password is not)
database.flavor=... What kind of database it is (optional, will guess based
on the url if this is not provided)
database.driver=... The Java class of the JDBC driver to load (optional, will
guess based on the flavor if this is not provided)
</pre>
@param filename path to the properties file we will attempt to read; if the file
cannot be read for any reason (e.g. does not exist) a debug level
log entry will be entered, but it will attempt to proceed using
solely the system properties
@param decoder character encoding to use when reading the property file
"""
Properties properties = new Properties();
if (filename != null && filename.length() > 0) {
try {
properties.load(new InputStreamReader(new FileInputStream(filename), decoder));
} catch (Exception e) {
log.debug("Trying system properties - unable to read properties file: " + filename);
}
}
return fromProperties(properties, "", true);
} | java | public static Builder fromPropertyFileOrSystemProperties(String filename, CharsetDecoder decoder) {
Properties properties = new Properties();
if (filename != null && filename.length() > 0) {
try {
properties.load(new InputStreamReader(new FileInputStream(filename), decoder));
} catch (Exception e) {
log.debug("Trying system properties - unable to read properties file: " + filename);
}
}
return fromProperties(properties, "", true);
} | [
"public",
"static",
"Builder",
"fromPropertyFileOrSystemProperties",
"(",
"String",
"filename",
",",
"CharsetDecoder",
"decoder",
")",
"{",
"Properties",
"properties",
"=",
"new",
"Properties",
"(",
")",
";",
"if",
"(",
"filename",
"!=",
"null",
"&&",
"filename",
... | Configure the database from up to five properties read from the specified
properties file, or from the system properties (system properties will take
precedence over the file):
<br/>
<pre>
database.url=... Database connect string (required)
database.user=... Authenticate as this user (optional if provided in url)
database.password=... User password (optional if user and password provided in
url; prompted on standard input if user is provided and
password is not)
database.flavor=... What kind of database it is (optional, will guess based
on the url if this is not provided)
database.driver=... The Java class of the JDBC driver to load (optional, will
guess based on the flavor if this is not provided)
</pre>
@param filename path to the properties file we will attempt to read; if the file
cannot be read for any reason (e.g. does not exist) a debug level
log entry will be entered, but it will attempt to proceed using
solely the system properties
@param decoder character encoding to use when reading the property file | [
"Configure",
"the",
"database",
"from",
"up",
"to",
"five",
"properties",
"read",
"from",
"the",
"specified",
"properties",
"file",
"or",
"from",
"the",
"system",
"properties",
"(",
"system",
"properties",
"will",
"take",
"precedence",
"over",
"the",
"file",
"... | train | https://github.com/susom/database/blob/25add9e08ad863712f9b5e319b6cb826f6f97640/src/main/java/com/github/susom/database/DatabaseProvider.java#L446-L456 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.