repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 201 | func_name stringlengths 4 126 | whole_func_string stringlengths 75 3.57k | language stringclasses 1
value | func_code_string stringlengths 75 3.57k | func_code_tokens listlengths 21 599 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 478 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
google/j2objc | jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java | BigDecimal.doRound128 | private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {
int mcp = mc.precision;
int drop;
BigDecimal res = null;
if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {
scale = checkScaleNonZero((long)scale - drop);
res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);
}
if(res!=null) {
return doRound(res,mc);
}
return null;
} | java | private static BigDecimal doRound128(long hi, long lo, int sign, int scale, MathContext mc) {
int mcp = mc.precision;
int drop;
BigDecimal res = null;
if(((drop = precision(hi, lo) - mcp) > 0)&&(drop<LONG_TEN_POWERS_TABLE.length)) {
scale = checkScaleNonZero((long)scale - drop);
res = divideAndRound128(hi, lo, LONG_TEN_POWERS_TABLE[drop], sign, scale, mc.roundingMode.oldMode, scale);
}
if(res!=null) {
return doRound(res,mc);
}
return null;
} | [
"private",
"static",
"BigDecimal",
"doRound128",
"(",
"long",
"hi",
",",
"long",
"lo",
",",
"int",
"sign",
",",
"int",
"scale",
",",
"MathContext",
"mc",
")",
"{",
"int",
"mcp",
"=",
"mc",
".",
"precision",
";",
"int",
"drop",
";",
"BigDecimal",
"res",... | rounds 128-bit value according {@code MathContext}
returns null if result can't be repsented as compact BigDecimal. | [
"rounds",
"128",
"-",
"bit",
"value",
"according",
"{"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/BigDecimal.java#L5083-L5095 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/FileBasedNamespaceMappings.java | FileBasedNamespaceMappings.getNamespacePrefixByURI | public synchronized String getNamespacePrefixByURI(String uri) throws NamespaceException
{
String prefix = uriToPrefix.get(uri);
if (prefix == null)
{
// make sure prefix is not taken
while (prefixToURI.get(String.valueOf(prefixCount)) != null)
{
prefixCount++;
}
prefix = String.valueOf(prefixCount);
prefixToURI.put(prefix, uri);
uriToPrefix.put(uri, prefix);
log.debug("adding new namespace mapping: " + prefix + " -> " + uri);
try
{
store();
}
catch (IOException e)
{
throw new NamespaceException("Could not obtain a prefix for uri: " + uri, e);
}
}
return prefix;
} | java | public synchronized String getNamespacePrefixByURI(String uri) throws NamespaceException
{
String prefix = uriToPrefix.get(uri);
if (prefix == null)
{
// make sure prefix is not taken
while (prefixToURI.get(String.valueOf(prefixCount)) != null)
{
prefixCount++;
}
prefix = String.valueOf(prefixCount);
prefixToURI.put(prefix, uri);
uriToPrefix.put(uri, prefix);
log.debug("adding new namespace mapping: " + prefix + " -> " + uri);
try
{
store();
}
catch (IOException e)
{
throw new NamespaceException("Could not obtain a prefix for uri: " + uri, e);
}
}
return prefix;
} | [
"public",
"synchronized",
"String",
"getNamespacePrefixByURI",
"(",
"String",
"uri",
")",
"throws",
"NamespaceException",
"{",
"String",
"prefix",
"=",
"uriToPrefix",
".",
"get",
"(",
"uri",
")",
";",
"if",
"(",
"prefix",
"==",
"null",
")",
"{",
"// make sure ... | Returns a prefix for the namespace <code>uri</code>. If a namespace
mapping exists, the already known prefix is returned; otherwise a new
prefix is created and assigned to the namespace uri.
@param uri the namespace uri.
@return the prefix for the namespace uri.
@throws NamespaceException if an yet unknown namespace uri / prefix
mapping could not be stored. | [
"Returns",
"a",
"prefix",
"for",
"the",
"namespace",
"<code",
">",
"uri<",
"/",
"code",
">",
".",
"If",
"a",
"namespace",
"mapping",
"exists",
"the",
"already",
"known",
"prefix",
"is",
"returned",
";",
"otherwise",
"a",
"new",
"prefix",
"is",
"created",
... | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/FileBasedNamespaceMappings.java#L115-L139 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java | SparseCpuLevel1.sscal | @Override
protected void sscal(long N, double a, INDArray X, int incx) {
cblas_sscal((int) N, (float) a, (FloatPointer) X.data().addressPointer(), incx);
} | java | @Override
protected void sscal(long N, double a, INDArray X, int incx) {
cblas_sscal((int) N, (float) a, (FloatPointer) X.data().addressPointer(), incx);
} | [
"@",
"Override",
"protected",
"void",
"sscal",
"(",
"long",
"N",
",",
"double",
"a",
",",
"INDArray",
"X",
",",
"int",
"incx",
")",
"{",
"cblas_sscal",
"(",
"(",
"int",
")",
"N",
",",
"(",
"float",
")",
"a",
",",
"(",
"FloatPointer",
")",
"X",
".... | Computes the product of a float vector by a scalar.
@param N The number of elements of the vector X
@param a a scalar
@param X a vector
@param incx the increment of the vector X | [
"Computes",
"the",
"product",
"of",
"a",
"float",
"vector",
"by",
"a",
"scalar",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-native/src/main/java/org/nd4j/linalg/cpu/nativecpu/blas/SparseCpuLevel1.java#L280-L283 |
eduarddrenth/ConfigurableReports | src/main/java/com/vectorprint/report/itext/style/stylers/DocumentSettings.java | DocumentSettings.configureVisualSignature | @Override
public void configureVisualSignature(PdfSignatureAppearance psa)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, VectorPrintException {
psa.setReason("verify origin");
try {
psa.setLocation(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException ex) {
log.log(Level.WARNING, "unable to set location for pdf signature", ex);
}
char[] pw = getValue(KEYSTORE_PASSWORD, char[].class);
char[] clone = pw.clone();
KeyStore ks = loadKeyStore(pw);
PrivateKey key = getKey(ks, (String) ks.aliases().nextElement(), clone);
Certificate[] certificateChain = ks.getCertificateChain((String) ks.aliases().nextElement());
PrivateKeySignature pks = new PrivateKeySignature(key, getValue(DIGESTPARAM, DIGESTALGORITHM.class).name(), "BC");
ExternalDigest as = new BouncyCastleDigest();
psa.setVisibleSignature(new Rectangle(0, getHeight() - 100, 200, getHeight()), 1, "signature");
try {
MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);
} catch (IOException | DocumentException | GeneralSecurityException ex) {
throw new VectorPrintException(ex);
}
} | java | @Override
public void configureVisualSignature(PdfSignatureAppearance psa)
throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, VectorPrintException {
psa.setReason("verify origin");
try {
psa.setLocation(InetAddress.getLocalHost().getHostName());
} catch (UnknownHostException ex) {
log.log(Level.WARNING, "unable to set location for pdf signature", ex);
}
char[] pw = getValue(KEYSTORE_PASSWORD, char[].class);
char[] clone = pw.clone();
KeyStore ks = loadKeyStore(pw);
PrivateKey key = getKey(ks, (String) ks.aliases().nextElement(), clone);
Certificate[] certificateChain = ks.getCertificateChain((String) ks.aliases().nextElement());
PrivateKeySignature pks = new PrivateKeySignature(key, getValue(DIGESTPARAM, DIGESTALGORITHM.class).name(), "BC");
ExternalDigest as = new BouncyCastleDigest();
psa.setVisibleSignature(new Rectangle(0, getHeight() - 100, 200, getHeight()), 1, "signature");
try {
MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0, MakeSignature.CryptoStandard.CMS);
} catch (IOException | DocumentException | GeneralSecurityException ex) {
throw new VectorPrintException(ex);
}
} | [
"@",
"Override",
"public",
"void",
"configureVisualSignature",
"(",
"PdfSignatureAppearance",
"psa",
")",
"throws",
"KeyStoreException",
",",
"NoSuchAlgorithmException",
",",
"UnrecoverableKeyException",
",",
"VectorPrintException",
"{",
"psa",
".",
"setReason",
"(",
"\"v... | adds a visible signature of 200 / 100 at top left of the first page of the pdf with "verify origin" as reason, the
localhost name as location. Uses MakeSignature.signDetached(psa, as, pks, certificateChain, null, null, null, 0,
MakeSignature.CryptoStandard.CMS)
@see #loadKeyStore(char[])
@see #getKey(java.security.KeyStore, java.lang.String, char[]) }
@param psa
@throws KeyStoreException
@throws NoSuchAlgorithmException
@throws UnrecoverableKeyException
@throws VectorPrintException | [
"adds",
"a",
"visible",
"signature",
"of",
"200",
"/",
"100",
"at",
"top",
"left",
"of",
"the",
"first",
"page",
"of",
"the",
"pdf",
"with",
"verify",
"origin",
"as",
"reason",
"the",
"localhost",
"name",
"as",
"location",
".",
"Uses",
"MakeSignature",
"... | train | https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/style/stylers/DocumentSettings.java#L197-L223 |
lucee/Lucee | core/src/main/java/lucee/runtime/type/util/ArrayUtil.java | ArrayUtil.setEL | public static Object setEL(Object o, int index, Object value) {
try {
return set(o, index, value);
}
catch (ArrayUtilException e) {
return null;
}
} | java | public static Object setEL(Object o, int index, Object value) {
try {
return set(o, index, value);
}
catch (ArrayUtilException e) {
return null;
}
} | [
"public",
"static",
"Object",
"setEL",
"(",
"Object",
"o",
",",
"int",
"index",
",",
"Object",
"value",
")",
"{",
"try",
"{",
"return",
"set",
"(",
"o",
",",
"index",
",",
"value",
")",
";",
"}",
"catch",
"(",
"ArrayUtilException",
"e",
")",
"{",
"... | sets a value to a array at defined index
@param o
@param index
@param value
@return value setted | [
"sets",
"a",
"value",
"to",
"a",
"array",
"at",
"defined",
"index"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/type/util/ArrayUtil.java#L604-L611 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java | Organizer.flattenPaging | public static <T> Paging<T> flattenPaging(Collection<Paging<T>> collectionOfPaging)
{
if (collectionOfPaging == null || collectionOfPaging.isEmpty())
return null;
PageCriteria pageCriteria = null;
// get first page criteria
Paging<T> firstPaging = collectionOfPaging.iterator().next();
if (firstPaging != null)
pageCriteria = firstPaging.getPageCriteria();
return flattenPaging(collectionOfPaging, pageCriteria, null, null);
} | java | public static <T> Paging<T> flattenPaging(Collection<Paging<T>> collectionOfPaging)
{
if (collectionOfPaging == null || collectionOfPaging.isEmpty())
return null;
PageCriteria pageCriteria = null;
// get first page criteria
Paging<T> firstPaging = collectionOfPaging.iterator().next();
if (firstPaging != null)
pageCriteria = firstPaging.getPageCriteria();
return flattenPaging(collectionOfPaging, pageCriteria, null, null);
} | [
"public",
"static",
"<",
"T",
">",
"Paging",
"<",
"T",
">",
"flattenPaging",
"(",
"Collection",
"<",
"Paging",
"<",
"T",
">",
">",
"collectionOfPaging",
")",
"{",
"if",
"(",
"collectionOfPaging",
"==",
"null",
"||",
"collectionOfPaging",
".",
"isEmpty",
"(... | Aggregates multiple collections into a single paging collection
@param collectionOfPaging
the collection paging that
@param <T>
the type class
@return the flatten collections into a single collection | [
"Aggregates",
"multiple",
"collections",
"into",
"a",
"single",
"paging",
"collection"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/util/Organizer.java#L177-L191 |
grails/grails-core | grails-core/src/main/groovy/org/grails/spring/context/support/PluginAwareResourceBundleMessageSource.java | PluginAwareResourceBundleMessageSource.resolveCodeFromPlugins | protected MessageFormat resolveCodeFromPlugins(String code, Locale locale) {
if (pluginCacheMillis < 0) {
PropertiesHolder propHolder = getMergedPluginProperties(locale);
MessageFormat result = propHolder.getMessageFormat(code, locale);
if (result != null) {
return result;
}
}
else {
MessageFormat result = findMessageFormatInBinaryPlugins(code, locale);
if (result != null) return result;
}
return null;
} | java | protected MessageFormat resolveCodeFromPlugins(String code, Locale locale) {
if (pluginCacheMillis < 0) {
PropertiesHolder propHolder = getMergedPluginProperties(locale);
MessageFormat result = propHolder.getMessageFormat(code, locale);
if (result != null) {
return result;
}
}
else {
MessageFormat result = findMessageFormatInBinaryPlugins(code, locale);
if (result != null) return result;
}
return null;
} | [
"protected",
"MessageFormat",
"resolveCodeFromPlugins",
"(",
"String",
"code",
",",
"Locale",
"locale",
")",
"{",
"if",
"(",
"pluginCacheMillis",
"<",
"0",
")",
"{",
"PropertiesHolder",
"propHolder",
"=",
"getMergedPluginProperties",
"(",
"locale",
")",
";",
"Mess... | Attempts to resolve a MessageFormat for the code from the list of plugin base names
@param code The code
@param locale The locale
@return a MessageFormat | [
"Attempts",
"to",
"resolve",
"a",
"MessageFormat",
"for",
"the",
"code",
"from",
"the",
"list",
"of",
"plugin",
"base",
"names"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/spring/context/support/PluginAwareResourceBundleMessageSource.java#L252-L265 |
Azure/azure-sdk-for-java | applicationinsights/data-plane/src/main/java/com/microsoft/azure/applicationinsights/query/implementation/MetricsImpl.java | MetricsImpl.getMultiple | public List<MetricsResultsItem> getMultiple(String appId, List<MetricsPostBodySchema> body) {
return getMultipleWithServiceResponseAsync(appId, body).toBlocking().single().body();
} | java | public List<MetricsResultsItem> getMultiple(String appId, List<MetricsPostBodySchema> body) {
return getMultipleWithServiceResponseAsync(appId, body).toBlocking().single().body();
} | [
"public",
"List",
"<",
"MetricsResultsItem",
">",
"getMultiple",
"(",
"String",
"appId",
",",
"List",
"<",
"MetricsPostBodySchema",
">",
"body",
")",
"{",
"return",
"getMultipleWithServiceResponseAsync",
"(",
"appId",
",",
"body",
")",
".",
"toBlocking",
"(",
")... | Retrieve metric data.
Gets metric values for multiple metrics.
@param appId ID of the application. This is Application ID from the API Access settings blade in the Azure portal.
@param body The batched metrics query.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<MetricsResultsItem> object if successful. | [
"Retrieve",
"metric",
"data",
".",
"Gets",
"metric",
"values",
"for",
"multiple",
"metrics",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/data-plane/src/main/java/com/microsoft/azure/applicationinsights/query/implementation/MetricsImpl.java#L292-L294 |
pinterest/secor | src/main/java/com/pinterest/secor/util/FileUtil.java | FileUtil.getMd5Hash | public static String getMd5Hash(String topic, String[] partitions) {
ArrayList<String> elements = new ArrayList<String>();
elements.add(topic);
for (String partition : partitions) {
elements.add(partition);
}
String pathPrefix = StringUtils.join(elements, "/");
try {
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] md5Bytes = messageDigest.digest(pathPrefix.getBytes("UTF-8"));
return getHexEncode(md5Bytes).substring(0, 4);
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage());
} catch (UnsupportedEncodingException e) {
LOG.error(e.getMessage());
}
return "";
} | java | public static String getMd5Hash(String topic, String[] partitions) {
ArrayList<String> elements = new ArrayList<String>();
elements.add(topic);
for (String partition : partitions) {
elements.add(partition);
}
String pathPrefix = StringUtils.join(elements, "/");
try {
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
byte[] md5Bytes = messageDigest.digest(pathPrefix.getBytes("UTF-8"));
return getHexEncode(md5Bytes).substring(0, 4);
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage());
} catch (UnsupportedEncodingException e) {
LOG.error(e.getMessage());
}
return "";
} | [
"public",
"static",
"String",
"getMd5Hash",
"(",
"String",
"topic",
",",
"String",
"[",
"]",
"partitions",
")",
"{",
"ArrayList",
"<",
"String",
">",
"elements",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"elements",
".",
"add",
"(",
"... | Generate MD5 hash of topic and partitions. And extract first 4 characters of the MD5 hash.
@param topic topic name
@param partitions partitions
@return md5 hash | [
"Generate",
"MD5",
"hash",
"of",
"topic",
"and",
"partitions",
".",
"And",
"extract",
"first",
"4",
"characters",
"of",
"the",
"MD5",
"hash",
"."
] | train | https://github.com/pinterest/secor/blob/4099ff061db392f11044e57dedf46c1617895278/src/main/java/com/pinterest/secor/util/FileUtil.java#L248-L265 |
logic-ng/LogicNG | src/main/java/org/logicng/solvers/MiniSat.java | MiniSat.miniSat | public static MiniSat miniSat(final FormulaFactory f, final MiniSatConfig config) {
return new MiniSat(f, SolverStyle.MINISAT, config, null);
} | java | public static MiniSat miniSat(final FormulaFactory f, final MiniSatConfig config) {
return new MiniSat(f, SolverStyle.MINISAT, config, null);
} | [
"public",
"static",
"MiniSat",
"miniSat",
"(",
"final",
"FormulaFactory",
"f",
",",
"final",
"MiniSatConfig",
"config",
")",
"{",
"return",
"new",
"MiniSat",
"(",
"f",
",",
"SolverStyle",
".",
"MINISAT",
",",
"config",
",",
"null",
")",
";",
"}"
] | Returns a new MiniSat solver with a given configuration.
@param f the formula factory
@param config the configuration
@return the solver | [
"Returns",
"a",
"new",
"MiniSat",
"solver",
"with",
"a",
"given",
"configuration",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/MiniSat.java#L141-L143 |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/event/EventServicesImpl.java | EventServicesImpl.getProcessInstance | public ProcessInstance getProcessInstance(Long procInstId)
throws ProcessException, DataAccessException {
TransactionWrapper transaction = null;
EngineDataAccessDB edao = new EngineDataAccessDB();
try {
transaction = edao.startTransaction();
return edao.getProcessInstance(procInstId);
} catch (SQLException e) {
throw new ProcessException(0, "Failed to get process instance", e);
} finally {
edao.stopTransaction(transaction);
}
} | java | public ProcessInstance getProcessInstance(Long procInstId)
throws ProcessException, DataAccessException {
TransactionWrapper transaction = null;
EngineDataAccessDB edao = new EngineDataAccessDB();
try {
transaction = edao.startTransaction();
return edao.getProcessInstance(procInstId);
} catch (SQLException e) {
throw new ProcessException(0, "Failed to get process instance", e);
} finally {
edao.stopTransaction(transaction);
}
} | [
"public",
"ProcessInstance",
"getProcessInstance",
"(",
"Long",
"procInstId",
")",
"throws",
"ProcessException",
",",
"DataAccessException",
"{",
"TransactionWrapper",
"transaction",
"=",
"null",
";",
"EngineDataAccessDB",
"edao",
"=",
"new",
"EngineDataAccessDB",
"(",
... | Returns the ProcessInstance identified by the passed in Id
@param procInstId
@return ProcessInstance | [
"Returns",
"the",
"ProcessInstance",
"identified",
"by",
"the",
"passed",
"in",
"Id"
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/event/EventServicesImpl.java#L351-L364 |
cdk/cdk | tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java | InChITautomerGenerator.getElementsByPosition | private Map<Integer, IAtom> getElementsByPosition(String inputInchi, IAtomContainer inputMolecule)
throws CDKException {
Map<Integer, IAtom> inchiAtomsByPosition = new HashMap<Integer, IAtom>();
int position = 0;
String inchi = inputInchi;
inchi = inchi.substring(inchi.indexOf('/') + 1);
String formula = inchi.substring(0, inchi.indexOf('/'));
/*
* Test for dots in the formula. For now, bail out when encountered; it
* would require more sophisticated InChI connection table parsing.
* Example: what happened to the platinum connectivity below?
* N.N.O=C1O[Pt]OC(=O)C12CCC2<br>
* InChI=1S/C6H8O4.2H3N.Pt/c7-4(8)6(5(9)10
* )2-1-3-6;;;/h1-3H2,(H,7,8)(H,9,10);2*1H3;/q;;;+2/p-2
*/
if (formula.contains("."))
throw new CDKException("Cannot parse InChI, formula contains dot (unsupported feature). Input formula="
+ formula);
Pattern formulaPattern = Pattern.compile("\\.?[0-9]*[A-Z]{1}[a-z]?[0-9]*");
Matcher match = formulaPattern.matcher(formula);
while (match.find()) {
String symbolAndCount = match.group();
String elementSymbol = (symbolAndCount.split("[0-9]"))[0];
if (!elementSymbol.equals("H")) {
int elementCnt = 1;
if (!(elementSymbol.length() == symbolAndCount.length())) {
elementCnt = Integer.valueOf(symbolAndCount.substring(elementSymbol.length()));
}
for (int i = 0; i < elementCnt; i++) {
position++;
IAtom atom = inputMolecule.getBuilder().newInstance(IAtom.class, elementSymbol);
/*
* This class uses the atom's ID attribute to keep track of
* atom positions defined in the InChi. So if for example
* atom.ID=14, it means this atom has position 14 in the
* InChI connection table.
*/
atom.setID(position + "");
inchiAtomsByPosition.put(position, atom);
}
}
}
return inchiAtomsByPosition;
} | java | private Map<Integer, IAtom> getElementsByPosition(String inputInchi, IAtomContainer inputMolecule)
throws CDKException {
Map<Integer, IAtom> inchiAtomsByPosition = new HashMap<Integer, IAtom>();
int position = 0;
String inchi = inputInchi;
inchi = inchi.substring(inchi.indexOf('/') + 1);
String formula = inchi.substring(0, inchi.indexOf('/'));
/*
* Test for dots in the formula. For now, bail out when encountered; it
* would require more sophisticated InChI connection table parsing.
* Example: what happened to the platinum connectivity below?
* N.N.O=C1O[Pt]OC(=O)C12CCC2<br>
* InChI=1S/C6H8O4.2H3N.Pt/c7-4(8)6(5(9)10
* )2-1-3-6;;;/h1-3H2,(H,7,8)(H,9,10);2*1H3;/q;;;+2/p-2
*/
if (formula.contains("."))
throw new CDKException("Cannot parse InChI, formula contains dot (unsupported feature). Input formula="
+ formula);
Pattern formulaPattern = Pattern.compile("\\.?[0-9]*[A-Z]{1}[a-z]?[0-9]*");
Matcher match = formulaPattern.matcher(formula);
while (match.find()) {
String symbolAndCount = match.group();
String elementSymbol = (symbolAndCount.split("[0-9]"))[0];
if (!elementSymbol.equals("H")) {
int elementCnt = 1;
if (!(elementSymbol.length() == symbolAndCount.length())) {
elementCnt = Integer.valueOf(symbolAndCount.substring(elementSymbol.length()));
}
for (int i = 0; i < elementCnt; i++) {
position++;
IAtom atom = inputMolecule.getBuilder().newInstance(IAtom.class, elementSymbol);
/*
* This class uses the atom's ID attribute to keep track of
* atom positions defined in the InChi. So if for example
* atom.ID=14, it means this atom has position 14 in the
* InChI connection table.
*/
atom.setID(position + "");
inchiAtomsByPosition.put(position, atom);
}
}
}
return inchiAtomsByPosition;
} | [
"private",
"Map",
"<",
"Integer",
",",
"IAtom",
">",
"getElementsByPosition",
"(",
"String",
"inputInchi",
",",
"IAtomContainer",
"inputMolecule",
")",
"throws",
"CDKException",
"{",
"Map",
"<",
"Integer",
",",
"IAtom",
">",
"inchiAtomsByPosition",
"=",
"new",
"... | Parses the InChI's formula (ignoring hydrogen) and returns a map
with with a position for each atom, increasing in the order
of the elements as listed in the formula.
@param inputInchi user input InChI
@param inputMolecule user input molecule
@return <Integer,IAtom> map indicating position and atom | [
"Parses",
"the",
"InChI",
"s",
"formula",
"(",
"ignoring",
"hydrogen",
")",
"and",
"returns",
"a",
"map",
"with",
"with",
"a",
"position",
"for",
"each",
"atom",
"increasing",
"in",
"the",
"order",
"of",
"the",
"elements",
"as",
"listed",
"in",
"the",
"f... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java#L200-L247 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java | MutateInBuilder.arrayPrepend | public <T> MutateInBuilder arrayPrepend(String path, T value) {
asyncBuilder.arrayPrepend(path, value);
return this;
} | java | public <T> MutateInBuilder arrayPrepend(String path, T value) {
asyncBuilder.arrayPrepend(path, value);
return this;
} | [
"public",
"<",
"T",
">",
"MutateInBuilder",
"arrayPrepend",
"(",
"String",
"path",
",",
"T",
"value",
")",
"{",
"asyncBuilder",
".",
"arrayPrepend",
"(",
"path",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Prepend to an existing array, pushing the value to the front/first position in
the array.
@param path the path of the array.
@param value the value to insert at the front of the array. | [
"Prepend",
"to",
"an",
"existing",
"array",
"pushing",
"the",
"value",
"to",
"the",
"front",
"/",
"first",
"position",
"in",
"the",
"array",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L707-L710 |
OpenBEL/openbel-framework | org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/ExternalType.java | ExternalType.writeObject | public static void writeObject(final ObjectOutput out, final Object o)
throws IOException {
if (o == null) {
out.writeByte(0);
return;
}
out.writeByte(1);
out.writeObject(o);
} | java | public static void writeObject(final ObjectOutput out, final Object o)
throws IOException {
if (o == null) {
out.writeByte(0);
return;
}
out.writeByte(1);
out.writeObject(o);
} | [
"public",
"static",
"void",
"writeObject",
"(",
"final",
"ObjectOutput",
"out",
",",
"final",
"Object",
"o",
")",
"throws",
"IOException",
"{",
"if",
"(",
"o",
"==",
"null",
")",
"{",
"out",
".",
"writeByte",
"(",
"0",
")",
";",
"return",
";",
"}",
"... | Writes the potentially null object to output. If {@code o} is null, one
byte is written to the output to indicate that. Otherwise, the written
size is the serialized object size plus an additional byte to indicate
non-null.
<p>
This method doesn't differ in functionality with
{@link ObjectOutput#writeObject(Object)}, including its support for
nulls. It exists as an analogue to the other methods here and as a point
for documenting how nulls are handled.
</p>
@param out Non-null {@link ObjectOutput}
@param o Object being written
@throws IOException Thrown if an I/O error occurs | [
"Writes",
"the",
"potentially",
"null",
"object",
"to",
"output",
".",
"If",
"{",
"@code",
"o",
"}",
"is",
"null",
"one",
"byte",
"is",
"written",
"to",
"the",
"output",
"to",
"indicate",
"that",
".",
"Otherwise",
"the",
"written",
"size",
"is",
"the",
... | train | https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/external/ExternalType.java#L128-L136 |
liferay/com-liferay-commerce | commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java | CommerceUserSegmentEntryPersistenceImpl.findAll | @Override
public List<CommerceUserSegmentEntry> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | java | @Override
public List<CommerceUserSegmentEntry> findAll() {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceUserSegmentEntry",
">",
"findAll",
"(",
")",
"{",
"return",
"findAll",
"(",
"QueryUtil",
".",
"ALL_POS",
",",
"QueryUtil",
".",
"ALL_POS",
",",
"null",
")",
";",
"}"
] | Returns all the commerce user segment entries.
@return the commerce user segment entries | [
"Returns",
"all",
"the",
"commerce",
"user",
"segment",
"entries",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-user-segment-service/src/main/java/com/liferay/commerce/user/segment/service/persistence/impl/CommerceUserSegmentEntryPersistenceImpl.java#L2770-L2773 |
intendia-oss/rxjava-gwt | src/main/modified/io/reactivex/super/io/reactivex/Maybe.java | Maybe.zipWith | @CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <U, R> Maybe<R> zipWith(MaybeSource<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) {
ObjectHelper.requireNonNull(other, "other is null");
return zip(this, other, zipper);
} | java | @CheckReturnValue
@SchedulerSupport(SchedulerSupport.NONE)
public final <U, R> Maybe<R> zipWith(MaybeSource<? extends U> other, BiFunction<? super T, ? super U, ? extends R> zipper) {
ObjectHelper.requireNonNull(other, "other is null");
return zip(this, other, zipper);
} | [
"@",
"CheckReturnValue",
"@",
"SchedulerSupport",
"(",
"SchedulerSupport",
".",
"NONE",
")",
"public",
"final",
"<",
"U",
",",
"R",
">",
"Maybe",
"<",
"R",
">",
"zipWith",
"(",
"MaybeSource",
"<",
"?",
"extends",
"U",
">",
"other",
",",
"BiFunction",
"<"... | Waits until this and the other MaybeSource signal a success value then applies the given BiFunction
to those values and emits the BiFunction's resulting value to downstream.
<img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.png" alt="">
<p>If either this or the other MaybeSource is empty or signals an error, the resulting Maybe will
terminate immediately and dispose the other source.
<dl>
<dt><b>Scheduler:</b></dt>
<dd>{@code zipWith} does not operate by default on a particular {@link Scheduler}.</dd>
</dl>
@param <U>
the type of items emitted by the {@code other} MaybeSource
@param <R>
the type of items emitted by the resulting Maybe
@param other
the other MaybeSource
@param zipper
a function that combines the pairs of items from the two MaybeSources to generate the items to
be emitted by the resulting Maybe
@return the new Maybe instance
@see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> | [
"Waits",
"until",
"this",
"and",
"the",
"other",
"MaybeSource",
"signal",
"a",
"success",
"value",
"then",
"applies",
"the",
"given",
"BiFunction",
"to",
"those",
"values",
"and",
"emits",
"the",
"BiFunction",
"s",
"resulting",
"value",
"to",
"downstream",
"."... | train | https://github.com/intendia-oss/rxjava-gwt/blob/8d5635b12ce40da99e76b59dc6bfe6fc2fffc1fa/src/main/modified/io/reactivex/super/io/reactivex/Maybe.java#L4568-L4573 |
synchronoss/cpo-api | cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java | CassandraCpoAdapter.getGroupType | protected <T> String getGroupType(T obj, String type, String name, Session session) throws CpoException {
String retType = type;
long objCount;
if (CpoAdapter.PERSIST_GROUP.equals(retType)) {
objCount = existsObject(name, obj, session, null);
if (objCount == 0) {
retType = CpoAdapter.CREATE_GROUP;
} else if (objCount == 1) {
retType = CpoAdapter.UPDATE_GROUP;
} else {
throw new CpoException("Persist can only UPDATE one record. Your EXISTS function returned 2 or more.");
}
}
return retType;
} | java | protected <T> String getGroupType(T obj, String type, String name, Session session) throws CpoException {
String retType = type;
long objCount;
if (CpoAdapter.PERSIST_GROUP.equals(retType)) {
objCount = existsObject(name, obj, session, null);
if (objCount == 0) {
retType = CpoAdapter.CREATE_GROUP;
} else if (objCount == 1) {
retType = CpoAdapter.UPDATE_GROUP;
} else {
throw new CpoException("Persist can only UPDATE one record. Your EXISTS function returned 2 or more.");
}
}
return retType;
} | [
"protected",
"<",
"T",
">",
"String",
"getGroupType",
"(",
"T",
"obj",
",",
"String",
"type",
",",
"String",
"name",
",",
"Session",
"session",
")",
"throws",
"CpoException",
"{",
"String",
"retType",
"=",
"type",
";",
"long",
"objCount",
";",
"if",
"(",... | DOCUMENT ME!
@param obj DOCUMENT ME!
@param type DOCUMENT ME!
@param name DOCUMENT ME!
@param session DOCUMENT ME!
@return DOCUMENT ME!
@throws CpoException DOCUMENT ME! | [
"DOCUMENT",
"ME!"
] | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L2473-L2490 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java | SAX2DTM2.copyAttributes | protected final void copyAttributes(final int nodeID, SerializationHandler handler)
throws SAXException{
for(int current = getFirstAttributeIdentity(nodeID); current != DTM.NULL; current = getNextAttributeIdentity(current)){
int eType = _exptype2(current);
copyAttribute(current, eType, handler);
}
} | java | protected final void copyAttributes(final int nodeID, SerializationHandler handler)
throws SAXException{
for(int current = getFirstAttributeIdentity(nodeID); current != DTM.NULL; current = getNextAttributeIdentity(current)){
int eType = _exptype2(current);
copyAttribute(current, eType, handler);
}
} | [
"protected",
"final",
"void",
"copyAttributes",
"(",
"final",
"int",
"nodeID",
",",
"SerializationHandler",
"handler",
")",
"throws",
"SAXException",
"{",
"for",
"(",
"int",
"current",
"=",
"getFirstAttributeIdentity",
"(",
"nodeID",
")",
";",
"current",
"!=",
"... | Copy attribute nodes from an element .
@param nodeID The Element node identity
@param handler The SerializationHandler | [
"Copy",
"attribute",
"nodes",
"from",
"an",
"element",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/dtm/ref/sax2dtm/SAX2DTM2.java#L3326-L3333 |
landawn/AbacusUtil | src/com/landawn/abacus/util/Fraction.java | Fraction.subAndCheck | private static int subAndCheck(final int x, final int y) {
final long s = (long) x - (long) y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: add");
}
return (int) s;
} | java | private static int subAndCheck(final int x, final int y) {
final long s = (long) x - (long) y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
throw new ArithmeticException("overflow: add");
}
return (int) s;
} | [
"private",
"static",
"int",
"subAndCheck",
"(",
"final",
"int",
"x",
",",
"final",
"int",
"y",
")",
"{",
"final",
"long",
"s",
"=",
"(",
"long",
")",
"x",
"-",
"(",
"long",
")",
"y",
";",
"if",
"(",
"s",
"<",
"Integer",
".",
"MIN_VALUE",
"||",
... | Subtract two integers, checking for overflow.
@param x
the minuend
@param y
the subtrahend
@return the difference <code>x-y</code>
@throws ArithmeticException
if the result can not be represented as an int | [
"Subtract",
"two",
"integers",
"checking",
"for",
"overflow",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Fraction.java#L819-L825 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java | HttpPostRequestEncoder.addBodyFileUpload | public void addBodyFileUpload(String name, File file, String contentType, boolean isText)
throws ErrorDataEncoderException {
addBodyFileUpload(name, file.getName(), file, contentType, isText);
} | java | public void addBodyFileUpload(String name, File file, String contentType, boolean isText)
throws ErrorDataEncoderException {
addBodyFileUpload(name, file.getName(), file, contentType, isText);
} | [
"public",
"void",
"addBodyFileUpload",
"(",
"String",
"name",
",",
"File",
"file",
",",
"String",
"contentType",
",",
"boolean",
"isText",
")",
"throws",
"ErrorDataEncoderException",
"{",
"addBodyFileUpload",
"(",
"name",
",",
"file",
".",
"getName",
"(",
")",
... | Add a file as a FileUpload
@param name
the name of the parameter
@param file
the file to be uploaded (if not Multipart mode, only the filename will be included)
@param contentType
the associated contentType for the File
@param isText
True if this file should be transmitted in Text format (else binary)
@throws NullPointerException
for name and file
@throws ErrorDataEncoderException
if the encoding is in error or if the finalize were already done | [
"Add",
"a",
"file",
"as",
"a",
"FileUpload"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/multipart/HttpPostRequestEncoder.java#L360-L363 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java | SimpleDocTreeVisitor.visitProvides | @Override
public R visitProvides(ProvidesTree node, P p) {
return defaultAction(node, p);
} | java | @Override
public R visitProvides(ProvidesTree node, P p) {
return defaultAction(node, p);
} | [
"@",
"Override",
"public",
"R",
"visitProvides",
"(",
"ProvidesTree",
"node",
",",
"P",
"p",
")",
"{",
"return",
"defaultAction",
"(",
"node",
",",
"p",
")",
";",
"}"
] | {@inheritDoc} This implementation calls {@code defaultAction}.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of {@code defaultAction} | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"calls",
"{",
"@code",
"defaultAction",
"}",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/SimpleDocTreeVisitor.java#L297-L300 |
square/android-times-square | library/src/main/java/com/squareup/timessquare/CalendarPickerView.java | CalendarPickerView.selectDate | public boolean selectDate(Date date, boolean smoothScroll) {
validateDate(date);
MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date);
if (monthCellWithMonthIndex == null || !isDateSelectable(date)) {
return false;
}
boolean wasSelected = doSelectDate(date, monthCellWithMonthIndex.cell);
if (wasSelected) {
scrollToSelectedMonth(monthCellWithMonthIndex.monthIndex, smoothScroll);
}
return wasSelected;
} | java | public boolean selectDate(Date date, boolean smoothScroll) {
validateDate(date);
MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date);
if (monthCellWithMonthIndex == null || !isDateSelectable(date)) {
return false;
}
boolean wasSelected = doSelectDate(date, monthCellWithMonthIndex.cell);
if (wasSelected) {
scrollToSelectedMonth(monthCellWithMonthIndex.monthIndex, smoothScroll);
}
return wasSelected;
} | [
"public",
"boolean",
"selectDate",
"(",
"Date",
"date",
",",
"boolean",
"smoothScroll",
")",
"{",
"validateDate",
"(",
"date",
")",
";",
"MonthCellWithMonthIndex",
"monthCellWithMonthIndex",
"=",
"getMonthCellWithIndexByDate",
"(",
"date",
")",
";",
"if",
"(",
"mo... | Select a new date. Respects the {@link SelectionMode} this CalendarPickerView is configured
with: if you are in {@link SelectionMode#SINGLE}, the previously selected date will be
un-selected. In {@link SelectionMode#MULTIPLE}, the new date will be added to the list of
selected dates.
<p>
If the selection was made (selectable date, in range), the view will scroll to the newly
selected date if it's not already visible.
@return - whether we were able to set the date | [
"Select",
"a",
"new",
"date",
".",
"Respects",
"the",
"{",
"@link",
"SelectionMode",
"}",
"this",
"CalendarPickerView",
"is",
"configured",
"with",
":",
"if",
"you",
"are",
"in",
"{",
"@link",
"SelectionMode#SINGLE",
"}",
"the",
"previously",
"selected",
"date... | train | https://github.com/square/android-times-square/blob/83b08e7cc220d587845054cd1471a604d17721f6/library/src/main/java/com/squareup/timessquare/CalendarPickerView.java#L618-L630 |
camunda/camunda-xml-model | src/main/java/org/camunda/bpm/model/xml/impl/util/IoUtil.java | IoUtil.getStringFromInputStream | private static String getStringFromInputStream(InputStream inputStream, boolean trim) throws IOException {
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (trim) {
stringBuilder.append(line.trim());
}
else {
stringBuilder.append(line).append("\n");
}
}
}
finally {
closeSilently(bufferedReader);
}
return stringBuilder.toString();
} | java | private static String getStringFromInputStream(InputStream inputStream, boolean trim) throws IOException {
BufferedReader bufferedReader = null;
StringBuilder stringBuilder = new StringBuilder();
try {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
if (trim) {
stringBuilder.append(line.trim());
}
else {
stringBuilder.append(line).append("\n");
}
}
}
finally {
closeSilently(bufferedReader);
}
return stringBuilder.toString();
} | [
"private",
"static",
"String",
"getStringFromInputStream",
"(",
"InputStream",
"inputStream",
",",
"boolean",
"trim",
")",
"throws",
"IOException",
"{",
"BufferedReader",
"bufferedReader",
"=",
"null",
";",
"StringBuilder",
"stringBuilder",
"=",
"new",
"StringBuilder",
... | Convert an {@link InputStream} to a {@link String}
@param inputStream the {@link InputStream} to convert
@param trim trigger if whitespaces are trimmed in the output
@return the resulting {@link String}
@throws IOException | [
"Convert",
"an",
"{",
"@link",
"InputStream",
"}",
"to",
"a",
"{",
"@link",
"String",
"}"
] | train | https://github.com/camunda/camunda-xml-model/blob/85b3f879e26d063f71c94cfd21ac17d9ff6baf4d/src/main/java/org/camunda/bpm/model/xml/impl/util/IoUtil.java#L61-L81 |
iipc/openwayback-access-control | oracle/src/main/java/org/archive/accesscontrol/oracle/RulesController.java | RulesController.putRule | public ModelAndView putRule(long id, HttpServletRequest request,
HttpServletResponse response) throws IOException {
Rule oldRule = ruleDao.getRule(id);
if (oldRule == null) {
return new ModelAndView(
view,
"object",
new SimpleError(
"Rule "
+ id
+ " does not exist. To create a new rule POST it to /rules",
404));
}
Rule newRule = (Rule) view.deserializeRequest(request);
newRule.setId(id);
String comment = "Changed by REST client: "
+ request.getHeader("User-agent");
if (request.getHeader("Comment") != null) {
comment = request.getHeader("Comment");
}
String user = "" + request.getRemoteUser() + "@"
+ request.getRemoteAddr();
if (request.getHeader("User") != null) {
user = request.getHeader("User") + " via " + user;
}
RuleChange change = new RuleChange(oldRule, RuleChange.UPDATED,
new Date(), user, comment);
change.setRule(newRule);
ruleDao.saveRule(newRule, change);
return new ModelAndView(view, "object", change);
} | java | public ModelAndView putRule(long id, HttpServletRequest request,
HttpServletResponse response) throws IOException {
Rule oldRule = ruleDao.getRule(id);
if (oldRule == null) {
return new ModelAndView(
view,
"object",
new SimpleError(
"Rule "
+ id
+ " does not exist. To create a new rule POST it to /rules",
404));
}
Rule newRule = (Rule) view.deserializeRequest(request);
newRule.setId(id);
String comment = "Changed by REST client: "
+ request.getHeader("User-agent");
if (request.getHeader("Comment") != null) {
comment = request.getHeader("Comment");
}
String user = "" + request.getRemoteUser() + "@"
+ request.getRemoteAddr();
if (request.getHeader("User") != null) {
user = request.getHeader("User") + " via " + user;
}
RuleChange change = new RuleChange(oldRule, RuleChange.UPDATED,
new Date(), user, comment);
change.setRule(newRule);
ruleDao.saveRule(newRule, change);
return new ModelAndView(view, "object", change);
} | [
"public",
"ModelAndView",
"putRule",
"(",
"long",
"id",
",",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"IOException",
"{",
"Rule",
"oldRule",
"=",
"ruleDao",
".",
"getRule",
"(",
"id",
")",
";",
"if",
"(",
"oldRule... | PUT /rules/:id
Updates the rule with the given id, noting the change in the change log.
Optional extra headers: Comment - A comment that will appear in the
change log. User - End-user who requested the change.
@param id
@param request
@param response
@return
@throws IOException | [
"PUT",
"/",
"rules",
"/",
":",
"id"
] | train | https://github.com/iipc/openwayback-access-control/blob/4a0f70f200fd8d7b6e313624b7628656d834bf31/oracle/src/main/java/org/archive/accesscontrol/oracle/RulesController.java#L71-L106 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/Assert.java | Assert.isNotAssignableTo | @NullSafe
private static boolean isNotAssignableTo(Class<?> from, Class<?> to) {
return to == null || (from != null && !to.isAssignableFrom(from));
} | java | @NullSafe
private static boolean isNotAssignableTo(Class<?> from, Class<?> to) {
return to == null || (from != null && !to.isAssignableFrom(from));
} | [
"@",
"NullSafe",
"private",
"static",
"boolean",
"isNotAssignableTo",
"(",
"Class",
"<",
"?",
">",
"from",
",",
"Class",
"<",
"?",
">",
"to",
")",
"{",
"return",
"to",
"==",
"null",
"||",
"(",
"from",
"!=",
"null",
"&&",
"!",
"to",
".",
"isAssignable... | Determines whether the {@link Class 'from' class type} is assignable to the {@link Class 'to' class type}.
@param from {@link Class class type} being evaluated for assignment compatibility
with the {@link Class 'to' class type}.
@param to {@link Class class type} used to determine if the {@link Class 'from' class type}
is assignment compatible.
@return a boolean value indicating whether the {@link Class 'from' class type} is assignable to
the {@link Class 'to' class type}.
@see java.lang.Class#isAssignableFrom(Class) | [
"Determines",
"whether",
"the",
"{",
"@link",
"Class",
"from",
"class",
"type",
"}",
"is",
"assignable",
"to",
"the",
"{",
"@link",
"Class",
"to",
"class",
"type",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/Assert.java#L601-L604 |
evernote/android-state | library/src/main/java/com/evernote/android/state/StateSaver.java | StateSaver.restoreInstanceState | public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
IMPL.restoreInstanceState(target, state);
} | java | public static <T> void restoreInstanceState(@NonNull T target, @Nullable Bundle state) {
IMPL.restoreInstanceState(target, state);
} | [
"public",
"static",
"<",
"T",
">",
"void",
"restoreInstanceState",
"(",
"@",
"NonNull",
"T",
"target",
",",
"@",
"Nullable",
"Bundle",
"state",
")",
"{",
"IMPL",
".",
"restoreInstanceState",
"(",
"target",
",",
"state",
")",
";",
"}"
] | Restore the given {@code target} from the passed in {@link Bundle}.
@param target The object containing fields annotated with {@link State}.
@param state The object is being restored from this bundle. Nothing is restored if the argument is {@code null}. | [
"Restore",
"the",
"given",
"{",
"@code",
"target",
"}",
"from",
"the",
"passed",
"in",
"{",
"@link",
"Bundle",
"}",
"."
] | train | https://github.com/evernote/android-state/blob/6d56c0c5709f330324ec23d39c3f70c9d59bf6d3/library/src/main/java/com/evernote/android/state/StateSaver.java#L51-L53 |
Kurento/kurento-module-creator | src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java | ExpressionParser.parseBooleanExpression | private Expression parseBooleanExpression(Expression expr) {
if (tokens.positiveLookahead(AND)) {
tokens.consume();
expr = new And(expr, parseSemVerExpression());
} else if (tokens.positiveLookahead(OR)) {
tokens.consume();
expr = new Or(expr, parseSemVerExpression());
}
return expr;
} | java | private Expression parseBooleanExpression(Expression expr) {
if (tokens.positiveLookahead(AND)) {
tokens.consume();
expr = new And(expr, parseSemVerExpression());
} else if (tokens.positiveLookahead(OR)) {
tokens.consume();
expr = new Or(expr, parseSemVerExpression());
}
return expr;
} | [
"private",
"Expression",
"parseBooleanExpression",
"(",
"Expression",
"expr",
")",
"{",
"if",
"(",
"tokens",
".",
"positiveLookahead",
"(",
"AND",
")",
")",
"{",
"tokens",
".",
"consume",
"(",
")",
";",
"expr",
"=",
"new",
"And",
"(",
"expr",
",",
"parse... | Parses the {@literal <boolean-expr>} non-terminal.
<pre>
{@literal
<boolean-expr> ::= <boolean-op> <semver-expr>
| <epsilon>
}
</pre>
@param expr
the left-hand expression of the logical operators
@return the expression AST | [
"Parses",
"the",
"{",
"@literal",
"<boolean",
"-",
"expr",
">",
"}",
"non",
"-",
"terminal",
"."
] | train | https://github.com/Kurento/kurento-module-creator/blob/c371516c665b902b5476433496a5aefcbca86d64/src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java#L154-L163 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java | ExtractionUtil.extractArchive | private static void extractArchive(ArchiveInputStream input,
File destination, FilenameFilter filter)
throws ArchiveExtractionException {
ArchiveEntry entry;
try {
final String destPath = destination.getCanonicalPath();
while ((entry = input.getNextEntry()) != null) {
if (entry.isDirectory()) {
final File dir = new File(destination, entry.getName());
if (!dir.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive contains a path (%s) that would be extracted outside of the target directory.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
if (!dir.exists() && !dir.mkdirs()) {
final String msg = String.format(
"Unable to create directory '%s'.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
} else {
extractFile(input, destination, filter, entry);
}
}
} catch (IOException | AnalysisException ex) {
throw new ArchiveExtractionException(ex);
} finally {
FileUtils.close(input);
}
} | java | private static void extractArchive(ArchiveInputStream input,
File destination, FilenameFilter filter)
throws ArchiveExtractionException {
ArchiveEntry entry;
try {
final String destPath = destination.getCanonicalPath();
while ((entry = input.getNextEntry()) != null) {
if (entry.isDirectory()) {
final File dir = new File(destination, entry.getName());
if (!dir.getCanonicalPath().startsWith(destPath)) {
final String msg = String.format(
"Archive contains a path (%s) that would be extracted outside of the target directory.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
if (!dir.exists() && !dir.mkdirs()) {
final String msg = String.format(
"Unable to create directory '%s'.",
dir.getAbsolutePath());
throw new AnalysisException(msg);
}
} else {
extractFile(input, destination, filter, entry);
}
}
} catch (IOException | AnalysisException ex) {
throw new ArchiveExtractionException(ex);
} finally {
FileUtils.close(input);
}
} | [
"private",
"static",
"void",
"extractArchive",
"(",
"ArchiveInputStream",
"input",
",",
"File",
"destination",
",",
"FilenameFilter",
"filter",
")",
"throws",
"ArchiveExtractionException",
"{",
"ArchiveEntry",
"entry",
";",
"try",
"{",
"final",
"String",
"destPath",
... | Extracts files from an archive.
@param input the archive to extract files from
@param destination the location to write the files too
@param filter determines which files get extracted
@throws ArchiveExtractionException thrown if there is an exception
extracting files from the archive | [
"Extracts",
"files",
"from",
"an",
"archive",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/utils/ExtractionUtil.java#L235-L266 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.rotationAround | public Matrix4d rotationAround(Quaterniondc quat, double ox, double oy, double oz) {
double w2 = quat.w() * quat.w(), x2 = quat.x() * quat.x();
double y2 = quat.y() * quat.y(), z2 = quat.z() * quat.z();
double zw = quat.z() * quat.w(), dzw = zw + zw, xy = quat.x() * quat.y(), dxy = xy + xy;
double xz = quat.x() * quat.z(), dxz = xz + xz, yw = quat.y() * quat.w(), dyw = yw + yw;
double yz = quat.y() * quat.z(), dyz = yz + yz, xw = quat.x() * quat.w(), dxw = xw + xw;
this._m20(dyw + dxz);
this._m21(dyz - dxw);
this._m22(z2 - y2 - x2 + w2);
this._m23(0.0);
this._m00(w2 + x2 - z2 - y2);
this._m01(dxy + dzw);
this._m02(dxz - dyw);
this._m03(0.0);
this._m10(-dzw + dxy);
this._m11(y2 - z2 + w2 - x2);
this._m12(dyz + dxw);
this._m13(0.0);
this._m30(-m00 * ox - m10 * oy - m20 * oz + ox);
this._m31(-m01 * ox - m11 * oy - m21 * oz + oy);
this._m32(-m02 * ox - m12 * oy - m22 * oz + oz);
this._m33(1.0);
this.properties = PROPERTY_AFFINE | PROPERTY_ORTHONORMAL;
return this;
} | java | public Matrix4d rotationAround(Quaterniondc quat, double ox, double oy, double oz) {
double w2 = quat.w() * quat.w(), x2 = quat.x() * quat.x();
double y2 = quat.y() * quat.y(), z2 = quat.z() * quat.z();
double zw = quat.z() * quat.w(), dzw = zw + zw, xy = quat.x() * quat.y(), dxy = xy + xy;
double xz = quat.x() * quat.z(), dxz = xz + xz, yw = quat.y() * quat.w(), dyw = yw + yw;
double yz = quat.y() * quat.z(), dyz = yz + yz, xw = quat.x() * quat.w(), dxw = xw + xw;
this._m20(dyw + dxz);
this._m21(dyz - dxw);
this._m22(z2 - y2 - x2 + w2);
this._m23(0.0);
this._m00(w2 + x2 - z2 - y2);
this._m01(dxy + dzw);
this._m02(dxz - dyw);
this._m03(0.0);
this._m10(-dzw + dxy);
this._m11(y2 - z2 + w2 - x2);
this._m12(dyz + dxw);
this._m13(0.0);
this._m30(-m00 * ox - m10 * oy - m20 * oz + ox);
this._m31(-m01 * ox - m11 * oy - m21 * oz + oy);
this._m32(-m02 * ox - m12 * oy - m22 * oz + oz);
this._m33(1.0);
this.properties = PROPERTY_AFFINE | PROPERTY_ORTHONORMAL;
return this;
} | [
"public",
"Matrix4d",
"rotationAround",
"(",
"Quaterniondc",
"quat",
",",
"double",
"ox",
",",
"double",
"oy",
",",
"double",
"oz",
")",
"{",
"double",
"w2",
"=",
"quat",
".",
"w",
"(",
")",
"*",
"quat",
".",
"w",
"(",
")",
",",
"x2",
"=",
"quat",
... | Set this matrix to a transformation composed of a rotation of the specified {@link Quaterniondc} while using <code>(ox, oy, oz)</code> as the rotation origin.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
This method is equivalent to calling: <code>translation(ox, oy, oz).rotate(quat).translate(-ox, -oy, -oz)</code>
<p>
Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion">http://en.wikipedia.org</a>
@param quat
the {@link Quaterniondc}
@param ox
the x coordinate of the rotation origin
@param oy
the y coordinate of the rotation origin
@param oz
the z coordinate of the rotation origin
@return this | [
"Set",
"this",
"matrix",
"to",
"a",
"transformation",
"composed",
"of",
"a",
"rotation",
"of",
"the",
"specified",
"{",
"@link",
"Quaterniondc",
"}",
"while",
"using",
"<code",
">",
"(",
"ox",
"oy",
"oz",
")",
"<",
"/",
"code",
">",
"as",
"the",
"rotat... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L5133-L5157 |
helun/Ektorp | org.ektorp/src/main/java/org/ektorp/util/ReflectionUtils.java | ReflectionUtils.findMethod | public static Method findMethod(Class<?> clazz, String name) {
for (Method me : clazz.getDeclaredMethods()) {
if (me.getName().equalsIgnoreCase(name)) {
return me;
}
}
if (clazz.getSuperclass() != null) {
return findMethod(clazz.getSuperclass(), name);
}
return null;
} | java | public static Method findMethod(Class<?> clazz, String name) {
for (Method me : clazz.getDeclaredMethods()) {
if (me.getName().equalsIgnoreCase(name)) {
return me;
}
}
if (clazz.getSuperclass() != null) {
return findMethod(clazz.getSuperclass(), name);
}
return null;
} | [
"public",
"static",
"Method",
"findMethod",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"name",
")",
"{",
"for",
"(",
"Method",
"me",
":",
"clazz",
".",
"getDeclaredMethods",
"(",
")",
")",
"{",
"if",
"(",
"me",
".",
"getName",
"(",
")",
"... | Ignores case when comparing method names
@param clazz
@param name
@return | [
"Ignores",
"case",
"when",
"comparing",
"method",
"names"
] | train | https://github.com/helun/Ektorp/blob/b822c0d656aefb90a5e0cb5ec2de3daa969e3eaa/org.ektorp/src/main/java/org/ektorp/util/ReflectionUtils.java#L77-L87 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/modal/ModalRenderer.java | ModalRenderer.encodeEnd | @Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter rw = context.getResponseWriter();
rw.endElement("div"); // modal-body
String cid=component.getClientId(context);
UIComponent foot = component.getFacet("footer");
if (foot != null) {
rw.startElement("div", component); // modal-footer
rw.writeAttribute("id", cid+"_footer", "id");
rw.writeAttribute("class", "modal-footer", "class");
foot.encodeAll(context);
rw.endElement("div"); // modal-footer
}
rw.endElement("div"); // modal-content
rw.endElement("div"); // modal-dialog
rw.endElement("div"); // modal
initModal(rw, cid);
} | java | @Override
public void encodeEnd(FacesContext context, UIComponent component)
throws IOException {
if (!component.isRendered()) {
return;
}
ResponseWriter rw = context.getResponseWriter();
rw.endElement("div"); // modal-body
String cid=component.getClientId(context);
UIComponent foot = component.getFacet("footer");
if (foot != null) {
rw.startElement("div", component); // modal-footer
rw.writeAttribute("id", cid+"_footer", "id");
rw.writeAttribute("class", "modal-footer", "class");
foot.encodeAll(context);
rw.endElement("div"); // modal-footer
}
rw.endElement("div"); // modal-content
rw.endElement("div"); // modal-dialog
rw.endElement("div"); // modal
initModal(rw, cid);
} | [
"@",
"Override",
"public",
"void",
"encodeEnd",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"component",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"ResponseWriter",
"rw"... | This methods generates the HTML code of the current b:modal.
<code>encodeBegin</code> generates the start of the component. After the,
the JSF framework calls <code>encodeChildren()</code> to generate the
HTML code between the beginning and the end of the component. For
instance, in the case of a panel component the content of the panel is
generated by <code>encodeChildren()</code>. After that,
<code>encodeEnd()</code> is called to generate the rest of the HTML code.
@param context
the FacesContext.
@param component
the current b:modal.
@throws IOException
thrown if something goes wrong when writing the HTML code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"modal",
".",
"<code",
">",
"encodeBegin<",
"/",
"code",
">",
"generates",
"the",
"start",
"of",
"the",
"component",
".",
"After",
"the",
"the",
"JSF",
"framework",
... | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/modal/ModalRenderer.java#L175-L200 |
Waikato/moa | moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java | CuckooHashing.fileElement | private void fileElement(Entry<T> currentElement, boolean rehash) {
int maxFailures = Math.max((int) Math.log(this.numElements),
this.numTables * 2);
int currentTable = 0;
for (int i = 0; i < maxFailures; i++) {
int hash = this.hashfunctions.get(currentTable).hash(
currentElement.getKey());
currentElement = this.tables.get(currentTable).set(hash,
currentElement);
if (currentElement == null) {
break;
}
currentTable = (currentTable + 1) % this.numTables;
}
if (currentElement != null) {
this.stash.add(currentElement);
this.stashSize++;
}
while (rehash && this.stashSize > this.maxStashSize) {
reset();
if (this.stashSize > this.maxStashSize) {
increaseAndReset();
}
}
} | java | private void fileElement(Entry<T> currentElement, boolean rehash) {
int maxFailures = Math.max((int) Math.log(this.numElements),
this.numTables * 2);
int currentTable = 0;
for (int i = 0; i < maxFailures; i++) {
int hash = this.hashfunctions.get(currentTable).hash(
currentElement.getKey());
currentElement = this.tables.get(currentTable).set(hash,
currentElement);
if (currentElement == null) {
break;
}
currentTable = (currentTable + 1) % this.numTables;
}
if (currentElement != null) {
this.stash.add(currentElement);
this.stashSize++;
}
while (rehash && this.stashSize > this.maxStashSize) {
reset();
if (this.stashSize > this.maxStashSize) {
increaseAndReset();
}
}
} | [
"private",
"void",
"fileElement",
"(",
"Entry",
"<",
"T",
">",
"currentElement",
",",
"boolean",
"rehash",
")",
"{",
"int",
"maxFailures",
"=",
"Math",
".",
"max",
"(",
"(",
"int",
")",
"Math",
".",
"log",
"(",
"this",
".",
"numElements",
")",
",",
"... | Adds an element to one of the tables for Cuckoo Hashing.
@param currentElement
entry to add in a table
@param rehash
if <code>true</code> the hash table will be rebuild when the
stash became too big. | [
"Adds",
"an",
"element",
"to",
"one",
"of",
"the",
"tables",
"for",
"Cuckoo",
"Hashing",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/CuckooHashing.java#L132-L156 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java | NetworkEnvironmentConfiguration.calculateNetworkBufferMemory | @SuppressWarnings("deprecation")
public static long calculateNetworkBufferMemory(long totalJavaMemorySize, Configuration config) {
final int segmentSize = getPageSize(config);
final long networkBufBytes;
if (hasNewNetworkConfig(config)) {
float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION);
long networkBufSize = (long) (totalJavaMemorySize * networkBufFraction);
networkBufBytes = calculateNewNetworkBufferMemory(config, networkBufSize, totalJavaMemorySize);
} else {
// use old (deprecated) network buffers parameter
int numNetworkBuffers = config.getInteger(TaskManagerOptions.NETWORK_NUM_BUFFERS);
networkBufBytes = (long) numNetworkBuffers * (long) segmentSize;
checkOldNetworkConfig(numNetworkBuffers);
ConfigurationParserUtils.checkConfigParameter(networkBufBytes < totalJavaMemorySize,
networkBufBytes, TaskManagerOptions.NETWORK_NUM_BUFFERS.key(),
"Network buffer memory size too large: " + networkBufBytes + " >= " +
totalJavaMemorySize + " (total JVM memory size)");
}
return networkBufBytes;
} | java | @SuppressWarnings("deprecation")
public static long calculateNetworkBufferMemory(long totalJavaMemorySize, Configuration config) {
final int segmentSize = getPageSize(config);
final long networkBufBytes;
if (hasNewNetworkConfig(config)) {
float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION);
long networkBufSize = (long) (totalJavaMemorySize * networkBufFraction);
networkBufBytes = calculateNewNetworkBufferMemory(config, networkBufSize, totalJavaMemorySize);
} else {
// use old (deprecated) network buffers parameter
int numNetworkBuffers = config.getInteger(TaskManagerOptions.NETWORK_NUM_BUFFERS);
networkBufBytes = (long) numNetworkBuffers * (long) segmentSize;
checkOldNetworkConfig(numNetworkBuffers);
ConfigurationParserUtils.checkConfigParameter(networkBufBytes < totalJavaMemorySize,
networkBufBytes, TaskManagerOptions.NETWORK_NUM_BUFFERS.key(),
"Network buffer memory size too large: " + networkBufBytes + " >= " +
totalJavaMemorySize + " (total JVM memory size)");
}
return networkBufBytes;
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"public",
"static",
"long",
"calculateNetworkBufferMemory",
"(",
"long",
"totalJavaMemorySize",
",",
"Configuration",
"config",
")",
"{",
"final",
"int",
"segmentSize",
"=",
"getPageSize",
"(",
"config",
")",
";"... | Calculates the amount of memory used for network buffers based on the total memory to use and
the according configuration parameters.
<p>The following configuration parameters are involved:
<ul>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_FRACTION},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MIN},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MAX}, and</li>
<li>{@link TaskManagerOptions#NETWORK_NUM_BUFFERS} (fallback if the ones above do not exist)</li>
</ul>.
@param totalJavaMemorySize overall available memory to use (in bytes)
@param config configuration object
@return memory to use for network buffers (in bytes) | [
"Calculates",
"the",
"amount",
"of",
"memory",
"used",
"for",
"network",
"buffers",
"based",
"on",
"the",
"total",
"memory",
"to",
"use",
"and",
"the",
"according",
"configuration",
"parameters",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java#L236-L259 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.jwt/src/com/ibm/ws/security/jwt/web/JwtEndpointServices.java | JwtEndpointServices.processTokenRequest | private void processTokenRequest(HttpServletResponse response, JwtConfig jwtConfig) throws IOException {
String tokenString = new TokenBuilder().createTokenString(jwtConfig);
addNoCacheHeaders(response);
response.setStatus(200);
if (tokenString == null) {
return;
}
try {
PrintWriter pw = response.getWriter();
response.setHeader(WebConstants.HTTP_HEADER_CONTENT_TYPE, WebConstants.HTTP_CONTENT_TYPE_JSON);
pw.write("{\"token\": \"" + tokenString + "\"}");
pw.flush();
pw.close();
} catch (IOException e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Caught an exception attempting to get the response writer: " + e.getLocalizedMessage());
}
}
} | java | private void processTokenRequest(HttpServletResponse response, JwtConfig jwtConfig) throws IOException {
String tokenString = new TokenBuilder().createTokenString(jwtConfig);
addNoCacheHeaders(response);
response.setStatus(200);
if (tokenString == null) {
return;
}
try {
PrintWriter pw = response.getWriter();
response.setHeader(WebConstants.HTTP_HEADER_CONTENT_TYPE, WebConstants.HTTP_CONTENT_TYPE_JSON);
pw.write("{\"token\": \"" + tokenString + "\"}");
pw.flush();
pw.close();
} catch (IOException e) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, "Caught an exception attempting to get the response writer: " + e.getLocalizedMessage());
}
}
} | [
"private",
"void",
"processTokenRequest",
"(",
"HttpServletResponse",
"response",
",",
"JwtConfig",
"jwtConfig",
")",
"throws",
"IOException",
"{",
"String",
"tokenString",
"=",
"new",
"TokenBuilder",
"(",
")",
".",
"createTokenString",
"(",
"jwtConfig",
")",
";",
... | produces a JWT token based upon the jwt Configuration, and the security
credentials of the authenticated user that called this method. Returns
the token as JSON in the response.
@param response
@param jwtConfig
@throws IOException | [
"produces",
"a",
"JWT",
"token",
"based",
"upon",
"the",
"jwt",
"Configuration",
"and",
"the",
"security",
"credentials",
"of",
"the",
"authenticated",
"user",
"that",
"called",
"this",
"method",
".",
"Returns",
"the",
"token",
"as",
"JSON",
"in",
"the",
"re... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.jwt/src/com/ibm/ws/security/jwt/web/JwtEndpointServices.java#L224-L244 |
apereo/cas | support/cas-server-support-ws-sts-api/src/main/java/org/apereo/cas/authentication/SecurityTokenServiceClientBuilder.java | SecurityTokenServiceClientBuilder.buildClientForSecurityTokenRequests | public SecurityTokenServiceClient buildClientForSecurityTokenRequests(final WSFederationRegisteredService service) {
val cxfBus = BusFactory.getDefaultBus();
val sts = new SecurityTokenServiceClient(cxfBus);
sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));
sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
sts.setWsdlLocation(prepareWsdlLocation(service));
if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
sts.setWspNamespace(service.getPolicyNamespace());
}
val namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
sts.setServiceQName(new QName(namespace, StringUtils.defaultIfBlank(service.getWsdlService(), WSFederationConstants.SECURITY_TOKEN_SERVICE)));
sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
sts.getProperties().putAll(new HashMap<>());
return sts;
} | java | public SecurityTokenServiceClient buildClientForSecurityTokenRequests(final WSFederationRegisteredService service) {
val cxfBus = BusFactory.getDefaultBus();
val sts = new SecurityTokenServiceClient(cxfBus);
sts.setAddressingNamespace(StringUtils.defaultIfBlank(service.getAddressingNamespace(), WSFederationConstants.HTTP_WWW_W3_ORG_2005_08_ADDRESSING));
sts.setTokenType(StringUtils.defaultIfBlank(service.getTokenType(), WSConstants.WSS_SAML2_TOKEN_TYPE));
sts.setKeyType(WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER);
sts.setWsdlLocation(prepareWsdlLocation(service));
if (StringUtils.isNotBlank(service.getPolicyNamespace())) {
sts.setWspNamespace(service.getPolicyNamespace());
}
val namespace = StringUtils.defaultIfBlank(service.getNamespace(), WSFederationConstants.HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512);
sts.setServiceQName(new QName(namespace, StringUtils.defaultIfBlank(service.getWsdlService(), WSFederationConstants.SECURITY_TOKEN_SERVICE)));
sts.setEndpointQName(new QName(namespace, service.getWsdlEndpoint()));
sts.getProperties().putAll(new HashMap<>());
return sts;
} | [
"public",
"SecurityTokenServiceClient",
"buildClientForSecurityTokenRequests",
"(",
"final",
"WSFederationRegisteredService",
"service",
")",
"{",
"val",
"cxfBus",
"=",
"BusFactory",
".",
"getDefaultBus",
"(",
")",
";",
"val",
"sts",
"=",
"new",
"SecurityTokenServiceClien... | Build client for security token requests.
@param service the rp
@return the security token service client | [
"Build",
"client",
"for",
"security",
"token",
"requests",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-ws-sts-api/src/main/java/org/apereo/cas/authentication/SecurityTokenServiceClientBuilder.java#L34-L49 |
alibaba/jstorm | jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/ZookeeperUtils.java | ZookeeperUtils.buildQuorum | public static String buildQuorum(List<HostAndPort> hostAndPorts, int defaultPort) {
List<String> entries = new ArrayList<String>(hostAndPorts.size());
for (HostAndPort hostAndPort : hostAndPorts) {
entries.add(buildQuorumEntry(hostAndPort, defaultPort));
}
return JstormYarnUtils.join(entries, ",", false);
} | java | public static String buildQuorum(List<HostAndPort> hostAndPorts, int defaultPort) {
List<String> entries = new ArrayList<String>(hostAndPorts.size());
for (HostAndPort hostAndPort : hostAndPorts) {
entries.add(buildQuorumEntry(hostAndPort, defaultPort));
}
return JstormYarnUtils.join(entries, ",", false);
} | [
"public",
"static",
"String",
"buildQuorum",
"(",
"List",
"<",
"HostAndPort",
">",
"hostAndPorts",
",",
"int",
"defaultPort",
")",
"{",
"List",
"<",
"String",
">",
"entries",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
"hostAndPorts",
".",
"size",
"(... | Build a quorum list, injecting a ":defaultPort" ref if needed on
any entry without one
@param hostAndPorts
@param defaultPort
@return | [
"Build",
"a",
"quorum",
"list",
"injecting",
"a",
":",
"defaultPort",
"ref",
"if",
"needed",
"on",
"any",
"entry",
"without",
"one"
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/ZookeeperUtils.java#L114-L120 |
xmlet/XsdAsmFaster | src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java | XsdAsmInterfaces.createElement | private void createElement(XsdElement element, String apiName) {
String elementName = element.getName();
if (!createdElements.containsKey(getCleanName(elementName))){
createdElements.put(getCleanName(elementName), element);
xsdAsmInstance.generateClassFromElement(element, apiName);
}
} | java | private void createElement(XsdElement element, String apiName) {
String elementName = element.getName();
if (!createdElements.containsKey(getCleanName(elementName))){
createdElements.put(getCleanName(elementName), element);
xsdAsmInstance.generateClassFromElement(element, apiName);
}
} | [
"private",
"void",
"createElement",
"(",
"XsdElement",
"element",
",",
"String",
"apiName",
")",
"{",
"String",
"elementName",
"=",
"element",
".",
"getName",
"(",
")",
";",
"if",
"(",
"!",
"createdElements",
".",
"containsKey",
"(",
"getCleanName",
"(",
"el... | Creates a class based on a {@link XsdElement} if it wasn't been already.
@param element The element that serves as base to creating the class.
@param apiName The name of the generated fluent interface. | [
"Creates",
"a",
"class",
"based",
"on",
"a",
"{"
] | train | https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdAsmInterfaces.java#L798-L805 |
OrienteerBAP/orientdb-oda-birt | org.orienteer.birt.orientdb.ui/src/org/orienteer/birt/orientdb/ui/impl/CustomDataSetWizardPage.java | CustomDataSetWizardPage.validateData | private void validateData( )
{
boolean isValid = ( m_queryTextField != null &&
getQueryText() != null && getQueryText().trim().length() > 0 );
if( isValid )
setMessage( DEFAULT_MESSAGE );
else
setMessage( "Requires input value.", ERROR );
setPageComplete( isValid );
} | java | private void validateData( )
{
boolean isValid = ( m_queryTextField != null &&
getQueryText() != null && getQueryText().trim().length() > 0 );
if( isValid )
setMessage( DEFAULT_MESSAGE );
else
setMessage( "Requires input value.", ERROR );
setPageComplete( isValid );
} | [
"private",
"void",
"validateData",
"(",
")",
"{",
"boolean",
"isValid",
"=",
"(",
"m_queryTextField",
"!=",
"null",
"&&",
"getQueryText",
"(",
")",
"!=",
"null",
"&&",
"getQueryText",
"(",
")",
".",
"trim",
"(",
")",
".",
"length",
"(",
")",
">",
"0",
... | Validates the user-defined value in the page control exists
and not a blank text.
Set page message accordingly. | [
"Validates",
"the",
"user",
"-",
"defined",
"value",
"in",
"the",
"page",
"control",
"exists",
"and",
"not",
"a",
"blank",
"text",
".",
"Set",
"page",
"message",
"accordingly",
"."
] | train | https://github.com/OrienteerBAP/orientdb-oda-birt/blob/62820c256fa1d221265e68b8ebb60f291a9a1405/org.orienteer.birt.orientdb.ui/src/org/orienteer/birt/orientdb/ui/impl/CustomDataSetWizardPage.java#L201-L212 |
mangstadt/biweekly | src/main/java/biweekly/util/XmlUtils.java | XmlUtils.hasQName | public static boolean hasQName(Node node, QName qname) {
return qname.getNamespaceURI().equals(node.getNamespaceURI()) && qname.getLocalPart().equals(node.getLocalName());
} | java | public static boolean hasQName(Node node, QName qname) {
return qname.getNamespaceURI().equals(node.getNamespaceURI()) && qname.getLocalPart().equals(node.getLocalName());
} | [
"public",
"static",
"boolean",
"hasQName",
"(",
"Node",
"node",
",",
"QName",
"qname",
")",
"{",
"return",
"qname",
".",
"getNamespaceURI",
"(",
")",
".",
"equals",
"(",
"node",
".",
"getNamespaceURI",
"(",
")",
")",
"&&",
"qname",
".",
"getLocalPart",
"... | Determines if a node has a particular qualified name.
@param node the node
@param qname the qualified name
@return true if the node has the given qualified name, false if not | [
"Determines",
"if",
"a",
"node",
"has",
"a",
"particular",
"qualified",
"name",
"."
] | train | https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/util/XmlUtils.java#L352-L354 |
phax/ph-oton | ph-oton-html/src/main/java/com/helger/html/markdown/MarkdownHelper.java | MarkdownHelper.skipSpaces | public static int skipSpaces (final String sIn, final int nStart)
{
int pos = nStart;
while (pos < sIn.length () && (sIn.charAt (pos) == ' ' || sIn.charAt (pos) == '\n'))
pos++;
return pos < sIn.length () ? pos : -1;
} | java | public static int skipSpaces (final String sIn, final int nStart)
{
int pos = nStart;
while (pos < sIn.length () && (sIn.charAt (pos) == ' ' || sIn.charAt (pos) == '\n'))
pos++;
return pos < sIn.length () ? pos : -1;
} | [
"public",
"static",
"int",
"skipSpaces",
"(",
"final",
"String",
"sIn",
",",
"final",
"int",
"nStart",
")",
"{",
"int",
"pos",
"=",
"nStart",
";",
"while",
"(",
"pos",
"<",
"sIn",
".",
"length",
"(",
")",
"&&",
"(",
"sIn",
".",
"charAt",
"(",
"pos"... | Skips spaces in the given String.
@param sIn
Input String.
@param nStart
Starting position.
@return The new position or -1 if EOL has been reached. | [
"Skips",
"spaces",
"in",
"the",
"given",
"String",
"."
] | train | https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-html/src/main/java/com/helger/html/markdown/MarkdownHelper.java#L72-L78 |
Azure/azure-sdk-for-java | network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/SecurityRulesInner.java | SecurityRulesInner.beginCreateOrUpdateAsync | public Observable<SecurityRuleInner> beginCreateOrUpdateAsync(String resourceGroupName, String networkSecurityGroupName, String securityRuleName, SecurityRuleInner securityRuleParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).map(new Func1<ServiceResponse<SecurityRuleInner>, SecurityRuleInner>() {
@Override
public SecurityRuleInner call(ServiceResponse<SecurityRuleInner> response) {
return response.body();
}
});
} | java | public Observable<SecurityRuleInner> beginCreateOrUpdateAsync(String resourceGroupName, String networkSecurityGroupName, String securityRuleName, SecurityRuleInner securityRuleParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, networkSecurityGroupName, securityRuleName, securityRuleParameters).map(new Func1<ServiceResponse<SecurityRuleInner>, SecurityRuleInner>() {
@Override
public SecurityRuleInner call(ServiceResponse<SecurityRuleInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SecurityRuleInner",
">",
"beginCreateOrUpdateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"networkSecurityGroupName",
",",
"String",
"securityRuleName",
",",
"SecurityRuleInner",
"securityRuleParameters",
")",
"{",
"return",
"begi... | Creates or updates a security rule in the specified network security group.
@param resourceGroupName The name of the resource group.
@param networkSecurityGroupName The name of the network security group.
@param securityRuleName The name of the security rule.
@param securityRuleParameters Parameters supplied to the create or update network security rule operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SecurityRuleInner object | [
"Creates",
"or",
"updates",
"a",
"security",
"rule",
"in",
"the",
"specified",
"network",
"security",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/SecurityRulesInner.java#L473-L480 |
jenkinsci/jenkins | core/src/main/java/hudson/scm/SCM.java | SCM.processWorkspaceBeforeDeletion | public boolean processWorkspaceBeforeDeletion(@Nonnull Job<?,?> project, @Nonnull FilePath workspace, @Nonnull Node node) throws IOException, InterruptedException {
if (project instanceof AbstractProject) {
return processWorkspaceBeforeDeletion((AbstractProject) project, workspace, node);
} else {
return true;
}
} | java | public boolean processWorkspaceBeforeDeletion(@Nonnull Job<?,?> project, @Nonnull FilePath workspace, @Nonnull Node node) throws IOException, InterruptedException {
if (project instanceof AbstractProject) {
return processWorkspaceBeforeDeletion((AbstractProject) project, workspace, node);
} else {
return true;
}
} | [
"public",
"boolean",
"processWorkspaceBeforeDeletion",
"(",
"@",
"Nonnull",
"Job",
"<",
"?",
",",
"?",
">",
"project",
",",
"@",
"Nonnull",
"FilePath",
"workspace",
",",
"@",
"Nonnull",
"Node",
"node",
")",
"throws",
"IOException",
",",
"InterruptedException",
... | Called before a workspace is deleted on the given node, to provide SCM an opportunity to perform clean up.
<p>
Hudson periodically scans through all the agents and removes old workspaces that are deemed unnecessary.
This behavior is implemented in {@link WorkspaceCleanupThread}, and it is necessary to control the
disk consumption on agents. If we don't do this, in a long run, all the agents will have workspaces
for all the projects, which will be prohibitive in big Hudson.
<p>
However, some SCM implementations require that the server be made aware of deletion of the local workspace,
and this method provides an opportunity for SCMs to perform such a clean-up act.
<p>
This call back is invoked after Hudson determines that a workspace is unnecessary, but before the actual
recursive directory deletion happens.
<p>
Note that this method does not guarantee that such a clean up will happen. For example, agents can be
taken offline by being physically removed from the network, and in such a case there's no opportunity
to perform this clean up.
<p>
This method is also invoked when the project is deleted.
@param project
The project that owns this {@link SCM}. This is always the same object for a particular instance
of {@link SCM}. Just passed in here so that {@link SCM} itself doesn't have to remember the value.
@param workspace
The workspace which is about to be deleted. This can be a remote file path.
@param node
The node that hosts the workspace. SCM can use this information to determine the course of action.
@return
true if {@link SCM} is OK to let Hudson proceed with deleting the workspace.
False to veto the workspace deletion.
@since 1.568 | [
"Called",
"before",
"a",
"workspace",
"is",
"deleted",
"on",
"the",
"given",
"node",
"to",
"provide",
"SCM",
"an",
"opportunity",
"to",
"perform",
"clean",
"up",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/scm/SCM.java#L234-L240 |
threerings/nenya | core/src/main/java/com/threerings/resource/ResourceManager.java | ResourceManager.resolveResourceSet | protected void resolveResourceSet (
String setName, String definition, String setType, List<ResourceBundle> dlist)
{
List<ResourceBundle> set = Lists.newArrayList();
StringTokenizer tok = new StringTokenizer(definition, ":");
while (tok.hasMoreTokens()) {
set.add(createResourceBundle(setType, tok.nextToken().trim(), dlist));
}
// convert our array list into an array and stick it in the table
ResourceBundle[] setvec = set.toArray(new ResourceBundle[set.size()]);
_sets.put(setName, setvec);
// if this is our default resource bundle, keep a reference to it
if (DEFAULT_RESOURCE_SET.equals(setName)) {
_default = setvec;
}
} | java | protected void resolveResourceSet (
String setName, String definition, String setType, List<ResourceBundle> dlist)
{
List<ResourceBundle> set = Lists.newArrayList();
StringTokenizer tok = new StringTokenizer(definition, ":");
while (tok.hasMoreTokens()) {
set.add(createResourceBundle(setType, tok.nextToken().trim(), dlist));
}
// convert our array list into an array and stick it in the table
ResourceBundle[] setvec = set.toArray(new ResourceBundle[set.size()]);
_sets.put(setName, setvec);
// if this is our default resource bundle, keep a reference to it
if (DEFAULT_RESOURCE_SET.equals(setName)) {
_default = setvec;
}
} | [
"protected",
"void",
"resolveResourceSet",
"(",
"String",
"setName",
",",
"String",
"definition",
",",
"String",
"setType",
",",
"List",
"<",
"ResourceBundle",
">",
"dlist",
")",
"{",
"List",
"<",
"ResourceBundle",
">",
"set",
"=",
"Lists",
".",
"newArrayList"... | Loads up a resource set based on the supplied definition information. | [
"Loads",
"up",
"a",
"resource",
"set",
"based",
"on",
"the",
"supplied",
"definition",
"information",
"."
] | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/resource/ResourceManager.java#L799-L816 |
JadiraOrg/jadira | bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java | BasicBinder.findUnmarshaller | public <S, T> FromUnmarshaller<S, T> findUnmarshaller(Class<S> source, Class<T> target) {
return findUnmarshaller(new ConverterKey<S,T>(source, target, DefaultBinding.class));
} | java | public <S, T> FromUnmarshaller<S, T> findUnmarshaller(Class<S> source, Class<T> target) {
return findUnmarshaller(new ConverterKey<S,T>(source, target, DefaultBinding.class));
} | [
"public",
"<",
"S",
",",
"T",
">",
"FromUnmarshaller",
"<",
"S",
",",
"T",
">",
"findUnmarshaller",
"(",
"Class",
"<",
"S",
">",
"source",
",",
"Class",
"<",
"T",
">",
"target",
")",
"{",
"return",
"findUnmarshaller",
"(",
"new",
"ConverterKey",
"<",
... | Resolve an UnMarshaller with the given source and target class.
The unmarshaller is used as follows: Instances of the source can be marshalled into the target class.
@param source The source (input) class
@param target The target (output) class | [
"Resolve",
"an",
"UnMarshaller",
"with",
"the",
"given",
"source",
"and",
"target",
"class",
".",
"The",
"unmarshaller",
"is",
"used",
"as",
"follows",
":",
"Instances",
"of",
"the",
"source",
"can",
"be",
"marshalled",
"into",
"the",
"target",
"class",
"."
... | train | https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java#L877-L879 |
UrielCh/ovh-java-sdk | ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java | ApiOvhPrice.hosting_privateDatabase_privateDatabaseName_GET | public OvhPrice hosting_privateDatabase_privateDatabaseName_GET(net.minidev.ovh.api.price.hosting.OvhPrivateDatabaseEnum privateDatabaseName) throws IOException {
String qPath = "/price/hosting/privateDatabase/{privateDatabaseName}";
StringBuilder sb = path(qPath, privateDatabaseName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | java | public OvhPrice hosting_privateDatabase_privateDatabaseName_GET(net.minidev.ovh.api.price.hosting.OvhPrivateDatabaseEnum privateDatabaseName) throws IOException {
String qPath = "/price/hosting/privateDatabase/{privateDatabaseName}";
StringBuilder sb = path(qPath, privateDatabaseName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhPrice.class);
} | [
"public",
"OvhPrice",
"hosting_privateDatabase_privateDatabaseName_GET",
"(",
"net",
".",
"minidev",
".",
"ovh",
".",
"api",
".",
"price",
".",
"hosting",
".",
"OvhPrivateDatabaseEnum",
"privateDatabaseName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
... | Get the price for a private database
REST: GET /price/hosting/privateDatabase/{privateDatabaseName}
@param privateDatabaseName [required] PrivateDatabase | [
"Get",
"the",
"price",
"for",
"a",
"private",
"database"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-price/src/main/java/net/minidev/ovh/api/ApiOvhPrice.java#L271-L276 |
wuman/JReadability | src/main/java/com/wuman/jreadability/Readability.java | Readability.incrementContentScore | private static Element incrementContentScore(Element node, int increment) {
int contentScore = getContentScore(node);
contentScore += increment;
node.attr(CONTENT_SCORE, Integer.toString(contentScore));
return node;
} | java | private static Element incrementContentScore(Element node, int increment) {
int contentScore = getContentScore(node);
contentScore += increment;
node.attr(CONTENT_SCORE, Integer.toString(contentScore));
return node;
} | [
"private",
"static",
"Element",
"incrementContentScore",
"(",
"Element",
"node",
",",
"int",
"increment",
")",
"{",
"int",
"contentScore",
"=",
"getContentScore",
"(",
"node",
")",
";",
"contentScore",
"+=",
"increment",
";",
"node",
".",
"attr",
"(",
"CONTENT... | Increase or decrease the content score for an Element by an
increment/decrement.
@param node
@param increment
@return | [
"Increase",
"or",
"decrease",
"the",
"content",
"score",
"for",
"an",
"Element",
"by",
"an",
"increment",
"/",
"decrement",
"."
] | train | https://github.com/wuman/JReadability/blob/16c18c42402bd13c6e024c2fd3a86dd28ba53e74/src/main/java/com/wuman/jreadability/Readability.java#L850-L855 |
jbundle/jbundle | main/db/src/main/java/org/jbundle/main/user/db/UserFilter.java | UserFilter.setupDefaultView | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties)
{
UserInfo user = (UserInfo)this.makeReferenceRecord();
user.addListener(new StringSubFileFilter(Integer.toString(UserGroup.RES_USER), user.getField(UserInfo.USER_GROUP_ID), null, null, null, null));
Converter convName = new FirstMLastConverter(user, null, UserInfo.FIRST_NAME, null, UserInfo.LAST_NAME);
ScreenComponent screenField = this.setupTableLookup(itsLocation, targetScreen, converter, iDisplayFieldDesc, user, UserInfo.USER_NAME_KEY, convName, true, false);
properties = new HashMap<String,Object>();
properties.put(ScreenModel.FIELD, this);
properties.put(ScreenModel.TOOLTIP, ThinMenuConstants.HOME);
String userID = ((BaseApplication)this.getRecord().getRecordOwner().getTask().getApplication()).getUserID();
properties.put(ScreenModel.VALUE, userID);
properties.put(ScreenModel.IMAGE, ThinMenuConstants.HOME);
createScreenComponent(ScreenModel.CANNED_BOX, targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST, ScreenConstants.DONT_SET_ANCHOR), targetScreen, converter, ScreenConstants.DONT_DISPLAY_FIELD_DESC, properties);
return screenField;
} | java | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties)
{
UserInfo user = (UserInfo)this.makeReferenceRecord();
user.addListener(new StringSubFileFilter(Integer.toString(UserGroup.RES_USER), user.getField(UserInfo.USER_GROUP_ID), null, null, null, null));
Converter convName = new FirstMLastConverter(user, null, UserInfo.FIRST_NAME, null, UserInfo.LAST_NAME);
ScreenComponent screenField = this.setupTableLookup(itsLocation, targetScreen, converter, iDisplayFieldDesc, user, UserInfo.USER_NAME_KEY, convName, true, false);
properties = new HashMap<String,Object>();
properties.put(ScreenModel.FIELD, this);
properties.put(ScreenModel.TOOLTIP, ThinMenuConstants.HOME);
String userID = ((BaseApplication)this.getRecord().getRecordOwner().getTask().getApplication()).getUserID();
properties.put(ScreenModel.VALUE, userID);
properties.put(ScreenModel.IMAGE, ThinMenuConstants.HOME);
createScreenComponent(ScreenModel.CANNED_BOX, targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST, ScreenConstants.DONT_SET_ANCHOR), targetScreen, converter, ScreenConstants.DONT_DISPLAY_FIELD_DESC, properties);
return screenField;
} | [
"public",
"ScreenComponent",
"setupDefaultView",
"(",
"ScreenLoc",
"itsLocation",
",",
"ComponentParent",
"targetScreen",
",",
"Convert",
"converter",
",",
"int",
"iDisplayFieldDesc",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"UserInfo",... | Set up the default screen control for this field.
@param itsLocation Location of this component on screen (ie., GridBagConstraint).
@param targetScreen Where to place this component (ie., Parent screen or GridBagLayout).
@param converter The converter to set the screenfield to.
@param iDisplayFieldDesc Display the label? (optional).
@param properties Extra properties
@return Return the component or ScreenField that is created for this field. | [
"Set",
"up",
"the",
"default",
"screen",
"control",
"for",
"this",
"field",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/main/db/src/main/java/org/jbundle/main/user/db/UserFilter.java#L74-L89 |
aws/aws-sdk-java | aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/Route.java | Route.withRequestModels | public Route withRequestModels(java.util.Map<String, String> requestModels) {
setRequestModels(requestModels);
return this;
} | java | public Route withRequestModels(java.util.Map<String, String> requestModels) {
setRequestModels(requestModels);
return this;
} | [
"public",
"Route",
"withRequestModels",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"requestModels",
")",
"{",
"setRequestModels",
"(",
"requestModels",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The request models for the route.
</p>
@param requestModels
The request models for the route.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"request",
"models",
"for",
"the",
"route",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/Route.java#L493-L496 |
docusign/docusign-java-client | src/main/java/com/docusign/esign/api/UsersApi.java | UsersApi.getInformation | public UserInformation getInformation(String accountId, String userId, UsersApi.GetInformationOptions options) throws ApiException {
Object localVarPostBody = "{}";
// verify the required parameter 'accountId' is set
if (accountId == null) {
throw new ApiException(400, "Missing the required parameter 'accountId' when calling getInformation");
}
// verify the required parameter 'userId' is set
if (userId == null) {
throw new ApiException(400, "Missing the required parameter 'userId' when calling getInformation");
}
// create path and map variables
String localVarPath = "/v2/accounts/{accountId}/users/{userId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString()))
.replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString()));
// query params
java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();
if (options != null) {
localVarQueryParams.addAll(apiClient.parameterToPairs("", "additional_info", options.additionalInfo));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "email", options.email));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ };
GenericType<UserInformation> localVarReturnType = new GenericType<UserInformation>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
} | java | public UserInformation getInformation(String accountId, String userId, UsersApi.GetInformationOptions options) throws ApiException {
Object localVarPostBody = "{}";
// verify the required parameter 'accountId' is set
if (accountId == null) {
throw new ApiException(400, "Missing the required parameter 'accountId' when calling getInformation");
}
// verify the required parameter 'userId' is set
if (userId == null) {
throw new ApiException(400, "Missing the required parameter 'userId' when calling getInformation");
}
// create path and map variables
String localVarPath = "/v2/accounts/{accountId}/users/{userId}".replaceAll("\\{format\\}","json")
.replaceAll("\\{" + "accountId" + "\\}", apiClient.escapeString(accountId.toString()))
.replaceAll("\\{" + "userId" + "\\}", apiClient.escapeString(userId.toString()));
// query params
java.util.List<Pair> localVarQueryParams = new java.util.ArrayList<Pair>();
java.util.Map<String, String> localVarHeaderParams = new java.util.HashMap<String, String>();
java.util.Map<String, Object> localVarFormParams = new java.util.HashMap<String, Object>();
if (options != null) {
localVarQueryParams.addAll(apiClient.parameterToPairs("", "additional_info", options.additionalInfo));
localVarQueryParams.addAll(apiClient.parameterToPairs("", "email", options.email));
}
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
final String[] localVarContentTypes = {
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
String[] localVarAuthNames = new String[] { "docusignAccessCode" }; //{ };
GenericType<UserInformation> localVarReturnType = new GenericType<UserInformation>() {};
return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType);
} | [
"public",
"UserInformation",
"getInformation",
"(",
"String",
"accountId",
",",
"String",
"userId",
",",
"UsersApi",
".",
"GetInformationOptions",
"options",
")",
"throws",
"ApiException",
"{",
"Object",
"localVarPostBody",
"=",
"\"{}\"",
";",
"// verify the required pa... | Gets the user information for a specified user.
Retrieves the user information for the specified user. To return additional user information that details the last login date, login status, and the user's password expiration date, set the optional `additional_info` query string parameter to **true**.
@param accountId The external account number (int) or account ID Guid. (required)
@param userId The user ID of the user being accessed. Generally this is the user ID of the authenticated user, but if the authenticated user is an Admin on the account, this may be another user the Admin user is accessing. (required)
@param options for modifying the method behavior.
@return UserInformation
@throws ApiException if fails to make API call | [
"Gets",
"the",
"user",
"information",
"for",
"a",
"specified",
"user",
".",
"Retrieves",
"the",
"user",
"information",
"for",
"the",
"specified",
"user",
".",
"To",
"return",
"additional",
"user",
"information",
"that",
"details",
"the",
"last",
"login",
"date... | train | https://github.com/docusign/docusign-java-client/blob/17ae82ace0f023e98edf813be832950568212e34/src/main/java/com/docusign/esign/api/UsersApi.java#L632-L675 |
maven-nar/nar-maven-plugin | src/main/java/com/github/maven_nar/cpptasks/compiler/CommandLineLinker.java | CommandLineLinker.runCommand | protected int runCommand(final CCTask task, final File workingDir, final String[] cmdline) throws BuildException {
return CUtil.runCommand(task, workingDir, cmdline, this.newEnvironment, this.env);
} | java | protected int runCommand(final CCTask task, final File workingDir, final String[] cmdline) throws BuildException {
return CUtil.runCommand(task, workingDir, cmdline, this.newEnvironment, this.env);
} | [
"protected",
"int",
"runCommand",
"(",
"final",
"CCTask",
"task",
",",
"final",
"File",
"workingDir",
",",
"final",
"String",
"[",
"]",
"cmdline",
")",
"throws",
"BuildException",
"{",
"return",
"CUtil",
".",
"runCommand",
"(",
"task",
",",
"workingDir",
","... | This method is exposed so test classes can overload
and test the arguments without actually spawning the
compiler | [
"This",
"method",
"is",
"exposed",
"so",
"test",
"classes",
"can",
"overload",
"and",
"test",
"the",
"arguments",
"without",
"actually",
"spawning",
"the",
"compiler"
] | train | https://github.com/maven-nar/nar-maven-plugin/blob/3c622e2024296b4203431bbae3bde290a01dac00/src/main/java/com/github/maven_nar/cpptasks/compiler/CommandLineLinker.java#L492-L494 |
ops4j/org.ops4j.base | ops4j-base-io/src/main/java/org/ops4j/io/ListerUtils.java | ListerUtils.parseFilter | public static Pattern parseFilter( final String spec )
{
StringBuffer sb = new StringBuffer();
for( int j = 0; j < spec.length(); j++ )
{
char c = spec.charAt( j );
switch( c )
{
case '.':
sb.append( "\\." );
break;
case '*':
// test for ** (all directories)
if( j < spec.length() - 1 && spec.charAt( j + 1 ) == '*' )
{
sb.append( ".*" );
j++;
}
else
{
sb.append( "[^/]*" );
}
break;
default:
sb.append( c );
break;
}
}
String s = sb.toString();
try
{
return Pattern.compile( s );
}
catch( Exception e )
{
throw new IllegalArgumentException( "Invalid character used in the filter name", e );
}
} | java | public static Pattern parseFilter( final String spec )
{
StringBuffer sb = new StringBuffer();
for( int j = 0; j < spec.length(); j++ )
{
char c = spec.charAt( j );
switch( c )
{
case '.':
sb.append( "\\." );
break;
case '*':
// test for ** (all directories)
if( j < spec.length() - 1 && spec.charAt( j + 1 ) == '*' )
{
sb.append( ".*" );
j++;
}
else
{
sb.append( "[^/]*" );
}
break;
default:
sb.append( c );
break;
}
}
String s = sb.toString();
try
{
return Pattern.compile( s );
}
catch( Exception e )
{
throw new IllegalArgumentException( "Invalid character used in the filter name", e );
}
} | [
"public",
"static",
"Pattern",
"parseFilter",
"(",
"final",
"String",
"spec",
")",
"{",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"spec",
".",
"length",
"(",
")",
";",
"j",
"++... | Parses a usual filter into a regex pattern.
@param spec the filter to be parsed
@return a regexp pattern corresponding to the filter
@throws IllegalArgumentException - If the filter could not be compiled to a pattern | [
"Parses",
"a",
"usual",
"filter",
"into",
"a",
"regex",
"pattern",
"."
] | train | https://github.com/ops4j/org.ops4j.base/blob/b0e742c0d9511f6b19ca64da2ebaf30b7a47256a/ops4j-base-io/src/main/java/org/ops4j/io/ListerUtils.java#L45-L83 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/randomprojection/RPUtils.java | RPUtils.sortCandidates | public static List<Pair<Double,Integer>> sortCandidates(INDArray x,INDArray X,
List<Integer> candidates,
String similarityFunction) {
int prevIdx = -1;
List<Pair<Double,Integer>> ret = new ArrayList<>();
for(int i = 0; i < candidates.size(); i++) {
if(candidates.get(i) != prevIdx) {
ret.add(Pair.of(computeDistance(similarityFunction,X.slice(candidates.get(i)),x),candidates.get(i)));
}
prevIdx = i;
}
Collections.sort(ret, new Comparator<Pair<Double, Integer>>() {
@Override
public int compare(Pair<Double, Integer> doubleIntegerPair, Pair<Double, Integer> t1) {
return Doubles.compare(doubleIntegerPair.getFirst(),t1.getFirst());
}
});
return ret;
} | java | public static List<Pair<Double,Integer>> sortCandidates(INDArray x,INDArray X,
List<Integer> candidates,
String similarityFunction) {
int prevIdx = -1;
List<Pair<Double,Integer>> ret = new ArrayList<>();
for(int i = 0; i < candidates.size(); i++) {
if(candidates.get(i) != prevIdx) {
ret.add(Pair.of(computeDistance(similarityFunction,X.slice(candidates.get(i)),x),candidates.get(i)));
}
prevIdx = i;
}
Collections.sort(ret, new Comparator<Pair<Double, Integer>>() {
@Override
public int compare(Pair<Double, Integer> doubleIntegerPair, Pair<Double, Integer> t1) {
return Doubles.compare(doubleIntegerPair.getFirst(),t1.getFirst());
}
});
return ret;
} | [
"public",
"static",
"List",
"<",
"Pair",
"<",
"Double",
",",
"Integer",
">",
">",
"sortCandidates",
"(",
"INDArray",
"x",
",",
"INDArray",
"X",
",",
"List",
"<",
"Integer",
">",
"candidates",
",",
"String",
"similarityFunction",
")",
"{",
"int",
"prevIdx",... | Get the sorted distances given the
query vector, input data, given the list of possible search candidates
@param x the query vector
@param X the input data to use
@param candidates the possible search candidates
@param similarityFunction the similarity function to use
@return the sorted distances | [
"Get",
"the",
"sorted",
"distances",
"given",
"the",
"query",
"vector",
"input",
"data",
"given",
"the",
"list",
"of",
"possible",
"search",
"candidates"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nearestneighbors-parent/nearestneighbor-core/src/main/java/org/deeplearning4j/clustering/randomprojection/RPUtils.java#L197-L219 |
headius/invokebinder | src/main/java/com/headius/invokebinder/SmartBinder.java | SmartBinder.dropFirst | public SmartBinder dropFirst(int count) {
return new SmartBinder(this, signature().dropFirst(count), binder.dropFirst(count));
} | java | public SmartBinder dropFirst(int count) {
return new SmartBinder(this, signature().dropFirst(count), binder.dropFirst(count));
} | [
"public",
"SmartBinder",
"dropFirst",
"(",
"int",
"count",
")",
"{",
"return",
"new",
"SmartBinder",
"(",
"this",
",",
"signature",
"(",
")",
".",
"dropFirst",
"(",
"count",
")",
",",
"binder",
".",
"dropFirst",
"(",
"count",
")",
")",
";",
"}"
] | Drop the first N arguments.
@param count the count of arguments to drop
@return a new SmartBinder with the drop applied | [
"Drop",
"the",
"first",
"N",
"arguments",
"."
] | train | https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/SmartBinder.java#L828-L830 |
sarl/sarl | sre/io.janusproject/io.janusproject.eclipse/src/io/janusproject/eclipse/JanusEclipsePlugin.java | JanusEclipsePlugin.createStatus | @SuppressWarnings("static-method")
public IStatus createStatus(int severity, String message) {
return new Status(severity, PLUGIN_ID, message);
} | java | @SuppressWarnings("static-method")
public IStatus createStatus(int severity, String message) {
return new Status(severity, PLUGIN_ID, message);
} | [
"@",
"SuppressWarnings",
"(",
"\"static-method\"",
")",
"public",
"IStatus",
"createStatus",
"(",
"int",
"severity",
",",
"String",
"message",
")",
"{",
"return",
"new",
"Status",
"(",
"severity",
",",
"PLUGIN_ID",
",",
"message",
")",
";",
"}"
] | Create a status.
@param severity the severity level, see {@link IStatus}.
@param message the message associated to the status.
@return the status. | [
"Create",
"a",
"status",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/sre/io.janusproject/io.janusproject.eclipse/src/io/janusproject/eclipse/JanusEclipsePlugin.java#L139-L142 |
alkacon/opencms-core | src-modules/org/opencms/workplace/commons/CmsHistoryList.java | CmsHistoryList.fillDetailProject | private void fillDetailProject(CmsListItem item, String detailId) {
StringBuffer html = new StringBuffer();
// search /read for the corresponding history project: it's tag id transmitted from getListItems()
// in a hidden column
Object tagIdObj = item.get(LIST_COLUMN_PUBLISH_TAG);
if (tagIdObj != null) {
// it is null if the offline version with changes is shown here: now history project available then
int tagId = ((Integer)tagIdObj).intValue();
try {
CmsHistoryProject project = getCms().readHistoryProject(tagId);
// output of project info
html.append(project.getName()).append("<br/>").append(project.getDescription());
} catch (CmsException cmse) {
html.append(cmse.getMessageContainer().key(getLocale()));
}
}
item.set(detailId, html.toString());
} | java | private void fillDetailProject(CmsListItem item, String detailId) {
StringBuffer html = new StringBuffer();
// search /read for the corresponding history project: it's tag id transmitted from getListItems()
// in a hidden column
Object tagIdObj = item.get(LIST_COLUMN_PUBLISH_TAG);
if (tagIdObj != null) {
// it is null if the offline version with changes is shown here: now history project available then
int tagId = ((Integer)tagIdObj).intValue();
try {
CmsHistoryProject project = getCms().readHistoryProject(tagId);
// output of project info
html.append(project.getName()).append("<br/>").append(project.getDescription());
} catch (CmsException cmse) {
html.append(cmse.getMessageContainer().key(getLocale()));
}
}
item.set(detailId, html.toString());
} | [
"private",
"void",
"fillDetailProject",
"(",
"CmsListItem",
"item",
",",
"String",
"detailId",
")",
"{",
"StringBuffer",
"html",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"// search /read for the corresponding history project: it's tag id transmitted from getListItems()",
"/... | Fills details of the project into the given item. <p>
@param item the list item to fill
@param detailId the id for the detail to fill | [
"Fills",
"details",
"of",
"the",
"project",
"into",
"the",
"given",
"item",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsHistoryList.java#L871-L890 |
Wadpam/guja | guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java | GeneratedDUserDaoImpl.queryByPreferredLanguage | public Iterable<DUser> queryByPreferredLanguage(java.lang.String preferredLanguage) {
return queryByField(null, DUserMapper.Field.PREFERREDLANGUAGE.getFieldName(), preferredLanguage);
} | java | public Iterable<DUser> queryByPreferredLanguage(java.lang.String preferredLanguage) {
return queryByField(null, DUserMapper.Field.PREFERREDLANGUAGE.getFieldName(), preferredLanguage);
} | [
"public",
"Iterable",
"<",
"DUser",
">",
"queryByPreferredLanguage",
"(",
"java",
".",
"lang",
".",
"String",
"preferredLanguage",
")",
"{",
"return",
"queryByField",
"(",
"null",
",",
"DUserMapper",
".",
"Field",
".",
"PREFERREDLANGUAGE",
".",
"getFieldName",
"... | query-by method for field preferredLanguage
@param preferredLanguage the specified attribute
@return an Iterable of DUsers for the specified preferredLanguage | [
"query",
"-",
"by",
"method",
"for",
"field",
"preferredLanguage"
] | train | https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java#L205-L207 |
bwkimmel/jdcp | jdcp-server/src/main/java/ca/eandb/jdcp/server/TemporaryJobServer.java | TemporaryJobServer.removeScheduledJob | private void removeScheduledJob(UUID jobId, boolean complete) {
ScheduledJob sched = jobs.remove(jobId);
if (sched != null) {
if (complete) {
sched.monitor.notifyComplete();
if (logger.isInfoEnabled()) {
logger.info("Job complete (" + jobId.toString() + ")");
}
} else {
sched.monitor.notifyCancelled();
if (logger.isInfoEnabled()) {
logger.info("Job cancelled (" + jobId.toString() + ")");
}
}
jobs.remove(jobId);
scheduler.removeJob(jobId);
}
if (jobs.isEmpty()) {
synchronized (this.complete) {
this.complete.notifyAll();
}
}
} | java | private void removeScheduledJob(UUID jobId, boolean complete) {
ScheduledJob sched = jobs.remove(jobId);
if (sched != null) {
if (complete) {
sched.monitor.notifyComplete();
if (logger.isInfoEnabled()) {
logger.info("Job complete (" + jobId.toString() + ")");
}
} else {
sched.monitor.notifyCancelled();
if (logger.isInfoEnabled()) {
logger.info("Job cancelled (" + jobId.toString() + ")");
}
}
jobs.remove(jobId);
scheduler.removeJob(jobId);
}
if (jobs.isEmpty()) {
synchronized (this.complete) {
this.complete.notifyAll();
}
}
} | [
"private",
"void",
"removeScheduledJob",
"(",
"UUID",
"jobId",
",",
"boolean",
"complete",
")",
"{",
"ScheduledJob",
"sched",
"=",
"jobs",
".",
"remove",
"(",
"jobId",
")",
";",
"if",
"(",
"sched",
"!=",
"null",
")",
"{",
"if",
"(",
"complete",
")",
"{... | Removes a job.
@param jobId The <code>UUID</code> identifying the job to be removed.
@param complete A value indicating whether the job has been completed. | [
"Removes",
"a",
"job",
"."
] | train | https://github.com/bwkimmel/jdcp/blob/630c5150c245054e2556ff370f4bad2ec793dfb7/jdcp-server/src/main/java/ca/eandb/jdcp/server/TemporaryJobServer.java#L340-L362 |
facebook/fresco | drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java | GenericDraweeHierarchy.setProgressBarImage | public void setProgressBarImage(int resourceId, ScalingUtils.ScaleType scaleType) {
setProgressBarImage(mResources.getDrawable(resourceId), scaleType);
} | java | public void setProgressBarImage(int resourceId, ScalingUtils.ScaleType scaleType) {
setProgressBarImage(mResources.getDrawable(resourceId), scaleType);
} | [
"public",
"void",
"setProgressBarImage",
"(",
"int",
"resourceId",
",",
"ScalingUtils",
".",
"ScaleType",
"scaleType",
")",
"{",
"setProgressBarImage",
"(",
"mResources",
".",
"getDrawable",
"(",
"resourceId",
")",
",",
"scaleType",
")",
";",
"}"
] | Sets a new progress bar drawable with scale type.
@param resourceId an identifier of an Android drawable or color resource.
@param ScalingUtils.ScaleType a new scale type. | [
"Sets",
"a",
"new",
"progress",
"bar",
"drawable",
"with",
"scale",
"type",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/drawee/src/main/java/com/facebook/drawee/generic/GenericDraweeHierarchy.java#L543-L545 |
ops4j/org.ops4j.pax.exam2 | containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/options/KarafDistributionOption.java | KarafDistributionOption.editConfigurationFileExtend | public static Option[] editConfigurationFileExtend(final String configurationFilePath,
File source, String... keysToUseFromSource) {
return createOptionListFromFile(source, new FileOptionFactory() {
@Override
public Option createOption(String key, Object value) {
return new KarafDistributionConfigurationFileExtendOption(configurationFilePath,
key, value);
}
}, keysToUseFromSource);
} | java | public static Option[] editConfigurationFileExtend(final String configurationFilePath,
File source, String... keysToUseFromSource) {
return createOptionListFromFile(source, new FileOptionFactory() {
@Override
public Option createOption(String key, Object value) {
return new KarafDistributionConfigurationFileExtendOption(configurationFilePath,
key, value);
}
}, keysToUseFromSource);
} | [
"public",
"static",
"Option",
"[",
"]",
"editConfigurationFileExtend",
"(",
"final",
"String",
"configurationFilePath",
",",
"File",
"source",
",",
"String",
"...",
"keysToUseFromSource",
")",
"{",
"return",
"createOptionListFromFile",
"(",
"source",
",",
"new",
"Fi... | This option allows to configure each configuration file based on the karaf.home location. The
value is "extend" which means it is either replaced or added. For simpler configuration you
can add a file source. If you want to put all values from this file do not configure any
keysToUseFromSource; otherwise define them to use only those specific values.
@param configurationFilePath
configuration file path
@param source
property key
@param keysToUseFromSource
property keys to be used
@return option array | [
"This",
"option",
"allows",
"to",
"configure",
"each",
"configuration",
"file",
"based",
"on",
"the",
"karaf",
".",
"home",
"location",
".",
"The",
"value",
"is",
"extend",
"which",
"means",
"it",
"is",
"either",
"replaced",
"or",
"added",
".",
"For",
"sim... | train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/containers/pax-exam-container-karaf/src/main/java/org/ops4j/pax/exam/karaf/options/KarafDistributionOption.java#L295-L305 |
box/box-java-sdk | src/main/java/com/box/sdk/BoxRetentionPolicy.java | BoxRetentionPolicy.getAll | public static Iterable<BoxRetentionPolicy.Info> getAll(
String name, String type, String userID, int limit, final BoxAPIConnection api, String ... fields) {
QueryStringBuilder queryString = new QueryStringBuilder();
if (name != null) {
queryString.appendParam("policy_name", name);
}
if (type != null) {
queryString.appendParam("policy_type", type);
}
if (userID != null) {
queryString.appendParam("created_by_user_id", userID);
}
if (fields.length > 0) {
queryString.appendParam("fields", fields);
}
URL url = RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString());
return new BoxResourceIterable<BoxRetentionPolicy.Info>(api, url, limit) {
@Override
protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) {
BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get("id").asString());
return policy.new Info(jsonObject);
}
};
} | java | public static Iterable<BoxRetentionPolicy.Info> getAll(
String name, String type, String userID, int limit, final BoxAPIConnection api, String ... fields) {
QueryStringBuilder queryString = new QueryStringBuilder();
if (name != null) {
queryString.appendParam("policy_name", name);
}
if (type != null) {
queryString.appendParam("policy_type", type);
}
if (userID != null) {
queryString.appendParam("created_by_user_id", userID);
}
if (fields.length > 0) {
queryString.appendParam("fields", fields);
}
URL url = RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString());
return new BoxResourceIterable<BoxRetentionPolicy.Info>(api, url, limit) {
@Override
protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) {
BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get("id").asString());
return policy.new Info(jsonObject);
}
};
} | [
"public",
"static",
"Iterable",
"<",
"BoxRetentionPolicy",
".",
"Info",
">",
"getAll",
"(",
"String",
"name",
",",
"String",
"type",
",",
"String",
"userID",
",",
"int",
"limit",
",",
"final",
"BoxAPIConnection",
"api",
",",
"String",
"...",
"fields",
")",
... | Returns all the retention policies with specified filters.
@param name a name to filter the retention policies by. A trailing partial match search is performed.
Set to null if no name filtering is required.
@param type a policy type to filter the retention policies by. Set to null if no type filtering is required.
@param userID a user id to filter the retention policies by. Set to null if no type filtering is required.
@param limit the limit of items per single response. The default value is 100.
@param api the API connection to be used by the resource.
@param fields the fields to retrieve.
@return an iterable with all the retention policies met search conditions. | [
"Returns",
"all",
"the",
"retention",
"policies",
"with",
"specified",
"filters",
"."
] | train | https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxRetentionPolicy.java#L361-L386 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/ExtendedPropertyUrl.java | ExtendedPropertyUrl.getExtendedPropertiesUrl | public static MozuUrl getExtendedPropertiesUrl(Boolean draft, String orderId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/extendedproperties?draft={draft}");
formatter.formatUrl("draft", draft);
formatter.formatUrl("orderId", orderId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl getExtendedPropertiesUrl(Boolean draft, String orderId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/extendedproperties?draft={draft}");
formatter.formatUrl("draft", draft);
formatter.formatUrl("orderId", orderId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"getExtendedPropertiesUrl",
"(",
"Boolean",
"draft",
",",
"String",
"orderId",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/orders/{orderId}/extendedproperties?draft={draft}\"",
")",
";",
"formatter"... | Get Resource Url for GetExtendedProperties
@param draft If true, retrieve the draft version of the order, which might include uncommitted changes to the order or its components.
@param orderId Unique identifier of the order.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"GetExtendedProperties"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/ExtendedPropertyUrl.java#L22-L28 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark-nlp/src/main/java/org/deeplearning4j/spark/models/embeddings/word2vec/Word2VecPerformerVoid.java | Word2VecPerformerVoid.trainSentence | public void trainSentence(final List<VocabWord> sentence, double alpha) {
if (sentence != null && !sentence.isEmpty()) {
for (int i = 0; i < sentence.size(); i++) {
if (!sentence.get(i).getWord().endsWith("STOP")) {
nextRandom.set(nextRandom.get() * 25214903917L + 11);
skipGram(i, sentence, (int) nextRandom.get() % window, alpha);
}
}
}
} | java | public void trainSentence(final List<VocabWord> sentence, double alpha) {
if (sentence != null && !sentence.isEmpty()) {
for (int i = 0; i < sentence.size(); i++) {
if (!sentence.get(i).getWord().endsWith("STOP")) {
nextRandom.set(nextRandom.get() * 25214903917L + 11);
skipGram(i, sentence, (int) nextRandom.get() % window, alpha);
}
}
}
} | [
"public",
"void",
"trainSentence",
"(",
"final",
"List",
"<",
"VocabWord",
">",
"sentence",
",",
"double",
"alpha",
")",
"{",
"if",
"(",
"sentence",
"!=",
"null",
"&&",
"!",
"sentence",
".",
"isEmpty",
"(",
")",
")",
"{",
"for",
"(",
"int",
"i",
"=",... | Train on a list of vocab words
@param sentence the list of vocab words to train on | [
"Train",
"on",
"a",
"list",
"of",
"vocab",
"words"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark-nlp/src/main/java/org/deeplearning4j/spark/models/embeddings/word2vec/Word2VecPerformerVoid.java#L247-L257 |
Mozu/mozu-java | mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/quotes/OrderItemUrl.java | OrderItemUrl.deleteQuoteItemUrl | public static MozuUrl deleteQuoteItemUrl(String quoteId, String quoteItemId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/{quoteId}/items/{quoteItemId}");
formatter.formatUrl("quoteId", quoteId);
formatter.formatUrl("quoteItemId", quoteItemId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl deleteQuoteItemUrl(String quoteId, String quoteItemId)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/quotes/{quoteId}/items/{quoteItemId}");
formatter.formatUrl("quoteId", quoteId);
formatter.formatUrl("quoteItemId", quoteItemId);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"deleteQuoteItemUrl",
"(",
"String",
"quoteId",
",",
"String",
"quoteItemId",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/quotes/{quoteId}/items/{quoteItemId}\"",
")",
";",
"formatter",
".",
"fo... | Get Resource Url for DeleteQuoteItem
@param quoteId
@param quoteItemId
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"DeleteQuoteItem"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-javaasync-core/src/main/java/com/mozu/api/urls/commerce/quotes/OrderItemUrl.java#L114-L120 |
b3log/latke | latke-core/src/main/java/org/json/JSONObject.java | JSONObject.getEnum | public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) throws JSONException {
E val = optEnum(clazz, key);
if(val==null) {
// JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException
throw new JSONException("JSONObject[" + quote(key)
+ "] is not an enum of type " + quote(clazz.getSimpleName())
+ ".");
}
return val;
} | java | public <E extends Enum<E>> E getEnum(Class<E> clazz, String key) throws JSONException {
E val = optEnum(clazz, key);
if(val==null) {
// JSONException should really take a throwable argument.
// If it did, I would re-implement this with the Enum.valueOf
// method and place any thrown exception in the JSONException
throw new JSONException("JSONObject[" + quote(key)
+ "] is not an enum of type " + quote(clazz.getSimpleName())
+ ".");
}
return val;
} | [
"public",
"<",
"E",
"extends",
"Enum",
"<",
"E",
">",
">",
"E",
"getEnum",
"(",
"Class",
"<",
"E",
">",
"clazz",
",",
"String",
"key",
")",
"throws",
"JSONException",
"{",
"E",
"val",
"=",
"optEnum",
"(",
"clazz",
",",
"key",
")",
";",
"if",
"(",... | Get the enum value associated with a key.
@param <E>
Enum Type
@param clazz
The type of enum to retrieve.
@param key
A key string.
@return The enum value associated with the key
@throws JSONException
if the key is not found or if the value cannot be converted
to an enum. | [
"Get",
"the",
"enum",
"value",
"associated",
"with",
"a",
"key",
"."
] | train | https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L585-L596 |
samskivert/samskivert | src/main/java/com/samskivert/swing/GroupLayout.java | GroupLayout.makeHBox | public static JPanel makeHBox (Policy policy, Justification justification)
{
return new JPanel(new HGroupLayout(policy, justification));
} | java | public static JPanel makeHBox (Policy policy, Justification justification)
{
return new JPanel(new HGroupLayout(policy, justification));
} | [
"public",
"static",
"JPanel",
"makeHBox",
"(",
"Policy",
"policy",
",",
"Justification",
"justification",
")",
"{",
"return",
"new",
"JPanel",
"(",
"new",
"HGroupLayout",
"(",
"policy",
",",
"justification",
")",
")",
";",
"}"
] | Creates a {@link JPanel} that is configured with an {@link
HGroupLayout} with the specified on-axis policy and justification
(default configuration otherwise). | [
"Creates",
"a",
"{"
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/swing/GroupLayout.java#L364-L367 |
h2oai/h2o-2 | src/main/java/hex/deeplearning/DeepLearning.java | DeepLearning.crossValidate | @Override public void crossValidate(Frame[] splits, Frame[] cv_preds, long[] offsets, int i) {
// Train a clone with slightly modified parameters (to account for cross-validation)
final DeepLearning cv = (DeepLearning) this.clone();
cv.genericCrossValidation(splits, offsets, i);
cv_preds[i] = ((DeepLearningModel) UKV.get(cv.dest())).score(cv.validation);
new TAtomic<DeepLearningModel>() {
@Override public DeepLearningModel atomic(DeepLearningModel m) {
if (!keep_cross_validation_splits && /*paranoid*/cv.dest().toString().contains("xval")) {
m.get_params().source = null;
m.get_params().validation=null;
m.get_params().response=null;
}
return m;
}
}.invoke(cv.dest());
} | java | @Override public void crossValidate(Frame[] splits, Frame[] cv_preds, long[] offsets, int i) {
// Train a clone with slightly modified parameters (to account for cross-validation)
final DeepLearning cv = (DeepLearning) this.clone();
cv.genericCrossValidation(splits, offsets, i);
cv_preds[i] = ((DeepLearningModel) UKV.get(cv.dest())).score(cv.validation);
new TAtomic<DeepLearningModel>() {
@Override public DeepLearningModel atomic(DeepLearningModel m) {
if (!keep_cross_validation_splits && /*paranoid*/cv.dest().toString().contains("xval")) {
m.get_params().source = null;
m.get_params().validation=null;
m.get_params().response=null;
}
return m;
}
}.invoke(cv.dest());
} | [
"@",
"Override",
"public",
"void",
"crossValidate",
"(",
"Frame",
"[",
"]",
"splits",
",",
"Frame",
"[",
"]",
"cv_preds",
",",
"long",
"[",
"]",
"offsets",
",",
"int",
"i",
")",
"{",
"// Train a clone with slightly modified parameters (to account for cross-validatio... | Cross-Validate a DeepLearning model by building new models on N train/test holdout splits
@param splits Frames containing train/test splits
@param cv_preds Array of Frames to store the predictions for each cross-validation run
@param offsets Array to store the offsets of starting row indices for each cross-validation run
@param i Which fold of cross-validation to perform | [
"Cross",
"-",
"Validate",
"a",
"DeepLearning",
"model",
"by",
"building",
"new",
"models",
"on",
"N",
"train",
"/",
"test",
"holdout",
"splits"
] | train | https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/src/main/java/hex/deeplearning/DeepLearning.java#L1305-L1320 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/TimestampBound.java | TimestampBound.ofReadTimestamp | public static TimestampBound ofReadTimestamp(Timestamp timestamp) {
return new TimestampBound(Mode.READ_TIMESTAMP, checkNotNull(timestamp), null);
} | java | public static TimestampBound ofReadTimestamp(Timestamp timestamp) {
return new TimestampBound(Mode.READ_TIMESTAMP, checkNotNull(timestamp), null);
} | [
"public",
"static",
"TimestampBound",
"ofReadTimestamp",
"(",
"Timestamp",
"timestamp",
")",
"{",
"return",
"new",
"TimestampBound",
"(",
"Mode",
".",
"READ_TIMESTAMP",
",",
"checkNotNull",
"(",
"timestamp",
")",
",",
"null",
")",
";",
"}"
] | Returns a timestamp bound that will perform reads and queries at the given timestamp. Unlike
other modes, reads at a specific timestamp are repeatable; the same read at the same timestamp
always returns the same data. If the timestamp is in the future, the read will block until the
specified timestamp, modulo the read's deadline.
<p>This mode is useful for large scale consistent reads such as mapreduces, or for coordinating
many reads against a consistent snapshot of the data. | [
"Returns",
"a",
"timestamp",
"bound",
"that",
"will",
"perform",
"reads",
"and",
"queries",
"at",
"the",
"given",
"timestamp",
".",
"Unlike",
"other",
"modes",
"reads",
"at",
"a",
"specific",
"timestamp",
"are",
"repeatable",
";",
"the",
"same",
"read",
"at"... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-spanner/src/main/java/com/google/cloud/spanner/TimestampBound.java#L152-L154 |
andreitognolo/raidenjpa | raidenjpa-core/src/main/java/org/raidenjpa/reflection/Cloner.java | Cloner.shallowCopy | @SuppressWarnings("unchecked")
public static <T> T shallowCopy(T original) {
Class<? extends T> clazz = (Class<? extends T>) original.getClass();
BeanClass<? extends T> beanClass = (BeanClass<? extends T>) classes.get(clazz);
if (beanClass == null) {
beanClass = BeanClass.buildFrom(clazz);
classes.put(clazz, beanClass);
}
return shallowCopyHelper(original, beanClass);
} | java | @SuppressWarnings("unchecked")
public static <T> T shallowCopy(T original) {
Class<? extends T> clazz = (Class<? extends T>) original.getClass();
BeanClass<? extends T> beanClass = (BeanClass<? extends T>) classes.get(clazz);
if (beanClass == null) {
beanClass = BeanClass.buildFrom(clazz);
classes.put(clazz, beanClass);
}
return shallowCopyHelper(original, beanClass);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"shallowCopy",
"(",
"T",
"original",
")",
"{",
"Class",
"<",
"?",
"extends",
"T",
">",
"clazz",
"=",
"(",
"Class",
"<",
"?",
"extends",
"T",
">",
")",
"origin... | Requires a no-args constructor
@param original
@return shallow copy of original | [
"Requires",
"a",
"no",
"-",
"args",
"constructor"
] | train | https://github.com/andreitognolo/raidenjpa/blob/1c6e320f9f9d26c89e54f41eab1ef123815d2f06/raidenjpa-core/src/main/java/org/raidenjpa/reflection/Cloner.java#L16-L28 |
galan/commons | src/main/java/de/galan/commons/net/flux/Response.java | Response.getStreamAsBytearray | public byte[] getStreamAsBytearray() throws IOException {
byte[] result = null;
try {
result = IOUtils.toByteArray(getStream());
}
catch (NullPointerException npex) {
throw new IOException("Timeout has been forced by CommonHttpClient", npex);
}
return result;
} | java | public byte[] getStreamAsBytearray() throws IOException {
byte[] result = null;
try {
result = IOUtils.toByteArray(getStream());
}
catch (NullPointerException npex) {
throw new IOException("Timeout has been forced by CommonHttpClient", npex);
}
return result;
} | [
"public",
"byte",
"[",
"]",
"getStreamAsBytearray",
"(",
")",
"throws",
"IOException",
"{",
"byte",
"[",
"]",
"result",
"=",
"null",
";",
"try",
"{",
"result",
"=",
"IOUtils",
".",
"toByteArray",
"(",
"getStream",
"(",
")",
")",
";",
"}",
"catch",
"(",... | Converts the inputstream to a string in UTF-8. Subsequent the inputstream will be empty/closed. | [
"Converts",
"the",
"inputstream",
"to",
"a",
"string",
"in",
"UTF",
"-",
"8",
".",
"Subsequent",
"the",
"inputstream",
"will",
"be",
"empty",
"/",
"closed",
"."
] | train | https://github.com/galan/commons/blob/45d2f36c69958d3f847e5fed66603ea629471822/src/main/java/de/galan/commons/net/flux/Response.java#L58-L67 |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java | ApiOvhXdsl.eligibility_search_fiberStreets_POST | public OvhAsyncTaskArray<OvhFiberStreet> eligibility_search_fiberStreets_POST(String inseeCode) throws IOException {
String qPath = "/xdsl/eligibility/search/fiberStreets";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "inseeCode", inseeCode);
String resp = execN(qPath, "POST", sb.toString(), o);
return convertTo(resp, t11);
} | java | public OvhAsyncTaskArray<OvhFiberStreet> eligibility_search_fiberStreets_POST(String inseeCode) throws IOException {
String qPath = "/xdsl/eligibility/search/fiberStreets";
StringBuilder sb = path(qPath);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "inseeCode", inseeCode);
String resp = execN(qPath, "POST", sb.toString(), o);
return convertTo(resp, t11);
} | [
"public",
"OvhAsyncTaskArray",
"<",
"OvhFiberStreet",
">",
"eligibility_search_fiberStreets_POST",
"(",
"String",
"inseeCode",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/xdsl/eligibility/search/fiberStreets\"",
";",
"StringBuilder",
"sb",
"=",
"path",
... | Get all street linked to a locality
REST: POST /xdsl/eligibility/search/fiberStreets
@param inseeCode [required] French INSEE identifier (you can get it with POST /xdsl/eligibility/search/cities)
@deprecated | [
"Get",
"all",
"street",
"linked",
"to",
"a",
"locality"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/ApiOvhXdsl.java#L392-L399 |
lotaris/jee-validation | src/main/java/com/lotaris/jee/validation/preprocessing/BeanValidationPreprocessor.java | BeanValidationPreprocessor.addError | private void addError(IValidationContext context, ConstraintViolation violation, JsonPointer pointer) {
// extract the error code, if any
final Class<? extends Annotation> annotationType = violation.getConstraintDescriptor().getAnnotation().annotationType();
final IErrorCode validationCode = constraintConverter.getErrorCode(annotationType);
final IErrorLocationType validationType = constraintConverter.getErrorLocationType(annotationType);
// add the error to the validation context
context.addError(pointer.toString(), validationType, validationCode, violation.getMessage());
} | java | private void addError(IValidationContext context, ConstraintViolation violation, JsonPointer pointer) {
// extract the error code, if any
final Class<? extends Annotation> annotationType = violation.getConstraintDescriptor().getAnnotation().annotationType();
final IErrorCode validationCode = constraintConverter.getErrorCode(annotationType);
final IErrorLocationType validationType = constraintConverter.getErrorLocationType(annotationType);
// add the error to the validation context
context.addError(pointer.toString(), validationType, validationCode, violation.getMessage());
} | [
"private",
"void",
"addError",
"(",
"IValidationContext",
"context",
",",
"ConstraintViolation",
"violation",
",",
"JsonPointer",
"pointer",
")",
"{",
"// extract the error code, if any",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
"=",
... | Adds an error message describing a constraint violation.
@param context the validation context to add errors to
@param violation the constraint violation
@param pointer a JSON pointer to the invalid value in the JSON document
@return an API error message | [
"Adds",
"an",
"error",
"message",
"describing",
"a",
"constraint",
"violation",
"."
] | train | https://github.com/lotaris/jee-validation/blob/feefff820b5a67c7471a13e08fdaf2d60bb3ad16/src/main/java/com/lotaris/jee/validation/preprocessing/BeanValidationPreprocessor.java#L162-L171 |
apache/groovy | src/main/groovy/groovy/util/FactoryBuilderSupport.java | FactoryBuilderSupport.resolveFactory | protected Factory resolveFactory(Object name, Map attributes, Object value) {
getProxyBuilder().getContext().put(CHILD_BUILDER, getProxyBuilder());
return getProxyBuilder().getFactories().get(name);
} | java | protected Factory resolveFactory(Object name, Map attributes, Object value) {
getProxyBuilder().getContext().put(CHILD_BUILDER, getProxyBuilder());
return getProxyBuilder().getFactories().get(name);
} | [
"protected",
"Factory",
"resolveFactory",
"(",
"Object",
"name",
",",
"Map",
"attributes",
",",
"Object",
"value",
")",
"{",
"getProxyBuilder",
"(",
")",
".",
"getContext",
"(",
")",
".",
"put",
"(",
"CHILD_BUILDER",
",",
"getProxyBuilder",
"(",
")",
")",
... | This is a hook for subclasses to plugin a custom strategy for mapping
names to factories.
@param name the name of the factory
@param attributes the attributes from the node
@param value value arguments from te node
@return the Factory associated with name.<br> | [
"This",
"is",
"a",
"hook",
"for",
"subclasses",
"to",
"plugin",
"a",
"custom",
"strategy",
"for",
"mapping",
"names",
"to",
"factories",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/util/FactoryBuilderSupport.java#L745-L748 |
Azure/azure-sdk-for-java | streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/InputsInner.java | InputsInner.createOrReplace | public InputInner createOrReplace(String resourceGroupName, String jobName, String inputName, InputInner input, String ifMatch, String ifNoneMatch) {
return createOrReplaceWithServiceResponseAsync(resourceGroupName, jobName, inputName, input, ifMatch, ifNoneMatch).toBlocking().single().body();
} | java | public InputInner createOrReplace(String resourceGroupName, String jobName, String inputName, InputInner input, String ifMatch, String ifNoneMatch) {
return createOrReplaceWithServiceResponseAsync(resourceGroupName, jobName, inputName, input, ifMatch, ifNoneMatch).toBlocking().single().body();
} | [
"public",
"InputInner",
"createOrReplace",
"(",
"String",
"resourceGroupName",
",",
"String",
"jobName",
",",
"String",
"inputName",
",",
"InputInner",
"input",
",",
"String",
"ifMatch",
",",
"String",
"ifNoneMatch",
")",
"{",
"return",
"createOrReplaceWithServiceResp... | Creates an input or replaces an already existing input under an existing streaming job.
@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 jobName The name of the streaming job.
@param inputName The name of the input.
@param input The definition of the input that will be used to create a new input or replace the existing one under the streaming job.
@param ifMatch The ETag of the input. Omit this value to always overwrite the current input. Specify the last-seen ETag value to prevent accidentally overwritting concurrent changes.
@param ifNoneMatch Set to '*' to allow a new input to be created, but to prevent updating an existing input. Other values will result in a 412 Pre-condition Failed response.
@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 InputInner object if successful. | [
"Creates",
"an",
"input",
"or",
"replaces",
"an",
"already",
"existing",
"input",
"under",
"an",
"existing",
"streaming",
"job",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/InputsInner.java#L214-L216 |
mbenson/therian | core/src/main/java/therian/util/Positions.java | Positions.readOnly | public static <T> Position.Readable<T> readOnly(final Type type, final T value) {
Validate.isTrue(TypeUtils.isInstance(value, type), "%s is not an instance of %s", value, Types.toString(type));
return readOnly(type, () -> value);
} | java | public static <T> Position.Readable<T> readOnly(final Type type, final T value) {
Validate.isTrue(TypeUtils.isInstance(value, type), "%s is not an instance of %s", value, Types.toString(type));
return readOnly(type, () -> value);
} | [
"public",
"static",
"<",
"T",
">",
"Position",
".",
"Readable",
"<",
"T",
">",
"readOnly",
"(",
"final",
"Type",
"type",
",",
"final",
"T",
"value",
")",
"{",
"Validate",
".",
"isTrue",
"(",
"TypeUtils",
".",
"isInstance",
"(",
"value",
",",
"type",
... | Get a read-only position of type {@code type} and value {@code value}.
@param type not {@code null}
@param value
@return Position.Readable | [
"Get",
"a",
"read",
"-",
"only",
"position",
"of",
"type",
"{",
"@code",
"type",
"}",
"and",
"value",
"{",
"@code",
"value",
"}",
"."
] | train | https://github.com/mbenson/therian/blob/0653505f73e2a6f5b0abc394ea6d83af03408254/core/src/main/java/therian/util/Positions.java#L178-L181 |
VueGWT/vue-gwt | processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/VForDefinition.java | VForDefinition.initKeyVariable | private void initKeyVariable(String name, TemplateParserContext context) {
this.keyVariableInfo = context.addLocalVariable("String", name.trim());
} | java | private void initKeyVariable(String name, TemplateParserContext context) {
this.keyVariableInfo = context.addLocalVariable("String", name.trim());
} | [
"private",
"void",
"initKeyVariable",
"(",
"String",
"name",
",",
"TemplateParserContext",
"context",
")",
"{",
"this",
".",
"keyVariableInfo",
"=",
"context",
".",
"addLocalVariable",
"(",
"\"String\"",
",",
"name",
".",
"trim",
"(",
")",
")",
";",
"}"
] | Init the key variable and add it to the parser context
@param name Name of the variable
@param context Context of the template parser | [
"Init",
"the",
"key",
"variable",
"and",
"add",
"it",
"to",
"the",
"parser",
"context"
] | train | https://github.com/VueGWT/vue-gwt/blob/961cd83aed6fe8e2dd80c279847f1b3f62918a1f/processors/src/main/java/com/axellience/vuegwt/processors/component/template/parser/VForDefinition.java#L179-L181 |
wmdietl/jsr308-langtools | src/share/classes/javax/tools/ToolProvider.java | ToolProvider.getSystemToolClassLoader | public static ClassLoader getSystemToolClassLoader() {
try {
Class<? extends JavaCompiler> c =
instance().getSystemToolClass(JavaCompiler.class, defaultJavaCompilerName);
return c.getClassLoader();
} catch (Throwable e) {
return trace(WARNING, e);
}
} | java | public static ClassLoader getSystemToolClassLoader() {
try {
Class<? extends JavaCompiler> c =
instance().getSystemToolClass(JavaCompiler.class, defaultJavaCompilerName);
return c.getClassLoader();
} catch (Throwable e) {
return trace(WARNING, e);
}
} | [
"public",
"static",
"ClassLoader",
"getSystemToolClassLoader",
"(",
")",
"{",
"try",
"{",
"Class",
"<",
"?",
"extends",
"JavaCompiler",
">",
"c",
"=",
"instance",
"(",
")",
".",
"getSystemToolClass",
"(",
"JavaCompiler",
".",
"class",
",",
"defaultJavaCompilerNa... | Returns the class loader for tools provided with this platform.
This does not include user-installed tools. Use the
{@linkplain java.util.ServiceLoader service provider mechanism}
for locating user installed tools.
@return the class loader for tools provided with this platform
or {@code null} if no tools are provided | [
"Returns",
"the",
"class",
"loader",
"for",
"tools",
"provided",
"with",
"this",
"platform",
".",
"This",
"does",
"not",
"include",
"user",
"-",
"installed",
"tools",
".",
"Use",
"the",
"{",
"@linkplain",
"java",
".",
"util",
".",
"ServiceLoader",
"service",... | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/javax/tools/ToolProvider.java#L127-L135 |
kite-sdk/kite | kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/stdio/AbstractParser.java | AbstractParser.isMimeTypeMatch | private boolean isMimeTypeMatch(MediaType mediaType, MediaType rangePattern) {
String WILDCARD = "*";
String rangePatternType = rangePattern.getType();
String rangePatternSubtype = rangePattern.getSubtype();
return (rangePatternType.equals(WILDCARD) || rangePatternType.equals(mediaType.getType()))
&& (rangePatternSubtype.equals(WILDCARD) || rangePatternSubtype.equals(mediaType.getSubtype()));
} | java | private boolean isMimeTypeMatch(MediaType mediaType, MediaType rangePattern) {
String WILDCARD = "*";
String rangePatternType = rangePattern.getType();
String rangePatternSubtype = rangePattern.getSubtype();
return (rangePatternType.equals(WILDCARD) || rangePatternType.equals(mediaType.getType()))
&& (rangePatternSubtype.equals(WILDCARD) || rangePatternSubtype.equals(mediaType.getSubtype()));
} | [
"private",
"boolean",
"isMimeTypeMatch",
"(",
"MediaType",
"mediaType",
",",
"MediaType",
"rangePattern",
")",
"{",
"String",
"WILDCARD",
"=",
"\"*\"",
";",
"String",
"rangePatternType",
"=",
"rangePattern",
".",
"getType",
"(",
")",
";",
"String",
"rangePatternSu... | Returns true if mediaType falls withing the given range (pattern), false otherwise | [
"Returns",
"true",
"if",
"mediaType",
"falls",
"withing",
"the",
"given",
"range",
"(",
"pattern",
")",
"false",
"otherwise"
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/stdio/AbstractParser.java#L141-L147 |
fabric8io/docker-maven-plugin | src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4.java | AwsSigner4.task4 | String task4(AwsSigner4Request sr, AuthConfig credentials) {
StringBuilder sb = new StringBuilder("AWS4-HMAC-SHA256 Credential=")
.append(credentials.getUsername() ).append( '/' ).append( sr.getScope() )
.append(", SignedHeaders=").append(sr.getSignedHeaders())
.append(", Signature=" );
hexEncode(sb, task3(sr, credentials));
return sb.toString();
} | java | String task4(AwsSigner4Request sr, AuthConfig credentials) {
StringBuilder sb = new StringBuilder("AWS4-HMAC-SHA256 Credential=")
.append(credentials.getUsername() ).append( '/' ).append( sr.getScope() )
.append(", SignedHeaders=").append(sr.getSignedHeaders())
.append(", Signature=" );
hexEncode(sb, task3(sr, credentials));
return sb.toString();
} | [
"String",
"task4",
"(",
"AwsSigner4Request",
"sr",
",",
"AuthConfig",
"credentials",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"\"AWS4-HMAC-SHA256 Credential=\"",
")",
".",
"append",
"(",
"credentials",
".",
"getUsername",
"(",
")",
")",
... | Task 4.
<a href="https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html">Add the Signing Information to the Request</a> | [
"Task",
"4",
".",
"<a",
"href",
"=",
"https",
":",
"//",
"docs",
".",
"aws",
".",
"amazon",
".",
"com",
"/",
"general",
"/",
"latest",
"/",
"gr",
"/",
"sigv4",
"-",
"add",
"-",
"signature",
"-",
"to",
"-",
"request",
".",
"html",
">",
"Add",
"t... | train | https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/access/ecr/AwsSigner4.java#L114-L121 |
apptik/JustJson | json-core/src/main/java/io/apptik/json/JsonObject.java | JsonObject.optDouble | public Double optDouble(String name, Double fallback) {
return optDouble(name, fallback, true);
} | java | public Double optDouble(String name, Double fallback) {
return optDouble(name, fallback, true);
} | [
"public",
"Double",
"optDouble",
"(",
"String",
"name",
",",
"Double",
"fallback",
")",
"{",
"return",
"optDouble",
"(",
"name",
",",
"fallback",
",",
"true",
")",
";",
"}"
] | Returns the value mapped by {@code name} if it exists and is a double or
can be coerced to a double, or {@code fallback} otherwise. | [
"Returns",
"the",
"value",
"mapped",
"by",
"{"
] | train | https://github.com/apptik/JustJson/blob/c90f0dd7f84df26da4749be8cd9b026fff499a79/json-core/src/main/java/io/apptik/json/JsonObject.java#L447-L449 |
opsmatters/newrelic-api | src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java | HttpContext.executePatchRequest | protected void executePatchRequest(URI uri, Object obj)
{
executePatchRequest(uri, obj, null, null);
} | java | protected void executePatchRequest(URI uri, Object obj)
{
executePatchRequest(uri, obj, null, null);
} | [
"protected",
"void",
"executePatchRequest",
"(",
"URI",
"uri",
",",
"Object",
"obj",
")",
"{",
"executePatchRequest",
"(",
"uri",
",",
"obj",
",",
"null",
",",
"null",
")",
";",
"}"
] | Execute a PATCH request.
@param uri The URI to call
@param obj The object to use for the PATCH | [
"Execute",
"a",
"PATCH",
"request",
"."
] | train | https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/services/HttpContext.java#L476-L479 |
landawn/AbacusUtil | src/com/landawn/abacus/util/JdbcUtil.java | JdbcUtil.dropTableIfExists | public static boolean dropTableIfExists(final Connection conn, final String tableName) {
try {
if (doesTableExist(conn, tableName)) {
execute(conn, "DROP TABLE " + tableName);
return true;
}
} catch (SQLException e) {
// ignore.
}
return false;
} | java | public static boolean dropTableIfExists(final Connection conn, final String tableName) {
try {
if (doesTableExist(conn, tableName)) {
execute(conn, "DROP TABLE " + tableName);
return true;
}
} catch (SQLException e) {
// ignore.
}
return false;
} | [
"public",
"static",
"boolean",
"dropTableIfExists",
"(",
"final",
"Connection",
"conn",
",",
"final",
"String",
"tableName",
")",
"{",
"try",
"{",
"if",
"(",
"doesTableExist",
"(",
"conn",
",",
"tableName",
")",
")",
"{",
"execute",
"(",
"conn",
",",
"\"DR... | Returns {@code true} if succeed to drop table, otherwise {@code false} is returned.
@param conn
@param tableName
@return | [
"Returns",
"{",
"@code",
"true",
"}",
"if",
"succeed",
"to",
"drop",
"table",
"otherwise",
"{",
"@code",
"false",
"}",
"is",
"returned",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L1687-L1699 |
tvesalainen/util | util/src/main/java/org/vesalainen/navi/Chain.java | Chain.horizontalScope | public double horizontalScope(double T, double d, double s)
{
double Fw = T / w;
return (Fw - d) * Math.log((s + Fw) / (Fw - d));
} | java | public double horizontalScope(double T, double d, double s)
{
double Fw = T / w;
return (Fw - d) * Math.log((s + Fw) / (Fw - d));
} | [
"public",
"double",
"horizontalScope",
"(",
"double",
"T",
",",
"double",
"d",
",",
"double",
"s",
")",
"{",
"double",
"Fw",
"=",
"T",
"/",
"w",
";",
"return",
"(",
"Fw",
"-",
"d",
")",
"*",
"Math",
".",
"log",
"(",
"(",
"s",
"+",
"Fw",
")",
... | Horizontal scope (length in plan view from fairlead to touchdown point)
@param T Fairlead tension
@param d Depth
@param s Chain length
@return | [
"Horizontal",
"scope",
"(",
"length",
"in",
"plan",
"view",
"from",
"fairlead",
"to",
"touchdown",
"point",
")"
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/navi/Chain.java#L71-L75 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java | ServiceDiscoveryManager.findServicesDiscoverInfo | public List<DiscoverInfo> findServicesDiscoverInfo(String feature, boolean stopOnFirst, boolean useCache, Map<? super Jid, Exception> encounteredExceptions)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
DomainBareJid serviceName = connection().getXMPPServiceDomain();
return findServicesDiscoverInfo(serviceName, feature, stopOnFirst, useCache, encounteredExceptions);
} | java | public List<DiscoverInfo> findServicesDiscoverInfo(String feature, boolean stopOnFirst, boolean useCache, Map<? super Jid, Exception> encounteredExceptions)
throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
DomainBareJid serviceName = connection().getXMPPServiceDomain();
return findServicesDiscoverInfo(serviceName, feature, stopOnFirst, useCache, encounteredExceptions);
} | [
"public",
"List",
"<",
"DiscoverInfo",
">",
"findServicesDiscoverInfo",
"(",
"String",
"feature",
",",
"boolean",
"stopOnFirst",
",",
"boolean",
"useCache",
",",
"Map",
"<",
"?",
"super",
"Jid",
",",
"Exception",
">",
"encounteredExceptions",
")",
"throws",
"NoR... | Find all services under the users service that provide a given feature.
@param feature the feature to search for
@param stopOnFirst if true, stop searching after the first service was found
@param useCache if true, query a cache first to avoid network I/O
@param encounteredExceptions an optional map which will be filled with the exceptions encountered
@return a possible empty list of services providing the given feature
@throws NoResponseException
@throws XMPPErrorException
@throws NotConnectedException
@throws InterruptedException
@since 4.2.2 | [
"Find",
"all",
"services",
"under",
"the",
"users",
"service",
"that",
"provide",
"a",
"given",
"feature",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/disco/ServiceDiscoveryManager.java#L703-L707 |
EMCECS/nfs-client-java | src/main/java/com/emc/ecs/nfsclient/network/RecordMarkingUtil.java | RecordMarkingUtil.putRecordMarkingAndSend | static void putRecordMarkingAndSend(Channel channel, Xdr rpcRequest) {
// XDR header buffer
List<ByteBuffer> buffers = new LinkedList<>();
buffers.add(ByteBuffer.wrap(rpcRequest.getBuffer(), 0, rpcRequest.getOffset()));
// payload buffer
if (rpcRequest.getPayloads() != null) {
buffers.addAll(rpcRequest.getPayloads());
}
List<ByteBuffer> outBuffers = new ArrayList<>();
int bytesToWrite = 0;
int remainingBuffers = buffers.size();
boolean isLast = false;
for (ByteBuffer buffer : buffers) {
if (bytesToWrite + buffer.remaining() > MTU_SIZE) {
if (outBuffers.isEmpty()) {
LOG.error("too big single byte buffer {}", buffer.remaining());
throw new IllegalArgumentException(
String.format("too big single byte buffer %d", buffer.remaining()));
} else {
sendBuffers(channel, bytesToWrite, outBuffers, isLast);
bytesToWrite = 0;
outBuffers.clear();
}
}
outBuffers.add(buffer);
bytesToWrite += buffer.remaining();
remainingBuffers -= 1;
isLast = (remainingBuffers == 0);
}
// send out remaining buffers
if (!outBuffers.isEmpty()) {
sendBuffers(channel, bytesToWrite, outBuffers, true);
}
} | java | static void putRecordMarkingAndSend(Channel channel, Xdr rpcRequest) {
// XDR header buffer
List<ByteBuffer> buffers = new LinkedList<>();
buffers.add(ByteBuffer.wrap(rpcRequest.getBuffer(), 0, rpcRequest.getOffset()));
// payload buffer
if (rpcRequest.getPayloads() != null) {
buffers.addAll(rpcRequest.getPayloads());
}
List<ByteBuffer> outBuffers = new ArrayList<>();
int bytesToWrite = 0;
int remainingBuffers = buffers.size();
boolean isLast = false;
for (ByteBuffer buffer : buffers) {
if (bytesToWrite + buffer.remaining() > MTU_SIZE) {
if (outBuffers.isEmpty()) {
LOG.error("too big single byte buffer {}", buffer.remaining());
throw new IllegalArgumentException(
String.format("too big single byte buffer %d", buffer.remaining()));
} else {
sendBuffers(channel, bytesToWrite, outBuffers, isLast);
bytesToWrite = 0;
outBuffers.clear();
}
}
outBuffers.add(buffer);
bytesToWrite += buffer.remaining();
remainingBuffers -= 1;
isLast = (remainingBuffers == 0);
}
// send out remaining buffers
if (!outBuffers.isEmpty()) {
sendBuffers(channel, bytesToWrite, outBuffers, true);
}
} | [
"static",
"void",
"putRecordMarkingAndSend",
"(",
"Channel",
"channel",
",",
"Xdr",
"rpcRequest",
")",
"{",
"// XDR header buffer",
"List",
"<",
"ByteBuffer",
">",
"buffers",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"buffers",
".",
"add",
"(",
"ByteBuffe... | Insert record marking into rpcRequest and then send to tcp stream.
@param channel The Channel to use for sending.
@param rpcRequest The request to send. | [
"Insert",
"record",
"marking",
"into",
"rpcRequest",
"and",
"then",
"send",
"to",
"tcp",
"stream",
"."
] | train | https://github.com/EMCECS/nfs-client-java/blob/7ba25bad5052b95cd286052745327729288b2843/src/main/java/com/emc/ecs/nfsclient/network/RecordMarkingUtil.java#L75-L117 |
OpenHFT/Chronicle-Map | src/main/java/net/openhft/chronicle/hash/impl/util/math/PoissonDistribution.java | PoissonDistribution.checkedCumulativeProbability | private static double checkedCumulativeProbability(double mean, long argument) {
double result = cumulativeProbability(mean, argument);
if (Double.isNaN(result)) {
throw new AssertionError("Discrete cumulative probability function returned NaN " +
"for argument " + argument);
}
return result;
} | java | private static double checkedCumulativeProbability(double mean, long argument) {
double result = cumulativeProbability(mean, argument);
if (Double.isNaN(result)) {
throw new AssertionError("Discrete cumulative probability function returned NaN " +
"for argument " + argument);
}
return result;
} | [
"private",
"static",
"double",
"checkedCumulativeProbability",
"(",
"double",
"mean",
",",
"long",
"argument",
")",
"{",
"double",
"result",
"=",
"cumulativeProbability",
"(",
"mean",
",",
"argument",
")",
";",
"if",
"(",
"Double",
".",
"isNaN",
"(",
"result",... | Computes the cumulative probability function and checks for {@code NaN}
values returned. Throws {@code MathInternalError} if the value is
{@code NaN}. Rethrows any exception encountered evaluating the cumulative
probability function. Throws {@code MathInternalError} if the cumulative
probability function returns {@code NaN}.
@param argument input value
@return the cumulative probability
@throws AssertionError if the cumulative probability is {@code NaN} | [
"Computes",
"the",
"cumulative",
"probability",
"function",
"and",
"checks",
"for",
"{",
"@code",
"NaN",
"}",
"values",
"returned",
".",
"Throws",
"{",
"@code",
"MathInternalError",
"}",
"if",
"the",
"value",
"is",
"{",
"@code",
"NaN",
"}",
".",
"Rethrows",
... | train | https://github.com/OpenHFT/Chronicle-Map/blob/0b09733cc96302f96be4394a261699eeb021fe37/src/main/java/net/openhft/chronicle/hash/impl/util/math/PoissonDistribution.java#L153-L160 |
mgm-tp/jfunk | jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/constraint/ConstraintFactory.java | ConstraintFactory.putToCache | private void putToCache(final Element element, final Constraint object) {
String id = element.getAttributeValue(XMLTags.ID);
if (id != null && id.length() > 0) {
Constraint old = putToCache(id, object);
if (old != null) {
LOG.warn("The id=" + id + " for object of type=" + old.getClass().getName()
+ " was already found. Please make sure this is ok and no mistake.");
}
}
} | java | private void putToCache(final Element element, final Constraint object) {
String id = element.getAttributeValue(XMLTags.ID);
if (id != null && id.length() > 0) {
Constraint old = putToCache(id, object);
if (old != null) {
LOG.warn("The id=" + id + " for object of type=" + old.getClass().getName()
+ " was already found. Please make sure this is ok and no mistake.");
}
}
} | [
"private",
"void",
"putToCache",
"(",
"final",
"Element",
"element",
",",
"final",
"Constraint",
"object",
")",
"{",
"String",
"id",
"=",
"element",
".",
"getAttributeValue",
"(",
"XMLTags",
".",
"ID",
")",
";",
"if",
"(",
"id",
"!=",
"null",
"&&",
"id",... | If the element has an attribute with name id this attribute's value will be used as key to
store the just generated object in a map. The object can in this case also be retrieved using
this id.
@see #getModel(String) | [
"If",
"the",
"element",
"has",
"an",
"attribute",
"with",
"name",
"id",
"this",
"attribute",
"s",
"value",
"will",
"be",
"used",
"as",
"key",
"to",
"store",
"the",
"just",
"generated",
"object",
"in",
"a",
"map",
".",
"The",
"object",
"can",
"in",
"thi... | train | https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/constraint/ConstraintFactory.java#L166-L175 |
apereo/cas | support/cas-server-support-x509-core/src/main/java/org/apereo/cas/adaptors/x509/authentication/handler/support/X509CredentialsAuthenticationHandler.java | X509CredentialsAuthenticationHandler.isCritical | private static boolean isCritical(final X509Certificate certificate, final String extensionOid) {
val criticalOids = certificate.getCriticalExtensionOIDs();
if (criticalOids == null || criticalOids.isEmpty()) {
return false;
}
return criticalOids.contains(extensionOid);
} | java | private static boolean isCritical(final X509Certificate certificate, final String extensionOid) {
val criticalOids = certificate.getCriticalExtensionOIDs();
if (criticalOids == null || criticalOids.isEmpty()) {
return false;
}
return criticalOids.contains(extensionOid);
} | [
"private",
"static",
"boolean",
"isCritical",
"(",
"final",
"X509Certificate",
"certificate",
",",
"final",
"String",
"extensionOid",
")",
"{",
"val",
"criticalOids",
"=",
"certificate",
".",
"getCriticalExtensionOIDs",
"(",
")",
";",
"if",
"(",
"criticalOids",
"=... | Checks if critical extension oids contain the extension oid.
@param certificate the certificate
@param extensionOid the extension oid
@return true, if critical | [
"Checks",
"if",
"critical",
"extension",
"oids",
"contain",
"the",
"extension",
"oid",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-x509-core/src/main/java/org/apereo/cas/adaptors/x509/authentication/handler/support/X509CredentialsAuthenticationHandler.java#L148-L154 |
alkacon/opencms-core | src/org/opencms/ade/containerpage/CmsDetailOnlyContainerUtil.java | CmsDetailOnlyContainerUtil.getDetailOnlyPageNameWithoutLocaleCheck | static String getDetailOnlyPageNameWithoutLocaleCheck(String detailContentSitePath, String contentLocale) {
String result = CmsResource.getFolderPath(detailContentSitePath);
if (contentLocale != null) {
result = CmsStringUtil.joinPaths(
result,
DETAIL_CONTAINERS_FOLDER_NAME,
contentLocale.toString(),
CmsResource.getName(detailContentSitePath));
} else {
result = CmsStringUtil.joinPaths(
result,
DETAIL_CONTAINERS_FOLDER_NAME,
CmsResource.getName(detailContentSitePath));
}
return result;
} | java | static String getDetailOnlyPageNameWithoutLocaleCheck(String detailContentSitePath, String contentLocale) {
String result = CmsResource.getFolderPath(detailContentSitePath);
if (contentLocale != null) {
result = CmsStringUtil.joinPaths(
result,
DETAIL_CONTAINERS_FOLDER_NAME,
contentLocale.toString(),
CmsResource.getName(detailContentSitePath));
} else {
result = CmsStringUtil.joinPaths(
result,
DETAIL_CONTAINERS_FOLDER_NAME,
CmsResource.getName(detailContentSitePath));
}
return result;
} | [
"static",
"String",
"getDetailOnlyPageNameWithoutLocaleCheck",
"(",
"String",
"detailContentSitePath",
",",
"String",
"contentLocale",
")",
"{",
"String",
"result",
"=",
"CmsResource",
".",
"getFolderPath",
"(",
"detailContentSitePath",
")",
";",
"if",
"(",
"contentLoca... | Returns the site path to the detail only container page.<p>
This does not perform any further checks regarding the locale and assumes that all these checks have been done before.
@param detailContentSitePath the detail content site path
@param contentLocale the content locale
@return the site path to the detail only container page | [
"Returns",
"the",
"site",
"path",
"to",
"the",
"detail",
"only",
"container",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/containerpage/CmsDetailOnlyContainerUtil.java#L466-L482 |
lucee/Lucee | core/src/main/java/lucee/runtime/tag/Mail.java | Mail.setBcc | public void setBcc(Object bcc) throws ApplicationException {
if (StringUtil.isEmpty(bcc)) return;
try {
smtp.addBCC(bcc);
}
catch (Exception e) {
throw new ApplicationException("attribute [bcc] of the tag [mail] is invalid", e.getMessage());
}
} | java | public void setBcc(Object bcc) throws ApplicationException {
if (StringUtil.isEmpty(bcc)) return;
try {
smtp.addBCC(bcc);
}
catch (Exception e) {
throw new ApplicationException("attribute [bcc] of the tag [mail] is invalid", e.getMessage());
}
} | [
"public",
"void",
"setBcc",
"(",
"Object",
"bcc",
")",
"throws",
"ApplicationException",
"{",
"if",
"(",
"StringUtil",
".",
"isEmpty",
"(",
"bcc",
")",
")",
"return",
";",
"try",
"{",
"smtp",
".",
"addBCC",
"(",
"bcc",
")",
";",
"}",
"catch",
"(",
"E... | set the value bcc Indicates addresses to copy the e-mail message to, without listing them in the
message header. "bcc" stands for "blind carbon copy."
@param strBcc value to set
@throws ApplicationException | [
"set",
"the",
"value",
"bcc",
"Indicates",
"addresses",
"to",
"copy",
"the",
"e",
"-",
"mail",
"message",
"to",
"without",
"listing",
"them",
"in",
"the",
"message",
"header",
".",
"bcc",
"stands",
"for",
"blind",
"carbon",
"copy",
"."
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/tag/Mail.java#L235-L243 |
jaliss/securesocial | samples/java/demo/app/controllers/Application.java | Application.index | @SecuredAction
public Result index() {
if(logger.isDebugEnabled()){
logger.debug("access granted to index");
}
DemoUser user = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
return ok(index.render(user, SecureSocial.env()));
} | java | @SecuredAction
public Result index() {
if(logger.isDebugEnabled()){
logger.debug("access granted to index");
}
DemoUser user = (DemoUser) ctx().args.get(SecureSocial.USER_KEY);
return ok(index.render(user, SecureSocial.env()));
} | [
"@",
"SecuredAction",
"public",
"Result",
"index",
"(",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"access granted to index\"",
")",
";",
"}",
"DemoUser",
"user",
"=",
"(",
"DemoUser",
")",
"c... | This action only gets called if the user is logged in.
@return | [
"This",
"action",
"only",
"gets",
"called",
"if",
"the",
"user",
"is",
"logged",
"in",
"."
] | train | https://github.com/jaliss/securesocial/blob/0f9710325724da34a46c5ecefb439121fce837b7/samples/java/demo/app/controllers/Application.java#L60-L67 |
Azure/azure-sdk-for-java | policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java | PolicyStatesInner.summarizeForPolicyDefinitionAsync | public Observable<SummarizeResultsInner> summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) {
return summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).map(new Func1<ServiceResponse<SummarizeResultsInner>, SummarizeResultsInner>() {
@Override
public SummarizeResultsInner call(ServiceResponse<SummarizeResultsInner> response) {
return response.body();
}
});
} | java | public Observable<SummarizeResultsInner> summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) {
return summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).map(new Func1<ServiceResponse<SummarizeResultsInner>, SummarizeResultsInner>() {
@Override
public SummarizeResultsInner call(ServiceResponse<SummarizeResultsInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SummarizeResultsInner",
">",
"summarizeForPolicyDefinitionAsync",
"(",
"String",
"subscriptionId",
",",
"String",
"policyDefinitionName",
",",
"QueryOptions",
"queryOptions",
")",
"{",
"return",
"summarizeForPolicyDefinitionWithServiceResponseAsync",... | Summarizes policy states for the subscription level policy definition.
@param subscriptionId Microsoft Azure subscription ID.
@param policyDefinitionName Policy definition name.
@param queryOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SummarizeResultsInner object | [
"Summarizes",
"policy",
"states",
"for",
"the",
"subscription",
"level",
"policy",
"definition",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policyinsights/resource-manager/v2018_04_04/src/main/java/com/microsoft/azure/management/policyinsights/v2018_04_04/implementation/PolicyStatesInner.java#L2395-L2402 |
jbossws/jbossws-common | src/main/java/org/jboss/ws/common/utils/HashCodeUtil.java | HashCodeUtil.hash | public static int hash(int aSeed, Object aObject)
{
int result = aSeed;
if (aObject == null)
{
result = org.jboss.ws.common.utils.HashCodeUtil.hash(result, 0);
}
else if (!org.jboss.ws.common.utils.HashCodeUtil.isArray(aObject))
{
result = org.jboss.ws.common.utils.HashCodeUtil.hash(result, aObject.hashCode());
}
else
{
int length = Array.getLength(aObject);
for (int idx = 0; idx < length; ++idx)
{
Object item = Array.get(aObject, idx);
//recursive call!
result = org.jboss.ws.common.utils.HashCodeUtil.hash(result, item);
}
}
return result;
} | java | public static int hash(int aSeed, Object aObject)
{
int result = aSeed;
if (aObject == null)
{
result = org.jboss.ws.common.utils.HashCodeUtil.hash(result, 0);
}
else if (!org.jboss.ws.common.utils.HashCodeUtil.isArray(aObject))
{
result = org.jboss.ws.common.utils.HashCodeUtil.hash(result, aObject.hashCode());
}
else
{
int length = Array.getLength(aObject);
for (int idx = 0; idx < length; ++idx)
{
Object item = Array.get(aObject, idx);
//recursive call!
result = org.jboss.ws.common.utils.HashCodeUtil.hash(result, item);
}
}
return result;
} | [
"public",
"static",
"int",
"hash",
"(",
"int",
"aSeed",
",",
"Object",
"aObject",
")",
"{",
"int",
"result",
"=",
"aSeed",
";",
"if",
"(",
"aObject",
"==",
"null",
")",
"{",
"result",
"=",
"org",
".",
"jboss",
".",
"ws",
".",
"common",
".",
"utils"... | <code>aObject</code> is a possibly-null object field, and possibly an array.
If <code>aObject</code> is an array, then each element may be a primitive
or a possibly-null object. | [
"<code",
">",
"aObject<",
"/",
"code",
">",
"is",
"a",
"possibly",
"-",
"null",
"object",
"field",
"and",
"possibly",
"an",
"array",
"."
] | train | https://github.com/jbossws/jbossws-common/blob/fcff8a3ef9bfe046d6fa8c855a3fe4f62841add7/src/main/java/org/jboss/ws/common/utils/HashCodeUtil.java#L110-L132 |
h2oai/h2o-2 | hadoop/src/main/java/water/hadoop/h2omapper.java | h2omapper.emitLogHeader | private void emitLogHeader(Context context, String mapredTaskId) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
Text textId = new Text(mapredTaskId);
for (Map.Entry<String, String> entry: conf) {
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
context.write(textId, new Text(sb.toString()));
}
context.write(textId, new Text("----- Properties -----"));
String[] plist = {
"mapred.local.dir",
"mapred.child.java.opts",
};
for (String k : plist) {
String v = conf.get(k);
if (v == null) {
v = "(null)";
}
context.write(textId, new Text(k + " " + v));
}
String userDir = System.getProperty("user.dir");
context.write(textId, new Text("user.dir " + userDir));
try {
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
context.write(textId, new Text("hostname " + localMachine.getHostName()));
}
catch (java.net.UnknownHostException uhe) {
// handle exception
}
} | java | private void emitLogHeader(Context context, String mapredTaskId) throws IOException, InterruptedException {
Configuration conf = context.getConfiguration();
Text textId = new Text(mapredTaskId);
for (Map.Entry<String, String> entry: conf) {
StringBuilder sb = new StringBuilder();
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
context.write(textId, new Text(sb.toString()));
}
context.write(textId, new Text("----- Properties -----"));
String[] plist = {
"mapred.local.dir",
"mapred.child.java.opts",
};
for (String k : plist) {
String v = conf.get(k);
if (v == null) {
v = "(null)";
}
context.write(textId, new Text(k + " " + v));
}
String userDir = System.getProperty("user.dir");
context.write(textId, new Text("user.dir " + userDir));
try {
java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
context.write(textId, new Text("hostname " + localMachine.getHostName()));
}
catch (java.net.UnknownHostException uhe) {
// handle exception
}
} | [
"private",
"void",
"emitLogHeader",
"(",
"Context",
"context",
",",
"String",
"mapredTaskId",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"Configuration",
"conf",
"=",
"context",
".",
"getConfiguration",
"(",
")",
";",
"Text",
"textId",
"=",
... | Emit a bunch of logging output at the beginning of the map task.
@throws IOException
@throws InterruptedException | [
"Emit",
"a",
"bunch",
"of",
"logging",
"output",
"at",
"the",
"beginning",
"of",
"the",
"map",
"task",
"."
] | train | https://github.com/h2oai/h2o-2/blob/be350f3f2c2fb6f135cc07c41f83fd0e4f521ac1/hadoop/src/main/java/water/hadoop/h2omapper.java#L270-L304 |
bazaarvoice/emodb | mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java | EmoSerDe.getRawValueOrNullIfAbsent | private Object getRawValueOrNullIfAbsent(String columnName, Map<String, Object> content)
throws SerDeException {
try {
return getRawValue(columnName, content);
} catch (ColumnNotFoundException e) {
return null;
}
} | java | private Object getRawValueOrNullIfAbsent(String columnName, Map<String, Object> content)
throws SerDeException {
try {
return getRawValue(columnName, content);
} catch (ColumnNotFoundException e) {
return null;
}
} | [
"private",
"Object",
"getRawValueOrNullIfAbsent",
"(",
"String",
"columnName",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"content",
")",
"throws",
"SerDeException",
"{",
"try",
"{",
"return",
"getRawValue",
"(",
"columnName",
",",
"content",
")",
";",
"}"... | Like {@link #getRawValue(String, java.util.Map)} except it returns null if the value is not present. | [
"Like",
"{"
] | train | https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/mapreduce/sor-hive/src/main/java/com/bazaarvoice/emodb/hive/EmoSerDe.java#L278-L285 |
alkacon/opencms-core | src/org/opencms/ui/apps/A_CmsWorkplaceApp.java | A_CmsWorkplaceApp.updateBreadCrumb | protected void updateBreadCrumb(Map<String, String> breadCrumbEntries) {
LinkedHashMap<String, String> entries = new LinkedHashMap<String, String>();
I_CmsWorkplaceAppConfiguration launchpadConfig = OpenCms.getWorkplaceAppManager().getAppConfiguration(
CmsAppHierarchyConfiguration.APP_ID);
if (launchpadConfig.getVisibility(A_CmsUI.getCmsObject()).isActive()) {
entries.put(CmsAppHierarchyConfiguration.APP_ID, launchpadConfig.getName(UI.getCurrent().getLocale()));
}
if ((breadCrumbEntries != null) && !breadCrumbEntries.isEmpty()) {
entries.putAll(breadCrumbEntries);
} else {
entries.put(
"",
OpenCms.getWorkplaceAppManager().getAppConfiguration(m_uiContext.getAppId()).getName(
UI.getCurrent().getLocale()));
}
m_breadCrumb.setEntries(entries);
} | java | protected void updateBreadCrumb(Map<String, String> breadCrumbEntries) {
LinkedHashMap<String, String> entries = new LinkedHashMap<String, String>();
I_CmsWorkplaceAppConfiguration launchpadConfig = OpenCms.getWorkplaceAppManager().getAppConfiguration(
CmsAppHierarchyConfiguration.APP_ID);
if (launchpadConfig.getVisibility(A_CmsUI.getCmsObject()).isActive()) {
entries.put(CmsAppHierarchyConfiguration.APP_ID, launchpadConfig.getName(UI.getCurrent().getLocale()));
}
if ((breadCrumbEntries != null) && !breadCrumbEntries.isEmpty()) {
entries.putAll(breadCrumbEntries);
} else {
entries.put(
"",
OpenCms.getWorkplaceAppManager().getAppConfiguration(m_uiContext.getAppId()).getName(
UI.getCurrent().getLocale()));
}
m_breadCrumb.setEntries(entries);
} | [
"protected",
"void",
"updateBreadCrumb",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"breadCrumbEntries",
")",
"{",
"LinkedHashMap",
"<",
"String",
",",
"String",
">",
"entries",
"=",
"new",
"LinkedHashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
... | Updates the bread crumb navigation.<p>
@param breadCrumbEntries the bread crumb entries | [
"Updates",
"the",
"bread",
"crumb",
"navigation",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/A_CmsWorkplaceApp.java#L388-L405 |
Netflix/ribbon | ribbon-core/src/main/java/com/netflix/client/ssl/AbstractSslContextFactory.java | AbstractSslContextFactory.createKeyManagers | private KeyManager[] createKeyManagers() throws ClientSslSocketFactoryException {
final KeyManagerFactory factory;
try {
factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
factory.init(this.keyStore, this.keyStorePassword.toCharArray());
} catch (NoSuchAlgorithmException e) {
throw new ClientSslSocketFactoryException(
String.format("Failed to create the key store because the algorithm %s is not supported. ",
KeyManagerFactory.getDefaultAlgorithm()), e);
} catch (UnrecoverableKeyException e) {
throw new ClientSslSocketFactoryException("Unrecoverable Key Exception initializing key manager factory; this is probably fatal", e);
} catch (KeyStoreException e) {
throw new ClientSslSocketFactoryException("KeyStore exception initializing key manager factory; this is probably fatal", e);
}
KeyManager[] managers = factory.getKeyManagers();
LOGGER.debug("Key managers are initialized. Total {} managers. ", managers.length);
return managers;
} | java | private KeyManager[] createKeyManagers() throws ClientSslSocketFactoryException {
final KeyManagerFactory factory;
try {
factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
factory.init(this.keyStore, this.keyStorePassword.toCharArray());
} catch (NoSuchAlgorithmException e) {
throw new ClientSslSocketFactoryException(
String.format("Failed to create the key store because the algorithm %s is not supported. ",
KeyManagerFactory.getDefaultAlgorithm()), e);
} catch (UnrecoverableKeyException e) {
throw new ClientSslSocketFactoryException("Unrecoverable Key Exception initializing key manager factory; this is probably fatal", e);
} catch (KeyStoreException e) {
throw new ClientSslSocketFactoryException("KeyStore exception initializing key manager factory; this is probably fatal", e);
}
KeyManager[] managers = factory.getKeyManagers();
LOGGER.debug("Key managers are initialized. Total {} managers. ", managers.length);
return managers;
} | [
"private",
"KeyManager",
"[",
"]",
"createKeyManagers",
"(",
")",
"throws",
"ClientSslSocketFactoryException",
"{",
"final",
"KeyManagerFactory",
"factory",
";",
"try",
"{",
"factory",
"=",
"KeyManagerFactory",
".",
"getInstance",
"(",
"KeyManagerFactory",
".",
"getDe... | Creates the key managers to be used by the factory from the associated key store and password.
@return the newly created array of key managers
@throws ClientSslSocketFactoryException if an exception is detected in loading the key store | [
"Creates",
"the",
"key",
"managers",
"to",
"be",
"used",
"by",
"the",
"factory",
"from",
"the",
"associated",
"key",
"store",
"and",
"password",
"."
] | train | https://github.com/Netflix/ribbon/blob/d15cd7715b0bf2f64ae6ca98c5e4d184f178e261/ribbon-core/src/main/java/com/netflix/client/ssl/AbstractSslContextFactory.java#L124-L146 |
hellosign/hellosign-java-sdk | src/main/java/com/hellosign/sdk/resource/SignatureRequest.java | SignatureRequest.addSigner | public void addSigner(String email, String name, int order) throws HelloSignException {
try {
signers.add((order - 1), new Signer(email, name));
} catch (Exception ex) {
throw new HelloSignException(ex);
}
} | java | public void addSigner(String email, String name, int order) throws HelloSignException {
try {
signers.add((order - 1), new Signer(email, name));
} catch (Exception ex) {
throw new HelloSignException(ex);
}
} | [
"public",
"void",
"addSigner",
"(",
"String",
"email",
",",
"String",
"name",
",",
"int",
"order",
")",
"throws",
"HelloSignException",
"{",
"try",
"{",
"signers",
".",
"add",
"(",
"(",
"order",
"-",
"1",
")",
",",
"new",
"Signer",
"(",
"email",
",",
... | Adds the signer with the given order to the list of signers for this
request. NOTE: The order refers to the 1-base index, not 0-base. This is
to reflect the indexing used by the HelloSign API. This means that adding
an item at order 1 will place it in the 0th index of the list (it will be
the first item).
@param email String
@param name String
@param order int
@throws HelloSignException thrown if there is a problem adding the
signer. | [
"Adds",
"the",
"signer",
"with",
"the",
"given",
"order",
"to",
"the",
"list",
"of",
"signers",
"for",
"this",
"request",
".",
"NOTE",
":",
"The",
"order",
"refers",
"to",
"the",
"1",
"-",
"base",
"index",
"not",
"0",
"-",
"base",
".",
"This",
"is",
... | train | https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/resource/SignatureRequest.java#L193-L199 |
facebookarchive/hadoop-20 | src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/LocalStore.java | LocalStore.zipCompress | public static void zipCompress(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename + COMPRESSION_SUFFIX);
CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum));
out.setComment("Failmon records.");
BufferedReader in = new BufferedReader(new FileReader(filename));
out.putNextEntry(new ZipEntry(new File(filename).getName()));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.finish();
out.close();
} | java | public static void zipCompress(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename + COMPRESSION_SUFFIX);
CheckedOutputStream csum = new CheckedOutputStream(fos, new CRC32());
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(csum));
out.setComment("Failmon records.");
BufferedReader in = new BufferedReader(new FileReader(filename));
out.putNextEntry(new ZipEntry(new File(filename).getName()));
int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();
out.finish();
out.close();
} | [
"public",
"static",
"void",
"zipCompress",
"(",
"String",
"filename",
")",
"throws",
"IOException",
"{",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"filename",
"+",
"COMPRESSION_SUFFIX",
")",
";",
"CheckedOutputStream",
"csum",
"=",
"new",
"Ch... | Compress a text file using the ZIP compressing algorithm.
@param filename the path to the file to be compressed | [
"Compress",
"a",
"text",
"file",
"using",
"the",
"ZIP",
"compressing",
"algorithm",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/failmon/src/java/org/apache/hadoop/contrib/failmon/LocalStore.java#L206-L221 |
chrisjenx/Calligraphy | calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyUtils.java | CalligraphyUtils.pullFontPathFromTheme | static String pullFontPathFromTheme(Context context, int styleAttrId, int subStyleAttrId, int[] attributeId) {
if (styleAttrId == -1 || attributeId == null)
return null;
final Resources.Theme theme = context.getTheme();
final TypedValue value = new TypedValue();
theme.resolveAttribute(styleAttrId, value, true);
int subStyleResId = -1;
final TypedArray parentTypedArray = theme.obtainStyledAttributes(value.resourceId, new int[]{subStyleAttrId});
try {
subStyleResId = parentTypedArray.getResourceId(0, -1);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
parentTypedArray.recycle();
}
if (subStyleResId == -1) return null;
final TypedArray subTypedArray = context.obtainStyledAttributes(subStyleResId, attributeId);
if (subTypedArray != null) {
try {
return subTypedArray.getString(0);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
subTypedArray.recycle();
}
}
return null;
} | java | static String pullFontPathFromTheme(Context context, int styleAttrId, int subStyleAttrId, int[] attributeId) {
if (styleAttrId == -1 || attributeId == null)
return null;
final Resources.Theme theme = context.getTheme();
final TypedValue value = new TypedValue();
theme.resolveAttribute(styleAttrId, value, true);
int subStyleResId = -1;
final TypedArray parentTypedArray = theme.obtainStyledAttributes(value.resourceId, new int[]{subStyleAttrId});
try {
subStyleResId = parentTypedArray.getResourceId(0, -1);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
parentTypedArray.recycle();
}
if (subStyleResId == -1) return null;
final TypedArray subTypedArray = context.obtainStyledAttributes(subStyleResId, attributeId);
if (subTypedArray != null) {
try {
return subTypedArray.getString(0);
} catch (Exception ignore) {
// Failed for some reason.
return null;
} finally {
subTypedArray.recycle();
}
}
return null;
} | [
"static",
"String",
"pullFontPathFromTheme",
"(",
"Context",
"context",
",",
"int",
"styleAttrId",
",",
"int",
"subStyleAttrId",
",",
"int",
"[",
"]",
"attributeId",
")",
"{",
"if",
"(",
"styleAttrId",
"==",
"-",
"1",
"||",
"attributeId",
"==",
"null",
")",
... | Last but not least, try to pull the Font Path from the Theme, which is defined.
@param context Activity Context
@param styleAttrId Theme style id
@param subStyleAttrId the sub style from the theme to look up after the first style
@param attributeId if -1 returns null.
@return null if no theme or attribute defined. | [
"Last",
"but",
"not",
"least",
"try",
"to",
"pull",
"the",
"Font",
"Path",
"from",
"the",
"Theme",
"which",
"is",
"defined",
"."
] | train | https://github.com/chrisjenx/Calligraphy/blob/085e441954d787bd4ef31f245afe5f2f2a311ea5/calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyUtils.java#L281-L313 |
Red5/red5-server-common | src/main/java/org/red5/server/net/remoting/RemotingClient.java | RemotingClient.addHeader | public void addHeader(String name, boolean required, Object value) {
RemotingHeader header = new RemotingHeader(name, required, value);
headers.put(name, header);
} | java | public void addHeader(String name, boolean required, Object value) {
RemotingHeader header = new RemotingHeader(name, required, value);
headers.put(name, header);
} | [
"public",
"void",
"addHeader",
"(",
"String",
"name",
",",
"boolean",
"required",
",",
"Object",
"value",
")",
"{",
"RemotingHeader",
"header",
"=",
"new",
"RemotingHeader",
"(",
"name",
",",
"required",
",",
"value",
")",
";",
"headers",
".",
"put",
"(",
... | Send an additional header to the server.
@param name
Header name
@param required
Header required?
@param value
Header body | [
"Send",
"an",
"additional",
"header",
"to",
"the",
"server",
"."
] | train | https://github.com/Red5/red5-server-common/blob/39ae73710c25bda86d70b13ef37ae707962217b9/src/main/java/org/red5/server/net/remoting/RemotingClient.java#L290-L293 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.