repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.Bool | public JBBPDslBuilder Bool(final String name) {
final Item item = new Item(BinType.BOOL, name, this.byteOrder);
this.addItem(item);
return this;
} | java | public JBBPDslBuilder Bool(final String name) {
final Item item = new Item(BinType.BOOL, name, this.byteOrder);
this.addItem(item);
return this;
} | [
"public",
"JBBPDslBuilder",
"Bool",
"(",
"final",
"String",
"name",
")",
"{",
"final",
"Item",
"item",
"=",
"new",
"Item",
"(",
"BinType",
".",
"BOOL",
",",
"name",
",",
"this",
".",
"byteOrder",
")",
";",
"this",
".",
"addItem",
"(",
"item",
")",
";... | Add named boolean field.
@param name name of the field, can be null for anonymous one
@return the builder instance, must not be null | [
"Add",
"named",
"boolean",
"field",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L806-L810 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/core/QueryReferenceBroker.java | QueryReferenceBroker.getCollectionByQuery | public ManageableCollection getCollectionByQuery(Class collectionClass, Query query, boolean lazy) throws PersistenceBrokerException
{
ManageableCollection result;
try
{
// BRJ: return empty Collection for null query
if (query == null)
{
result = (ManageableCollection)collectionClass.newInstance();
}
else
{
if (lazy)
{
result = pb.getProxyFactory().createCollectionProxy(pb.getPBKey(), query, collectionClass);
}
else
{
result = getCollectionByQuery(collectionClass, query.getSearchClass(), query);
}
}
return result;
}
catch (Exception e)
{
if(e instanceof PersistenceBrokerException)
{
throw (PersistenceBrokerException) e;
}
else
{
throw new PersistenceBrokerException(e);
}
}
} | java | public ManageableCollection getCollectionByQuery(Class collectionClass, Query query, boolean lazy) throws PersistenceBrokerException
{
ManageableCollection result;
try
{
// BRJ: return empty Collection for null query
if (query == null)
{
result = (ManageableCollection)collectionClass.newInstance();
}
else
{
if (lazy)
{
result = pb.getProxyFactory().createCollectionProxy(pb.getPBKey(), query, collectionClass);
}
else
{
result = getCollectionByQuery(collectionClass, query.getSearchClass(), query);
}
}
return result;
}
catch (Exception e)
{
if(e instanceof PersistenceBrokerException)
{
throw (PersistenceBrokerException) e;
}
else
{
throw new PersistenceBrokerException(e);
}
}
} | [
"public",
"ManageableCollection",
"getCollectionByQuery",
"(",
"Class",
"collectionClass",
",",
"Query",
"query",
",",
"boolean",
"lazy",
")",
"throws",
"PersistenceBrokerException",
"{",
"ManageableCollection",
"result",
";",
"try",
"{",
"// BRJ: return empty Collection f... | retrieve a collection of type collectionClass matching the Query query
if lazy = true return a CollectionProxy
@param collectionClass
@param query
@param lazy
@return ManageableCollection
@throws PersistenceBrokerException | [
"retrieve",
"a",
"collection",
"of",
"type",
"collectionClass",
"matching",
"the",
"Query",
"query",
"if",
"lazy",
"=",
"true",
"return",
"a",
"CollectionProxy"
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/QueryReferenceBroker.java#L244-L279 |
Teddy-Zhu/SilentGo | framework/src/main/java/com/silentgo/core/route/support/paramdispatcher/PathParamDispatch.java | PathParamDispatch.dispatch | @Override
public void dispatch(ParameterResolveFactory parameterResolveFactory, ActionParam param, Route route, Object[] args) {
if (!route.isRegex()) return;
Matcher matcher = route.getMatcher();
String[] pathParameters = new String[matcher.groupCount()];
for (int i = 1, len = matcher.groupCount(); i <= len; i++) {
pathParameters[i - 1] = matcher.group(i);
}
Map<String, String> path = new HashMap<>();
route.getRegexRoute().getNames().forEach(name -> CollectionKit.MapAdd(path, name, matcher.group(name)));
param.getRequest().setPathNamedParameters(path);
param.getRequest().setPathParameters(pathParameters);
} | java | @Override
public void dispatch(ParameterResolveFactory parameterResolveFactory, ActionParam param, Route route, Object[] args) {
if (!route.isRegex()) return;
Matcher matcher = route.getMatcher();
String[] pathParameters = new String[matcher.groupCount()];
for (int i = 1, len = matcher.groupCount(); i <= len; i++) {
pathParameters[i - 1] = matcher.group(i);
}
Map<String, String> path = new HashMap<>();
route.getRegexRoute().getNames().forEach(name -> CollectionKit.MapAdd(path, name, matcher.group(name)));
param.getRequest().setPathNamedParameters(path);
param.getRequest().setPathParameters(pathParameters);
} | [
"@",
"Override",
"public",
"void",
"dispatch",
"(",
"ParameterResolveFactory",
"parameterResolveFactory",
",",
"ActionParam",
"param",
",",
"Route",
"route",
",",
"Object",
"[",
"]",
"args",
")",
"{",
"if",
"(",
"!",
"route",
".",
"isRegex",
"(",
")",
")",
... | prepare to resolve path parameters
@param parameterResolveFactory
@param param
@param route
@param args | [
"prepare",
"to",
"resolve",
"path",
"parameters"
] | train | https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/framework/src/main/java/com/silentgo/core/route/support/paramdispatcher/PathParamDispatch.java#L37-L50 |
liferay/com-liferay-commerce | commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplateUserSegmentRelPersistenceImpl.java | CommerceNotificationTemplateUserSegmentRelPersistenceImpl.findAll | @Override
public List<CommerceNotificationTemplateUserSegmentRel> findAll(int start,
int end) {
return findAll(start, end, null);
} | java | @Override
public List<CommerceNotificationTemplateUserSegmentRel> findAll(int start,
int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceNotificationTemplateUserSegmentRel",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce notification template user segment rels.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceNotificationTemplateUserSegmentRelModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce notification template user segment rels
@param end the upper bound of the range of commerce notification template user segment rels (not inclusive)
@return the range of commerce notification template user segment rels | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"notification",
"template",
"user",
"segment",
"rels",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplateUserSegmentRelPersistenceImpl.java#L2060-L2064 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/CharsetIssues.java | CharsetIssues.replaceNthArgWithCharsetString | private static String replaceNthArgWithCharsetString(String sig, int stackOffset) {
List<String> arguments = SignatureUtils.getParameterSignatures(sig);
StringBuilder sb = new StringBuilder("(");
int argumentIndexToReplace = (arguments.size() - stackOffset) - 1;
for (int i = 0; i < arguments.size(); i++) {
if (i == argumentIndexToReplace) {
sb.append(CHARSET_SIG);
} else {
sb.append(arguments.get(i));
}
}
sb.append(sig.substring(sig.lastIndexOf(')'), sig.length()));
return sb.toString();
} | java | private static String replaceNthArgWithCharsetString(String sig, int stackOffset) {
List<String> arguments = SignatureUtils.getParameterSignatures(sig);
StringBuilder sb = new StringBuilder("(");
int argumentIndexToReplace = (arguments.size() - stackOffset) - 1;
for (int i = 0; i < arguments.size(); i++) {
if (i == argumentIndexToReplace) {
sb.append(CHARSET_SIG);
} else {
sb.append(arguments.get(i));
}
}
sb.append(sig.substring(sig.lastIndexOf(')'), sig.length()));
return sb.toString();
} | [
"private",
"static",
"String",
"replaceNthArgWithCharsetString",
"(",
"String",
"sig",
",",
"int",
"stackOffset",
")",
"{",
"List",
"<",
"String",
">",
"arguments",
"=",
"SignatureUtils",
".",
"getParameterSignatures",
"(",
"sig",
")",
";",
"StringBuilder",
"sb",
... | rebuilds a signature replacing a String argument at a specified spot, with a Charset parameter.
@param sig
the signature to replace
@param stackOffset
the offset of the parameter to replace
@return a new signature with a Charset parameter | [
"rebuilds",
"a",
"signature",
"replacing",
"a",
"String",
"argument",
"at",
"a",
"specified",
"spot",
"with",
"a",
"Charset",
"parameter",
"."
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/CharsetIssues.java#L291-L308 |
UrielCh/ovh-java-sdk | ovh-java-sdk-allDom/src/main/java/net/minidev/ovh/api/ApiOvhAllDom.java | ApiOvhAllDom.serviceName_domain_domain_GET | public OvhAllDomDomain serviceName_domain_domain_GET(String serviceName, String domain) throws IOException {
String qPath = "/allDom/{serviceName}/domain/{domain}";
StringBuilder sb = path(qPath, serviceName, domain);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAllDomDomain.class);
} | java | public OvhAllDomDomain serviceName_domain_domain_GET(String serviceName, String domain) throws IOException {
String qPath = "/allDom/{serviceName}/domain/{domain}";
StringBuilder sb = path(qPath, serviceName, domain);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhAllDomDomain.class);
} | [
"public",
"OvhAllDomDomain",
"serviceName_domain_domain_GET",
"(",
"String",
"serviceName",
",",
"String",
"domain",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/allDom/{serviceName}/domain/{domain}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qP... | Get this object properties
REST: GET /allDom/{serviceName}/domain/{domain}
@param serviceName [required] The internal name of your allDom
@param domain [required] Domain name | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-allDom/src/main/java/net/minidev/ovh/api/ApiOvhAllDom.java#L71-L76 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheUnitImpl.java | CacheUnitImpl.removeExternalCacheAdapter | public void removeExternalCacheAdapter(String groupId, String address) throws DynamicCacheServiceNotStarted {
if (servletCacheUnit == null) {
throw new DynamicCacheServiceNotStarted("Servlet cache service has not been started.");
}
servletCacheUnit.removeExternalCacheAdapter(groupId, address);
} | java | public void removeExternalCacheAdapter(String groupId, String address) throws DynamicCacheServiceNotStarted {
if (servletCacheUnit == null) {
throw new DynamicCacheServiceNotStarted("Servlet cache service has not been started.");
}
servletCacheUnit.removeExternalCacheAdapter(groupId, address);
} | [
"public",
"void",
"removeExternalCacheAdapter",
"(",
"String",
"groupId",
",",
"String",
"address",
")",
"throws",
"DynamicCacheServiceNotStarted",
"{",
"if",
"(",
"servletCacheUnit",
"==",
"null",
")",
"{",
"throw",
"new",
"DynamicCacheServiceNotStarted",
"(",
"\"Ser... | This implements the method in the CacheUnit interface.
This is delegated to the ExternalCacheServices.
It calls ServletCacheUnit to perform this operation.
@param groupId The external cache group id.
@param address The IP address of the target external cache. | [
"This",
"implements",
"the",
"method",
"in",
"the",
"CacheUnit",
"interface",
".",
"This",
"is",
"delegated",
"to",
"the",
"ExternalCacheServices",
".",
"It",
"calls",
"ServletCacheUnit",
"to",
"perform",
"this",
"operation",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/CacheUnitImpl.java#L231-L236 |
grpc/grpc-java | netty/src/main/java/io/grpc/netty/GrpcSslContexts.java | GrpcSslContexts.configure | @CanIgnoreReturnValue
public static SslContextBuilder configure(SslContextBuilder builder, Provider jdkProvider) {
ApplicationProtocolConfig apc;
if (SUN_PROVIDER_NAME.equals(jdkProvider.getName())) {
// Jetty ALPN/NPN only supports one of NPN or ALPN
if (JettyTlsUtil.isJettyAlpnConfigured()) {
apc = ALPN;
} else if (JettyTlsUtil.isJettyNpnConfigured()) {
apc = NPN;
} else if (JettyTlsUtil.isJava9AlpnAvailable()) {
apc = ALPN;
} else {
throw new IllegalArgumentException(
SUN_PROVIDER_NAME + " selected, but Jetty NPN/ALPN unavailable");
}
} else if (isConscrypt(jdkProvider)) {
apc = ALPN;
} else {
throw new IllegalArgumentException("Unknown provider; can't configure: " + jdkProvider);
}
return builder
.sslProvider(SslProvider.JDK)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(apc)
.sslContextProvider(jdkProvider);
} | java | @CanIgnoreReturnValue
public static SslContextBuilder configure(SslContextBuilder builder, Provider jdkProvider) {
ApplicationProtocolConfig apc;
if (SUN_PROVIDER_NAME.equals(jdkProvider.getName())) {
// Jetty ALPN/NPN only supports one of NPN or ALPN
if (JettyTlsUtil.isJettyAlpnConfigured()) {
apc = ALPN;
} else if (JettyTlsUtil.isJettyNpnConfigured()) {
apc = NPN;
} else if (JettyTlsUtil.isJava9AlpnAvailable()) {
apc = ALPN;
} else {
throw new IllegalArgumentException(
SUN_PROVIDER_NAME + " selected, but Jetty NPN/ALPN unavailable");
}
} else if (isConscrypt(jdkProvider)) {
apc = ALPN;
} else {
throw new IllegalArgumentException("Unknown provider; can't configure: " + jdkProvider);
}
return builder
.sslProvider(SslProvider.JDK)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(apc)
.sslContextProvider(jdkProvider);
} | [
"@",
"CanIgnoreReturnValue",
"public",
"static",
"SslContextBuilder",
"configure",
"(",
"SslContextBuilder",
"builder",
",",
"Provider",
"jdkProvider",
")",
"{",
"ApplicationProtocolConfig",
"apc",
";",
"if",
"(",
"SUN_PROVIDER_NAME",
".",
"equals",
"(",
"jdkProvider",
... | Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if
an application requires particular settings it should override the options set here. | [
"Set",
"ciphers",
"and",
"APN",
"appropriate",
"for",
"gRPC",
".",
"Precisely",
"what",
"is",
"set",
"is",
"permitted",
"to",
"change",
"so",
"if",
"an",
"application",
"requires",
"particular",
"settings",
"it",
"should",
"override",
"the",
"options",
"set",
... | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/netty/src/main/java/io/grpc/netty/GrpcSslContexts.java#L213-L238 |
keenon/loglinear | src/main/java/com/github/keenon/loglinear/model/ConcatVector.java | ConcatVector.setSparseComponent | public void setSparseComponent(int component, int[] indices, double[] values) {
if (component >= pointers.length) {
increaseSizeTo(component + 1);
}
assert (indices.length == values.length);
if (indices.length == 0) {
pointers[component] = new double[2];
sparse[component] = true;
copyOnWrite[component] = false;
} else {
double[] sparseInfo = new double[indices.length * 2];
for (int i = 0; i < indices.length; i++) {
sparseInfo[i * 2] = indices[i];
sparseInfo[(i * 2) + 1] = values[i];
}
pointers[component] = sparseInfo;
sparse[component] = true;
copyOnWrite[component] = false;
}
} | java | public void setSparseComponent(int component, int[] indices, double[] values) {
if (component >= pointers.length) {
increaseSizeTo(component + 1);
}
assert (indices.length == values.length);
if (indices.length == 0) {
pointers[component] = new double[2];
sparse[component] = true;
copyOnWrite[component] = false;
} else {
double[] sparseInfo = new double[indices.length * 2];
for (int i = 0; i < indices.length; i++) {
sparseInfo[i * 2] = indices[i];
sparseInfo[(i * 2) + 1] = values[i];
}
pointers[component] = sparseInfo;
sparse[component] = true;
copyOnWrite[component] = false;
}
} | [
"public",
"void",
"setSparseComponent",
"(",
"int",
"component",
",",
"int",
"[",
"]",
"indices",
",",
"double",
"[",
"]",
"values",
")",
"{",
"if",
"(",
"component",
">=",
"pointers",
".",
"length",
")",
"{",
"increaseSizeTo",
"(",
"component",
"+",
"1"... | Sets a component to a set of sparse indices, each with a value.
@param component the index of the component to set
@param indices the indices of the vector to give values to
@param values their values | [
"Sets",
"a",
"component",
"to",
"a",
"set",
"of",
"sparse",
"indices",
"each",
"with",
"a",
"value",
"."
] | train | https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/model/ConcatVector.java#L122-L143 |
PureSolTechnologies/parsers | parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java | PackratParser.processTerminal | private MemoEntry processTerminal(ParseTreeNode node, Terminal terminal, int position, int line)
throws TreeException {
printMessage("applyTerminal: " + terminal, position, line);
TokenDefinitionSet tokenDefinitions = grammar.getTokenDefinitions();
TokenDefinition tokenDefinition = tokenDefinitions.getDefinition(terminal.getName());
MemoEntry result = processTokenDefinition(node, tokenDefinition, position, line);
if (result == null) {
throw new RuntimeException("There should be a result not null!");
}
printMessage("applied Terminal '" + terminal + "' (" + result.getAnswer() + ").", position, line);
return result;
} | java | private MemoEntry processTerminal(ParseTreeNode node, Terminal terminal, int position, int line)
throws TreeException {
printMessage("applyTerminal: " + terminal, position, line);
TokenDefinitionSet tokenDefinitions = grammar.getTokenDefinitions();
TokenDefinition tokenDefinition = tokenDefinitions.getDefinition(terminal.getName());
MemoEntry result = processTokenDefinition(node, tokenDefinition, position, line);
if (result == null) {
throw new RuntimeException("There should be a result not null!");
}
printMessage("applied Terminal '" + terminal + "' (" + result.getAnswer() + ").", position, line);
return result;
} | [
"private",
"MemoEntry",
"processTerminal",
"(",
"ParseTreeNode",
"node",
",",
"Terminal",
"terminal",
",",
"int",
"position",
",",
"int",
"line",
")",
"throws",
"TreeException",
"{",
"printMessage",
"(",
"\"applyTerminal: \"",
"+",
"terminal",
",",
"position",
","... | This method processes a single terminal. This method uses
processTokenDefinition to do this. The information to be put into that method
is extracted and prepared here.
@param node
@param terminal
@param position
@return
@throws TreeException | [
"This",
"method",
"processes",
"a",
"single",
"terminal",
".",
"This",
"method",
"uses",
"processTokenDefinition",
"to",
"do",
"this",
".",
"The",
"information",
"to",
"be",
"put",
"into",
"that",
"method",
"is",
"extracted",
"and",
"prepared",
"here",
"."
] | train | https://github.com/PureSolTechnologies/parsers/blob/61077223b90d3768ff9445ae13036343c98b63cd/parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java#L631-L642 |
atomix/catalyst | serializer/src/main/java/io/atomix/catalyst/serializer/Serializer.java | Serializer.writeObject | public <T> BufferOutput<?> writeObject(T object, BufferOutput<?> buffer) {
if (object == null) {
return buffer.writeByte(Identifier.NULL.code());
}
Class<?> type = object.getClass();
// get the enclosing class from a cache.
Class<?> enclosingClass = enclosingClasses.computeIfAbsent(type, clazz -> Optional.ofNullable(clazz.getEnclosingClass())).orElse(null);
// Enums that implement interfaces or methods are generated as inner classes. For this reason,
// we need to get the enclosing class if it's an enum.
if (enclosingClass != null && enclosingClass.isEnum())
type = enclosingClass;
// Look up the serializer for the given object type.
TypeSerializer serializer = getSerializer(type);
// If no serializer was found, throw a serialization exception.
if (serializer == null) {
throw new SerializationException("cannot serialize unregistered type: " + type);
}
// Cache the serializable type ID if necessary.
if (!ids.containsKey(type)) {
ids.put(type, registry.id(type));
}
// Lookup the serializable type ID for the type.
int typeId = registry.id(type);
if (typeId == 0) {
return writeByClass(type, object, buffer, serializer);
}
return writeById(typeId, object, buffer, serializer);
} | java | public <T> BufferOutput<?> writeObject(T object, BufferOutput<?> buffer) {
if (object == null) {
return buffer.writeByte(Identifier.NULL.code());
}
Class<?> type = object.getClass();
// get the enclosing class from a cache.
Class<?> enclosingClass = enclosingClasses.computeIfAbsent(type, clazz -> Optional.ofNullable(clazz.getEnclosingClass())).orElse(null);
// Enums that implement interfaces or methods are generated as inner classes. For this reason,
// we need to get the enclosing class if it's an enum.
if (enclosingClass != null && enclosingClass.isEnum())
type = enclosingClass;
// Look up the serializer for the given object type.
TypeSerializer serializer = getSerializer(type);
// If no serializer was found, throw a serialization exception.
if (serializer == null) {
throw new SerializationException("cannot serialize unregistered type: " + type);
}
// Cache the serializable type ID if necessary.
if (!ids.containsKey(type)) {
ids.put(type, registry.id(type));
}
// Lookup the serializable type ID for the type.
int typeId = registry.id(type);
if (typeId == 0) {
return writeByClass(type, object, buffer, serializer);
}
return writeById(typeId, object, buffer, serializer);
} | [
"public",
"<",
"T",
">",
"BufferOutput",
"<",
"?",
">",
"writeObject",
"(",
"T",
"object",
",",
"BufferOutput",
"<",
"?",
">",
"buffer",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"return",
"buffer",
".",
"writeByte",
"(",
"Identifier",
"... | Writes an object to the given buffer.
<p>
Serialized bytes will be written to the given {@link Buffer} starting at its current
{@link Buffer#position()}. If the bytes {@link Buffer#remaining()} in
the buffer are not great enough to hold the serialized bytes, the buffer will be automatically expanded up to the
buffer's {@link Buffer#maxCapacity()}.
<p>
The given object must have a {@link Serializer#register(Class) registered} serializer or implement {@link java.io.Serializable}.
If a serializable type ID was provided during registration, the type ID will be written to the given
{@link Buffer} in lieu of the class name. Types with no associated type ID will be written
to the buffer with a full class name for reference during serialization.
<p>
Types that implement {@link CatalystSerializable} will be serialized via
{@link CatalystSerializable#writeObject(BufferOutput, Serializer)} unless a
{@link TypeSerializer} was explicitly registered for the type.
<p>
Types that implement {@link java.io.Serializable} will be serialized using Java's {@link java.io.ObjectOutputStream}.
Types that implement {@link java.io.Externalizable} will be serialized via that interface's methods unless a custom
{@link TypeSerializer} has been registered for the type. {@link java.io.Externalizable} types can,
however, still take advantage of faster serialization of type IDs.
@param object The object to write.
@param buffer The buffer to which to write the object.
@param <T> The object type.
@return The serialized object.
@throws SerializationException If no serializer is registered for the object.
@see Serializer#writeObject(Object) | [
"Writes",
"an",
"object",
"to",
"the",
"given",
"buffer",
".",
"<p",
">",
"Serialized",
"bytes",
"will",
"be",
"written",
"to",
"the",
"given",
"{",
"@link",
"Buffer",
"}",
"starting",
"at",
"its",
"current",
"{",
"@link",
"Buffer#position",
"()",
"}",
"... | train | https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/Serializer.java#L845-L878 |
ocelotds/ocelot | ocelot-web/src/main/java/org/ocelotds/topic/TopicsMessagesBroadcaster.java | TopicsMessagesBroadcaster.sendMessageToTopicForSessions | int sendMessageToTopicForSessions(Collection<Session> sessions, MessageToClient mtc, Object payload) {
int sended = 0;
JsTopicMessageController msgControl = messageControllerManager.getJsTopicMessageController(mtc.getId());
Collection<Session> sessionsClosed = new ArrayList<>();
for (Session session : sessions) {
try {
sended += checkAndSendMtcToSession(session, msgControl, mtc, payload);
} catch (SessionException se) {
sessionsClosed.add(se.getSession());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Send message to '{}' topic {} client(s) : {}", new Object[]{mtc.getId(), sessions.size() - sessionsClosed.size(), mtc});
}
topicManager.removeSessionsToTopic(sessionsClosed);
return sended;
} | java | int sendMessageToTopicForSessions(Collection<Session> sessions, MessageToClient mtc, Object payload) {
int sended = 0;
JsTopicMessageController msgControl = messageControllerManager.getJsTopicMessageController(mtc.getId());
Collection<Session> sessionsClosed = new ArrayList<>();
for (Session session : sessions) {
try {
sended += checkAndSendMtcToSession(session, msgControl, mtc, payload);
} catch (SessionException se) {
sessionsClosed.add(se.getSession());
}
}
if (logger.isDebugEnabled()) {
logger.debug("Send message to '{}' topic {} client(s) : {}", new Object[]{mtc.getId(), sessions.size() - sessionsClosed.size(), mtc});
}
topicManager.removeSessionsToTopic(sessionsClosed);
return sended;
} | [
"int",
"sendMessageToTopicForSessions",
"(",
"Collection",
"<",
"Session",
">",
"sessions",
",",
"MessageToClient",
"mtc",
",",
"Object",
"payload",
")",
"{",
"int",
"sended",
"=",
"0",
";",
"JsTopicMessageController",
"msgControl",
"=",
"messageControllerManager",
... | send message to sessions
apply msgControl to topic
@param sessions
@param mtc
@param payload
@return | [
"send",
"message",
"to",
"sessions",
"apply",
"msgControl",
"to",
"topic"
] | train | https://github.com/ocelotds/ocelot/blob/5f0ac37afd8fa4dc9f7234a2aac8abbb522128e7/ocelot-web/src/main/java/org/ocelotds/topic/TopicsMessagesBroadcaster.java#L86-L102 |
arquillian/arquillian-algeron | common/configuration/src/main/java/org/arquillian/algeron/configuration/Reflection.java | Reflection.newInstance | public static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments) {
if (implClass == null) {
throw new IllegalArgumentException("ImplClass must be specified");
}
if (argumentTypes == null) {
throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
}
if (arguments == null) {
throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
}
final T obj;
try {
final Constructor<T> constructor = getConstructor(implClass, argumentTypes);
if (!constructor.isAccessible()) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
constructor.setAccessible(true);
return null;
}
});
}
obj = constructor.newInstance(arguments);
} catch (Exception e) {
throw new RuntimeException("Could not create new instance of " + implClass, e);
}
return obj;
} | java | public static <T> T newInstance(final Class<T> implClass, final Class<?>[] argumentTypes, final Object[] arguments) {
if (implClass == null) {
throw new IllegalArgumentException("ImplClass must be specified");
}
if (argumentTypes == null) {
throw new IllegalArgumentException("ArgumentTypes must be specified. Use empty array if no arguments");
}
if (arguments == null) {
throw new IllegalArgumentException("Arguments must be specified. Use empty array if no arguments");
}
final T obj;
try {
final Constructor<T> constructor = getConstructor(implClass, argumentTypes);
if (!constructor.isAccessible()) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
constructor.setAccessible(true);
return null;
}
});
}
obj = constructor.newInstance(arguments);
} catch (Exception e) {
throw new RuntimeException("Could not create new instance of " + implClass, e);
}
return obj;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"newInstance",
"(",
"final",
"Class",
"<",
"T",
">",
"implClass",
",",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"argumentTypes",
",",
"final",
"Object",
"[",
"]",
"arguments",
")",
"{",
"if",
"(",
"implClass"... | Create a new instance by finding a constructor that matches the argumentTypes signature
using the arguments for instantiation.
@param implClass
Full classname of class to create
@param argumentTypes
The constructor argument types
@param arguments
The constructor arguments
@return a new instance
@throws IllegalArgumentException
if className, argumentTypes, or arguments are null
@throws RuntimeException
if any exceptions during creation
@author <a href="mailto:aslak@conduct.no">Aslak Knutsen</a>
@author <a href="mailto:andrew.rubinger@jboss.org">ALR</a> | [
"Create",
"a",
"new",
"instance",
"by",
"finding",
"a",
"constructor",
"that",
"matches",
"the",
"argumentTypes",
"signature",
"using",
"the",
"arguments",
"for",
"instantiation",
"."
] | train | https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/configuration/src/main/java/org/arquillian/algeron/configuration/Reflection.java#L47-L74 |
gallandarakhneorg/afc | core/maths/mathgeom/tobeincluded/src/d3/continuous/Sphere3d.java | Sphere3d.setProperties | public void setProperties(DoubleProperty x, DoubleProperty y, DoubleProperty z, DoubleProperty radius1) {
this.cxProperty = x;
this.cyProperty = y;
this.czProperty = z;
this.radiusProperty = radius1;
this.radiusProperty.set(Math.abs(this.radiusProperty.get()));
} | java | public void setProperties(DoubleProperty x, DoubleProperty y, DoubleProperty z, DoubleProperty radius1) {
this.cxProperty = x;
this.cyProperty = y;
this.czProperty = z;
this.radiusProperty = radius1;
this.radiusProperty.set(Math.abs(this.radiusProperty.get()));
} | [
"public",
"void",
"setProperties",
"(",
"DoubleProperty",
"x",
",",
"DoubleProperty",
"y",
",",
"DoubleProperty",
"z",
",",
"DoubleProperty",
"radius1",
")",
"{",
"this",
".",
"cxProperty",
"=",
"x",
";",
"this",
".",
"cyProperty",
"=",
"y",
";",
"this",
"... | Change the frame of the sphere.
@param x
@param y
@param z
@param radius1 | [
"Change",
"the",
"frame",
"of",
"the",
"sphere",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/maths/mathgeom/tobeincluded/src/d3/continuous/Sphere3d.java#L119-L125 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java | SwaptionDataLattice.convertTenor | private double convertTenor(int maturityInMonths, int tenorInMonths) {
Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths);
return schedule.getPayment(schedule.getNumberOfPeriods()-1);
} | java | private double convertTenor(int maturityInMonths, int tenorInMonths) {
Schedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, tenorInMonths);
return schedule.getPayment(schedule.getNumberOfPeriods()-1);
} | [
"private",
"double",
"convertTenor",
"(",
"int",
"maturityInMonths",
",",
"int",
"tenorInMonths",
")",
"{",
"Schedule",
"schedule",
"=",
"fixMetaSchedule",
".",
"generateSchedule",
"(",
"referenceDate",
",",
"maturityInMonths",
",",
"tenorInMonths",
")",
";",
"retur... | Convert tenor given as offset in months to year fraction.
@param maturityInMonths The maturity as offset in months.
@param tenorInMonths The tenor as offset in months.
@return THe tenor as year fraction. | [
"Convert",
"tenor",
"given",
"as",
"offset",
"in",
"months",
"to",
"year",
"fraction",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata/model/volatilities/SwaptionDataLattice.java#L534-L537 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/Record.java | Record.getRate | public Rate getRate(int field) throws MPXJException
{
Rate result;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
String rate = m_fields[field];
int index = rate.indexOf('/');
double amount;
TimeUnit units;
if (index == -1)
{
amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();
units = TimeUnit.HOURS;
}
else
{
amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();
units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);
}
result = new Rate(amount, units);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse rate", ex);
}
}
else
{
result = null;
}
return (result);
} | java | public Rate getRate(int field) throws MPXJException
{
Rate result;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
String rate = m_fields[field];
int index = rate.indexOf('/');
double amount;
TimeUnit units;
if (index == -1)
{
amount = m_formats.getCurrencyFormat().parse(rate).doubleValue();
units = TimeUnit.HOURS;
}
else
{
amount = m_formats.getCurrencyFormat().parse(rate.substring(0, index)).doubleValue();
units = TimeUnitUtility.getInstance(rate.substring(index + 1), m_locale);
}
result = new Rate(amount, units);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse rate", ex);
}
}
else
{
result = null;
}
return (result);
} | [
"public",
"Rate",
"getRate",
"(",
"int",
"field",
")",
"throws",
"MPXJException",
"{",
"Rate",
"result",
";",
"if",
"(",
"(",
"field",
"<",
"m_fields",
".",
"length",
")",
"&&",
"(",
"m_fields",
"[",
"field",
"]",
".",
"length",
"(",
")",
"!=",
"0",
... | Accessor method used to retrieve an Rate object representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field
@throws MPXJException normally thrown when parsing fails | [
"Accessor",
"method",
"used",
"to",
"retrieve",
"an",
"Rate",
"object",
"representing",
"the",
"contents",
"of",
"an",
"individual",
"field",
".",
"If",
"the",
"field",
"does",
"not",
"exist",
"in",
"the",
"record",
"null",
"is",
"returned",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/Record.java#L369-L407 |
boncey/Flickr4Java | src/main/java/com/flickr4java/flickr/groups/pools/PoolsInterface.java | PoolsInterface.getPhotos | public PhotoList<Photo> getPhotos(String groupId, String[] tags, Set<String> extras, int perPage, int page) throws FlickrException {
return getPhotos(groupId, null, tags, extras, perPage, page);
} | java | public PhotoList<Photo> getPhotos(String groupId, String[] tags, Set<String> extras, int perPage, int page) throws FlickrException {
return getPhotos(groupId, null, tags, extras, perPage, page);
} | [
"public",
"PhotoList",
"<",
"Photo",
">",
"getPhotos",
"(",
"String",
"groupId",
",",
"String",
"[",
"]",
"tags",
",",
"Set",
"<",
"String",
">",
"extras",
",",
"int",
"perPage",
",",
"int",
"page",
")",
"throws",
"FlickrException",
"{",
"return",
"getPh... | Convenience/Compatibility method.
This method does not require authentication.
@see com.flickr4java.flickr.photos.Extras
@param groupId
The group ID
@param tags
The optional tags (may be null)
@param extras
Set of extra-attributes to include (may be null)
@param perPage
The number of photos per page (0 to ignore)
@param page
The page offset (0 to ignore)
@return A Collection of Photo objects
@throws FlickrException | [
"Convenience",
"/",
"Compatibility",
"method",
"."
] | train | https://github.com/boncey/Flickr4Java/blob/f66987ba0e360e5fb7730efbbb8c51f3d978fc25/src/main/java/com/flickr4java/flickr/groups/pools/PoolsInterface.java#L247-L249 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ArrayList.java | ArrayList.subList | public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
} | java | public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
} | [
"public",
"List",
"<",
"E",
">",
"subList",
"(",
"int",
"fromIndex",
",",
"int",
"toIndex",
")",
"{",
"subListRangeCheck",
"(",
"fromIndex",
",",
"toIndex",
",",
"size",
")",
";",
"return",
"new",
"SubList",
"(",
"this",
",",
"0",
",",
"fromIndex",
","... | Returns a view of the portion of this list between the specified
{@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
{@code fromIndex} and {@code toIndex} are equal, the returned list is
empty.) The returned list is backed by this list, so non-structural
changes in the returned list are reflected in this list, and vice-versa.
The returned list supports all of the optional list operations.
<p>This method eliminates the need for explicit range operations (of
the sort that commonly exist for arrays). Any operation that expects
a list can be used as a range operation by passing a subList view
instead of a whole list. For example, the following idiom
removes a range of elements from a list:
<pre>
list.subList(from, to).clear();
</pre>
Similar idioms may be constructed for {@link #indexOf(Object)} and
{@link #lastIndexOf(Object)}, and all of the algorithms in the
{@link Collections} class can be applied to a subList.
<p>The semantics of the list returned by this method become undefined if
the backing list (i.e., this list) is <i>structurally modified</i> in
any way other than via the returned list. (Structural modifications are
those that change the size of this list, or otherwise perturb it in such
a fashion that iterations in progress may yield incorrect results.)
@throws IndexOutOfBoundsException {@inheritDoc}
@throws IllegalArgumentException {@inheritDoc} | [
"Returns",
"a",
"view",
"of",
"the",
"portion",
"of",
"this",
"list",
"between",
"the",
"specified",
"{",
"@code",
"fromIndex",
"}",
"inclusive",
"and",
"{",
"@code",
"toIndex",
"}",
"exclusive",
".",
"(",
"If",
"{",
"@code",
"fromIndex",
"}",
"and",
"{"... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/ArrayList.java#L1005-L1008 |
graknlabs/grakn | server/src/graql/util/Partition.java | Partition.sameComponent | public boolean sameComponent(V a, V b) {
return componentOf(a).equals(componentOf(b));
} | java | public boolean sameComponent(V a, V b) {
return componentOf(a).equals(componentOf(b));
} | [
"public",
"boolean",
"sameComponent",
"(",
"V",
"a",
",",
"V",
"b",
")",
"{",
"return",
"componentOf",
"(",
"a",
")",
".",
"equals",
"(",
"componentOf",
"(",
"b",
")",
")",
";",
"}"
] | Determines whether the two items are in the same component or not | [
"Determines",
"whether",
"the",
"two",
"items",
"are",
"in",
"the",
"same",
"component",
"or",
"not"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/util/Partition.java#L95-L97 |
snowflakedb/snowflake-jdbc | src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageObjectSummary.java | StorageObjectSummary.createFromAzureListBlobItem | public static StorageObjectSummary createFromAzureListBlobItem(ListBlobItem listBlobItem)
throws StorageProviderException
{
String location, key, md5;
long size;
// Retrieve the BLOB properties that we need for the Summary
// Azure Storage stores metadata inside each BLOB, therefore the listBlobItem
// will point us to the underlying BLOB and will get the properties from it
// During the process the Storage Client could fail, hence we need to wrap the
// get calls in try/catch and handle possible exceptions
try
{
location = listBlobItem.getContainer().getName();
CloudBlob cloudBlob = (CloudBlob) listBlobItem;
key = cloudBlob.getName();
BlobProperties blobProperties = cloudBlob.getProperties();
// the content md5 property is not always the actual md5 of the file. But for here, it's only
// used for skipping file on PUT command, hense is ok.
md5 = convertBase64ToHex(blobProperties.getContentMD5());
size = blobProperties.getLength();
}
catch (URISyntaxException | StorageException ex)
{
// This should only happen if somehow we got here with and invalid URI (it should never happen)
// ...or there is a Storage service error. Unlike S3, Azure fetches metadata from the BLOB itself,
// and its a lazy operation
throw new StorageProviderException(ex);
}
return new StorageObjectSummary(location, key, md5, size);
} | java | public static StorageObjectSummary createFromAzureListBlobItem(ListBlobItem listBlobItem)
throws StorageProviderException
{
String location, key, md5;
long size;
// Retrieve the BLOB properties that we need for the Summary
// Azure Storage stores metadata inside each BLOB, therefore the listBlobItem
// will point us to the underlying BLOB and will get the properties from it
// During the process the Storage Client could fail, hence we need to wrap the
// get calls in try/catch and handle possible exceptions
try
{
location = listBlobItem.getContainer().getName();
CloudBlob cloudBlob = (CloudBlob) listBlobItem;
key = cloudBlob.getName();
BlobProperties blobProperties = cloudBlob.getProperties();
// the content md5 property is not always the actual md5 of the file. But for here, it's only
// used for skipping file on PUT command, hense is ok.
md5 = convertBase64ToHex(blobProperties.getContentMD5());
size = blobProperties.getLength();
}
catch (URISyntaxException | StorageException ex)
{
// This should only happen if somehow we got here with and invalid URI (it should never happen)
// ...or there is a Storage service error. Unlike S3, Azure fetches metadata from the BLOB itself,
// and its a lazy operation
throw new StorageProviderException(ex);
}
return new StorageObjectSummary(location, key, md5, size);
} | [
"public",
"static",
"StorageObjectSummary",
"createFromAzureListBlobItem",
"(",
"ListBlobItem",
"listBlobItem",
")",
"throws",
"StorageProviderException",
"{",
"String",
"location",
",",
"key",
",",
"md5",
";",
"long",
"size",
";",
"// Retrieve the BLOB properties that we n... | Contructs a StorageObjectSummary object from Azure BLOB properties
Using factory methods to create these objects since Azure can throw,
while retrieving the BLOB properties
@param listBlobItem an Azure ListBlobItem object
@return the ObjectSummary object created | [
"Contructs",
"a",
"StorageObjectSummary",
"object",
"from",
"Azure",
"BLOB",
"properties",
"Using",
"factory",
"methods",
"to",
"create",
"these",
"objects",
"since",
"Azure",
"can",
"throw",
"while",
"retrieving",
"the",
"BLOB",
"properties"
] | train | https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/jdbc/cloud/storage/StorageObjectSummary.java#L69-L102 |
EdwardRaff/JSAT | JSAT/src/jsat/linear/Matrix.java | Matrix.isSymmetric | public static boolean isSymmetric(Matrix A, double eps)
{
if(!A.isSquare())
return false;
for(int i = 0; i < A.rows(); i++)
for(int j = i+1; j < A.cols(); j++)
if( Math.abs(A.get(i, j)-A.get(j, i)) > eps)
return false;
return true;
} | java | public static boolean isSymmetric(Matrix A, double eps)
{
if(!A.isSquare())
return false;
for(int i = 0; i < A.rows(); i++)
for(int j = i+1; j < A.cols(); j++)
if( Math.abs(A.get(i, j)-A.get(j, i)) > eps)
return false;
return true;
} | [
"public",
"static",
"boolean",
"isSymmetric",
"(",
"Matrix",
"A",
",",
"double",
"eps",
")",
"{",
"if",
"(",
"!",
"A",
".",
"isSquare",
"(",
")",
")",
"return",
"false",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"A",
".",
"rows",
"(... | Checks to see if the given input is approximately symmetric. Rounding
errors may cause the computation of a matrix to come out non symmetric,
where |a[i,h] - a[j, i]| < eps. Despite these errors, it may be
preferred to treat the matrix as perfectly symmetric regardless.
@param A the input matrix
@param eps the maximum tolerable difference between two entries
@return {@code true} if the matrix is approximately symmetric | [
"Checks",
"to",
"see",
"if",
"the",
"given",
"input",
"is",
"approximately",
"symmetric",
".",
"Rounding",
"errors",
"may",
"cause",
"the",
"computation",
"of",
"a",
"matrix",
"to",
"come",
"out",
"non",
"symmetric",
"where",
"|a",
"[",
"i",
"h",
"]",
"-... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/Matrix.java#L1074-L1083 |
jenkinsci/artifactory-plugin | src/main/java/org/jfrog/hudson/util/CredentialManager.java | CredentialManager.getPreferredResolver | public static CredentialsConfig getPreferredResolver(ResolverOverrider resolverOverrider, ArtifactoryServer server) {
if (resolverOverrider != null && resolverOverrider.isOverridingDefaultResolver()) {
CredentialsConfig resolverCredentialsConfig = resolverOverrider.getResolverCredentialsConfig();
if (resolverCredentialsConfig != null) {
return resolverCredentialsConfig;
}
}
return server.getResolvingCredentialsConfig();
} | java | public static CredentialsConfig getPreferredResolver(ResolverOverrider resolverOverrider, ArtifactoryServer server) {
if (resolverOverrider != null && resolverOverrider.isOverridingDefaultResolver()) {
CredentialsConfig resolverCredentialsConfig = resolverOverrider.getResolverCredentialsConfig();
if (resolverCredentialsConfig != null) {
return resolverCredentialsConfig;
}
}
return server.getResolvingCredentialsConfig();
} | [
"public",
"static",
"CredentialsConfig",
"getPreferredResolver",
"(",
"ResolverOverrider",
"resolverOverrider",
",",
"ArtifactoryServer",
"server",
")",
"{",
"if",
"(",
"resolverOverrider",
"!=",
"null",
"&&",
"resolverOverrider",
".",
"isOverridingDefaultResolver",
"(",
... | Decides and returns the preferred resolver credentials to use from this builder settings and selected server
Override priority:
1) Job override resolver
2) Plugin manage override resolver
3) Plugin manage general
@param resolverOverrider Resolve-overriding capable builder
@param server Selected Artifactory server
@return Preferred resolver credentials | [
"Decides",
"and",
"returns",
"the",
"preferred",
"resolver",
"credentials",
"to",
"use",
"from",
"this",
"builder",
"settings",
"and",
"selected",
"server",
"Override",
"priority",
":",
"1",
")",
"Job",
"override",
"resolver",
"2",
")",
"Plugin",
"manage",
"ov... | train | https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/util/CredentialManager.java#L78-L87 |
jmeetsma/Iglu-Common | src/main/java/org/ijsberg/iglu/database/component/StandardConnectionPool.java | StandardConnectionPool.obtainConnection | ConnectionWrapper obtainConnection() {
synchronized (allConnections) {
//fails if connection pool not started
if (!availableConnections.isEmpty()) {
//retrieve and remove first connection from list
// since released connections are added to the back, connections will rotate
ConnectionWrapper connWrap = (ConnectionWrapper) availableConnections.remove(0);
usedConnections.add(connWrap);
if (usedConnections.size() > maxNrOfConcurrentConnectionsCounted) {
maxNrOfConcurrentConnectionsCounted = usedConnections.size();
}
return connWrap;
} else {
//create one if max not reached
//this also restores lost connections
if ((allConnections.size() < initialNrofConnections) || (allConnections.size() < maxNrofConnections)) {
try {
ConnectionWrapper connWrap = createConnectionWrapper(dbUrl, dbUsername, dbUserpassword);
allConnections.add(connWrap);
usedConnections.add(connWrap);
System.out.println(new LogEntry("Creating new Connection, now " + allConnections.size() + " in use"));
return connWrap;
} catch (SQLException sqle) {
//happens if db unreachable
//connection will be lost for the time being
nrofErrors++;
System.out.println(new LogEntry("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle));
throw new ResourceException("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle);
}
} else {
System.out.println(new LogEntry("maximum nr of connections (" + maxNrofConnections + ") reached while Application demands another"));
}
return null;
}
}
} | java | ConnectionWrapper obtainConnection() {
synchronized (allConnections) {
//fails if connection pool not started
if (!availableConnections.isEmpty()) {
//retrieve and remove first connection from list
// since released connections are added to the back, connections will rotate
ConnectionWrapper connWrap = (ConnectionWrapper) availableConnections.remove(0);
usedConnections.add(connWrap);
if (usedConnections.size() > maxNrOfConcurrentConnectionsCounted) {
maxNrOfConcurrentConnectionsCounted = usedConnections.size();
}
return connWrap;
} else {
//create one if max not reached
//this also restores lost connections
if ((allConnections.size() < initialNrofConnections) || (allConnections.size() < maxNrofConnections)) {
try {
ConnectionWrapper connWrap = createConnectionWrapper(dbUrl, dbUsername, dbUserpassword);
allConnections.add(connWrap);
usedConnections.add(connWrap);
System.out.println(new LogEntry("Creating new Connection, now " + allConnections.size() + " in use"));
return connWrap;
} catch (SQLException sqle) {
//happens if db unreachable
//connection will be lost for the time being
nrofErrors++;
System.out.println(new LogEntry("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle));
throw new ResourceException("Cannot create new connection to " + dbUrl + " unreachable or useless connection settings", sqle);
}
} else {
System.out.println(new LogEntry("maximum nr of connections (" + maxNrofConnections + ") reached while Application demands another"));
}
return null;
}
}
} | [
"ConnectionWrapper",
"obtainConnection",
"(",
")",
"{",
"synchronized",
"(",
"allConnections",
")",
"{",
"//fails if connection pool not started",
"if",
"(",
"!",
"availableConnections",
".",
"isEmpty",
"(",
")",
")",
"{",
"//retrieve and remove first connection from list",... | To be invoked by ConnectionWrapper and StandardConnectionPool only only
@return A database connection (wrapped in a class that implements Connection as well) | [
"To",
"be",
"invoked",
"by",
"ConnectionWrapper",
"and",
"StandardConnectionPool",
"only",
"only"
] | train | https://github.com/jmeetsma/Iglu-Common/blob/0fb0885775b576209ff1b5a0f67e3c25a99a6420/src/main/java/org/ijsberg/iglu/database/component/StandardConnectionPool.java#L440-L478 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.restoreSecretAsync | public Observable<SecretBundle> restoreSecretAsync(String vaultBaseUrl, byte[] secretBundleBackup) {
return restoreSecretWithServiceResponseAsync(vaultBaseUrl, secretBundleBackup).map(new Func1<ServiceResponse<SecretBundle>, SecretBundle>() {
@Override
public SecretBundle call(ServiceResponse<SecretBundle> response) {
return response.body();
}
});
} | java | public Observable<SecretBundle> restoreSecretAsync(String vaultBaseUrl, byte[] secretBundleBackup) {
return restoreSecretWithServiceResponseAsync(vaultBaseUrl, secretBundleBackup).map(new Func1<ServiceResponse<SecretBundle>, SecretBundle>() {
@Override
public SecretBundle call(ServiceResponse<SecretBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"SecretBundle",
">",
"restoreSecretAsync",
"(",
"String",
"vaultBaseUrl",
",",
"byte",
"[",
"]",
"secretBundleBackup",
")",
"{",
"return",
"restoreSecretWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"secretBundleBackup",
")",
".",
"... | Restores a backed up secret to a vault.
Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param secretBundleBackup The backup blob associated with a secret bundle.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the SecretBundle object | [
"Restores",
"a",
"backed",
"up",
"secret",
"to",
"a",
"vault",
".",
"Restores",
"a",
"backed",
"up",
"secret",
"and",
"all",
"its",
"versions",
"to",
"a",
"vault",
".",
"This",
"operation",
"requires",
"the",
"secrets",
"/",
"restore",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L5021-L5028 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java | ApiOvhEmailexchange.organizationName_service_exchangeService_account_primaryEmailAddress_PUT | public void organizationName_service_exchangeService_account_primaryEmailAddress_PUT(String organizationName, String exchangeService, String primaryEmailAddress, OvhAccount body) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/account/{primaryEmailAddress}";
StringBuilder sb = path(qPath, organizationName, exchangeService, primaryEmailAddress);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void organizationName_service_exchangeService_account_primaryEmailAddress_PUT(String organizationName, String exchangeService, String primaryEmailAddress, OvhAccount body) throws IOException {
String qPath = "/email/exchange/{organizationName}/service/{exchangeService}/account/{primaryEmailAddress}";
StringBuilder sb = path(qPath, organizationName, exchangeService, primaryEmailAddress);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"organizationName_service_exchangeService_account_primaryEmailAddress_PUT",
"(",
"String",
"organizationName",
",",
"String",
"exchangeService",
",",
"String",
"primaryEmailAddress",
",",
"OvhAccount",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qP... | Alter this object properties
REST: PUT /email/exchange/{organizationName}/service/{exchangeService}/account/{primaryEmailAddress}
@param body [required] New object properties
@param organizationName [required] The internal name of your exchange organization
@param exchangeService [required] The internal name of your exchange service
@param primaryEmailAddress [required] Default email for this mailbox | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailexchange/src/main/java/net/minidev/ovh/api/ApiOvhEmailexchange.java#L2092-L2096 |
JOML-CI/JOML | src/org/joml/Matrix4x3f.java | Matrix4x3f.lookAlong | public Matrix4x3f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) {
return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this);
} | java | public Matrix4x3f lookAlong(float dirX, float dirY, float dirZ, float upX, float upY, float upZ) {
return lookAlong(dirX, dirY, dirZ, upX, upY, upZ, this);
} | [
"public",
"Matrix4x3f",
"lookAlong",
"(",
"float",
"dirX",
",",
"float",
"dirY",
",",
"float",
"dirZ",
",",
"float",
"upX",
",",
"float",
"upY",
",",
"float",
"upZ",
")",
"{",
"return",
"lookAlong",
"(",
"dirX",
",",
"dirY",
",",
"dirZ",
",",
"upX",
... | Apply a rotation transformation to this matrix to make <code>-z</code> point along <code>dir</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookalong rotation matrix,
then the new matrix will be <code>M * L</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the
lookalong rotation transformation will be applied first!
<p>
This is equivalent to calling
{@link #lookAt(float, float, float, float, float, float, float, float, float) lookAt()}
with <code>eye = (0, 0, 0)</code> and <code>center = dir</code>.
<p>
In order to set the matrix to a lookalong transformation without post-multiplying it,
use {@link #setLookAlong(float, float, float, float, float, float) setLookAlong()}
@see #lookAt(float, float, float, float, float, float, float, float, float)
@see #setLookAlong(float, float, float, float, float, float)
@param dirX
the x-coordinate of the direction to look along
@param dirY
the y-coordinate of the direction to look along
@param dirZ
the z-coordinate of the direction to look along
@param upX
the x-coordinate of the up vector
@param upY
the y-coordinate of the up vector
@param upZ
the z-coordinate of the up vector
@return this | [
"Apply",
"a",
"rotation",
"transformation",
"to",
"this",
"matrix",
"to",
"make",
"<code",
">",
"-",
"z<",
"/",
"code",
">",
"point",
"along",
"<code",
">",
"dir<",
"/",
"code",
">",
".",
"<p",
">",
"If",
"<code",
">",
"M<",
"/",
"code",
">",
"is",... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3f.java#L6092-L6094 |
denisneuling/apitrary.jar | apitrary-api-client/src/main/java/com/apitrary/api/client/util/ClassUtil.java | ClassUtil.setSilent | public static Object setSilent(Object target, String fieldName, Object value) {
Class<?> targetClass = target.getClass();
try {
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(target, box(value, field.getType()));
return target;
} catch (Exception e) {
return target;
}
} | java | public static Object setSilent(Object target, String fieldName, Object value) {
Class<?> targetClass = target.getClass();
try {
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(target, box(value, field.getType()));
return target;
} catch (Exception e) {
return target;
}
} | [
"public",
"static",
"Object",
"setSilent",
"(",
"Object",
"target",
",",
"String",
"fieldName",
",",
"Object",
"value",
")",
"{",
"Class",
"<",
"?",
">",
"targetClass",
"=",
"target",
".",
"getClass",
"(",
")",
";",
"try",
"{",
"Field",
"field",
"=",
"... | <p>
setSilent.
</p>
@param target
a {@link java.lang.Object} object.
@param fieldName
a {@link java.lang.String} object.
@param value
a {@link java.lang.Object} object.
@return a {@link java.lang.Object} object. | [
"<p",
">",
"setSilent",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/denisneuling/apitrary.jar/blob/b7f639a1e735c60ba2b1b62851926757f5de8628/apitrary-api-client/src/main/java/com/apitrary/api/client/util/ClassUtil.java#L286-L296 |
ebean-orm/querybean-agent-now-merged-into-ebean-agent- | src/main/java/io/ebean/typequery/agent/ClassInfo.java | ClassInfo.addAssocBeanExtras | public void addAssocBeanExtras(ClassVisitor cv) {
if (isLog(3)) {
String msg = "... add fields";
if (!hasBasicConstructor) {
msg += ", basic constructor";
}
if (!hasMainConstructor) {
msg += ", main constructor";
}
log(msg);
}
if (!hasBasicConstructor) {
// add the assoc bean basic constructor
new TypeQueryAssocBasicConstructor(this, cv, ASSOC_BEAN_BASIC_CONSTRUCTOR_DESC, ASSOC_BEAN_BASIC_SIG).visitCode();
}
if (!hasMainConstructor) {
// add the assoc bean main constructor
new TypeQueryAssocMainConstructor(this, cv, ASSOC_BEAN_MAIN_CONSTRUCTOR_DESC, ASSOC_BEAN_MAIN_SIG).visitCode();
}
} | java | public void addAssocBeanExtras(ClassVisitor cv) {
if (isLog(3)) {
String msg = "... add fields";
if (!hasBasicConstructor) {
msg += ", basic constructor";
}
if (!hasMainConstructor) {
msg += ", main constructor";
}
log(msg);
}
if (!hasBasicConstructor) {
// add the assoc bean basic constructor
new TypeQueryAssocBasicConstructor(this, cv, ASSOC_BEAN_BASIC_CONSTRUCTOR_DESC, ASSOC_BEAN_BASIC_SIG).visitCode();
}
if (!hasMainConstructor) {
// add the assoc bean main constructor
new TypeQueryAssocMainConstructor(this, cv, ASSOC_BEAN_MAIN_CONSTRUCTOR_DESC, ASSOC_BEAN_MAIN_SIG).visitCode();
}
} | [
"public",
"void",
"addAssocBeanExtras",
"(",
"ClassVisitor",
"cv",
")",
"{",
"if",
"(",
"isLog",
"(",
"3",
")",
")",
"{",
"String",
"msg",
"=",
"\"... add fields\"",
";",
"if",
"(",
"!",
"hasBasicConstructor",
")",
"{",
"msg",
"+=",
"\", basic constructor\""... | Add fields and constructors to assoc type query beans as necessary. | [
"Add",
"fields",
"and",
"constructors",
"to",
"assoc",
"type",
"query",
"beans",
"as",
"necessary",
"."
] | train | https://github.com/ebean-orm/querybean-agent-now-merged-into-ebean-agent-/blob/a063554fabdbed15ff5e10ad0a0b53b67e039006/src/main/java/io/ebean/typequery/agent/ClassInfo.java#L185-L207 |
algolia/algoliasearch-client-java | src/main/java/com/algolia/search/saas/Index.java | Index.saveSynonym | public JSONObject saveSynonym(String objectID, JSONObject content, RequestOptions requestOptions) throws AlgoliaException {
return saveSynonym(objectID, content, false, requestOptions);
} | java | public JSONObject saveSynonym(String objectID, JSONObject content, RequestOptions requestOptions) throws AlgoliaException {
return saveSynonym(objectID, content, false, requestOptions);
} | [
"public",
"JSONObject",
"saveSynonym",
"(",
"String",
"objectID",
",",
"JSONObject",
"content",
",",
"RequestOptions",
"requestOptions",
")",
"throws",
"AlgoliaException",
"{",
"return",
"saveSynonym",
"(",
"objectID",
",",
"content",
",",
"false",
",",
"requestOpti... | Update one synonym
@param objectID The objectId of the synonym to save
@param content The new content of this synonym
@param requestOptions Options to pass to this request | [
"Update",
"one",
"synonym"
] | train | https://github.com/algolia/algoliasearch-client-java/blob/a05da2f66c099fe6f77295c7b6a8a12c24e95f9b/src/main/java/com/algolia/search/saas/Index.java#L1676-L1678 |
LearnLib/automatalib | visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/DOT.java | DOT.renderDOTExternal | public static void renderDOTExternal(Reader r, String format) {
try {
File image = File.createTempFile("dot", format);
runDOT(r, format, image);
Desktop.getDesktop().open(image);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Error rendering DOT: " + e.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
} | java | public static void renderDOTExternal(Reader r, String format) {
try {
File image = File.createTempFile("dot", format);
runDOT(r, format, image);
Desktop.getDesktop().open(image);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"Error rendering DOT: " + e.getMessage(),
"Error",
JOptionPane.ERROR_MESSAGE);
}
} | [
"public",
"static",
"void",
"renderDOTExternal",
"(",
"Reader",
"r",
",",
"String",
"format",
")",
"{",
"try",
"{",
"File",
"image",
"=",
"File",
".",
"createTempFile",
"(",
"\"dot\"",
",",
"format",
")",
";",
"runDOT",
"(",
"r",
",",
"format",
",",
"i... | Renders a GraphVIZ description, using an external program for displaying. The program is determined by the
system's file type associations, using the {@link Desktop#open(File)} method.
@param r
the reader from which the GraphVIZ description is read.
@param format
the output format, as understood by the dot utility, e.g., png, ps, ... | [
"Renders",
"a",
"GraphVIZ",
"description",
"using",
"an",
"external",
"program",
"for",
"displaying",
".",
"The",
"program",
"is",
"determined",
"by",
"the",
"system",
"s",
"file",
"type",
"associations",
"using",
"the",
"{",
"@link",
"Desktop#open",
"(",
"Fil... | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/DOT.java#L209-L220 |
infinispan/infinispan | remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/ProtobufValueWrapperSearchWorkCreator.java | ProtobufValueWrapperSearchWorkCreator.discoverMessageType | private void discoverMessageType(ProtobufValueWrapper valueWrapper) {
try {
ProtobufParser.INSTANCE.parse(new WrappedMessageTagHandler(valueWrapper, serializationContext), wrapperDescriptor, valueWrapper.getBinary());
} catch (IOException e) {
throw new CacheException(e);
}
} | java | private void discoverMessageType(ProtobufValueWrapper valueWrapper) {
try {
ProtobufParser.INSTANCE.parse(new WrappedMessageTagHandler(valueWrapper, serializationContext), wrapperDescriptor, valueWrapper.getBinary());
} catch (IOException e) {
throw new CacheException(e);
}
} | [
"private",
"void",
"discoverMessageType",
"(",
"ProtobufValueWrapper",
"valueWrapper",
")",
"{",
"try",
"{",
"ProtobufParser",
".",
"INSTANCE",
".",
"parse",
"(",
"new",
"WrappedMessageTagHandler",
"(",
"valueWrapper",
",",
"serializationContext",
")",
",",
"wrapperDe... | Discovers the type of the protobuf payload and if it is a message type it sets the descriptor using {@link
ProtobufValueWrapper#setMessageDescriptor}.
@param valueWrapper the wrapper of the protobuf binary payload | [
"Discovers",
"the",
"type",
"of",
"the",
"protobuf",
"payload",
"and",
"if",
"it",
"is",
"a",
"message",
"type",
"it",
"sets",
"the",
"descriptor",
"using",
"{",
"@link",
"ProtobufValueWrapper#setMessageDescriptor",
"}",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/remote-query/remote-query-server/src/main/java/org/infinispan/query/remote/impl/indexing/ProtobufValueWrapperSearchWorkCreator.java#L88-L94 |
dnsjava/dnsjava | org/xbill/DNS/Mnemonic.java | Mnemonic.addAlias | public void
addAlias(int val, String str) {
check(val);
Integer value = toInteger(val);
str = sanitize(str);
strings.put(str, value);
} | java | public void
addAlias(int val, String str) {
check(val);
Integer value = toInteger(val);
str = sanitize(str);
strings.put(str, value);
} | [
"public",
"void",
"addAlias",
"(",
"int",
"val",
",",
"String",
"str",
")",
"{",
"check",
"(",
"val",
")",
";",
"Integer",
"value",
"=",
"toInteger",
"(",
"val",
")",
";",
"str",
"=",
"sanitize",
"(",
"str",
")",
";",
"strings",
".",
"put",
"(",
... | Defines an additional text representation of a numeric value. This will
be used by getValue(), but not getText().
@param val The numeric value
@param string The text string | [
"Defines",
"an",
"additional",
"text",
"representation",
"of",
"a",
"numeric",
"value",
".",
"This",
"will",
"be",
"used",
"by",
"getValue",
"()",
"but",
"not",
"getText",
"()",
"."
] | train | https://github.com/dnsjava/dnsjava/blob/d97b6a0685d59143372bb392ab591dd8dd840b61/org/xbill/DNS/Mnemonic.java#L143-L149 |
sahan/DroidBallet | droidballet/src/main/java/com/lonepulse/droidballet/detector/HorizontalMotionDetector.java | HorizontalMotionDetector.processHorizontalDirection | private HORIZONTAL_DIRECTION processHorizontalDirection(float[] output, float midRangeHigh, float midRangeLow) {
output[1] = (output[1] < 0)? 0.0f : output[1];
if (output[1] < midRangeLow) {
output[1] *= -1;
return HORIZONTAL_DIRECTION.RIGHT;
}
else if (output[1] > midRangeHigh) {
return HORIZONTAL_DIRECTION.LEFT;
}
else {
return HORIZONTAL_DIRECTION.NONE;
}
} | java | private HORIZONTAL_DIRECTION processHorizontalDirection(float[] output, float midRangeHigh, float midRangeLow) {
output[1] = (output[1] < 0)? 0.0f : output[1];
if (output[1] < midRangeLow) {
output[1] *= -1;
return HORIZONTAL_DIRECTION.RIGHT;
}
else if (output[1] > midRangeHigh) {
return HORIZONTAL_DIRECTION.LEFT;
}
else {
return HORIZONTAL_DIRECTION.NONE;
}
} | [
"private",
"HORIZONTAL_DIRECTION",
"processHorizontalDirection",
"(",
"float",
"[",
"]",
"output",
",",
"float",
"midRangeHigh",
",",
"float",
"midRangeLow",
")",
"{",
"output",
"[",
"1",
"]",
"=",
"(",
"output",
"[",
"1",
"]",
"<",
"0",
")",
"?",
"0.0f",
... | <p>Determines the {@link HORIZONTAL_DIRECTION} of the motion and trims
the sensor reading on the X-Axis to within the bounds handled by the the
motion detector.
@param output
the smoothed sensor values
@param midRangeHigh
the upper-bound of the mid-range which correlates with {@link HORIZONTAL_DIRECTION#NONE}
@param midRangeLow
the lower-bound of the mid-range which correlates with {@link HORIZONTAL_DIRECTION#NONE}
@return the {@link HORIZONTAL_DIRECTION} of the motion | [
"<p",
">",
"Determines",
"the",
"{",
"@link",
"HORIZONTAL_DIRECTION",
"}",
"of",
"the",
"motion",
"and",
"trims",
"the",
"sensor",
"reading",
"on",
"the",
"X",
"-",
"Axis",
"to",
"within",
"the",
"bounds",
"handled",
"by",
"the",
"the",
"motion",
"detector... | train | https://github.com/sahan/DroidBallet/blob/c6001c9e933cb2c8dbcabe1ae561678b31b10b62/droidballet/src/main/java/com/lonepulse/droidballet/detector/HorizontalMotionDetector.java#L141-L158 |
iipc/openwayback | wayback-core/src/main/java/org/archive/wayback/replay/HttpHeaderOperation.java | HttpHeaderOperation.replaceHeader | public static void replaceHeader(Map<String, String> headers, String name, String value) {
removeHeader(headers, name);
headers.put(name, value);
} | java | public static void replaceHeader(Map<String, String> headers, String name, String value) {
removeHeader(headers, name);
headers.put(name, value);
} | [
"public",
"static",
"void",
"replaceHeader",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
",",
"String",
"name",
",",
"String",
"value",
")",
"{",
"removeHeader",
"(",
"headers",
",",
"name",
")",
";",
"headers",
".",
"put",
"(",
"name",
"... | Replace header field {@code name} value with {@code value}, or
add it if {@code headers} does not have {@code name}.
@param headers header fields
@param name header field name
@param value new value for the header field | [
"Replace",
"header",
"field",
"{"
] | train | https://github.com/iipc/openwayback/blob/da74c3a59a5b5a5c365bd4702dcb45d263535794/wayback-core/src/main/java/org/archive/wayback/replay/HttpHeaderOperation.java#L166-L169 |
grails/grails-core | grails-encoder/src/main/groovy/org/grails/encoder/AbstractEncodedAppender.java | AbstractEncodedAppender.shouldEncode | public boolean shouldEncode(Encoder encoderToApply, EncodingState encodingState) {
return ignoreEncodingState || (encoderToApply != null
&& (encodingState == null || shouldEncodeWith(encoderToApply, encodingState)));
} | java | public boolean shouldEncode(Encoder encoderToApply, EncodingState encodingState) {
return ignoreEncodingState || (encoderToApply != null
&& (encodingState == null || shouldEncodeWith(encoderToApply, encodingState)));
} | [
"public",
"boolean",
"shouldEncode",
"(",
"Encoder",
"encoderToApply",
",",
"EncodingState",
"encodingState",
")",
"{",
"return",
"ignoreEncodingState",
"||",
"(",
"encoderToApply",
"!=",
"null",
"&&",
"(",
"encodingState",
"==",
"null",
"||",
"shouldEncodeWith",
"(... | Check if the encoder should be used to a input with certain encodingState
@param encoderToApply
the encoder to apply
@param encodingState
the current encoding state
@return true, if should encode | [
"Check",
"if",
"the",
"encoder",
"should",
"be",
"used",
"to",
"a",
"input",
"with",
"certain",
"encodingState"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-encoder/src/main/groovy/org/grails/encoder/AbstractEncodedAppender.java#L170-L173 |
mikepenz/Android-Iconics | library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java | IconicsDrawable.colorListRes | @NonNull
public IconicsDrawable colorListRes(@ColorRes int colorResId) {
return color(ContextCompat.getColorStateList(mContext, colorResId));
} | java | @NonNull
public IconicsDrawable colorListRes(@ColorRes int colorResId) {
return color(ContextCompat.getColorStateList(mContext, colorResId));
} | [
"@",
"NonNull",
"public",
"IconicsDrawable",
"colorListRes",
"(",
"@",
"ColorRes",
"int",
"colorResId",
")",
"{",
"return",
"color",
"(",
"ContextCompat",
".",
"getColorStateList",
"(",
"mContext",
",",
"colorResId",
")",
")",
";",
"}"
] | Set the color of the drawable.
@param colorResId The color resource, from your R file.
@return The current IconicsDrawable for chaining. | [
"Set",
"the",
"color",
"of",
"the",
"drawable",
"."
] | train | https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java#L488-L491 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java | TmdbTV.getTVCredits | public MediaCreditList getTVCredits(int tvID, String language) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, tvID);
parameters.add(Param.LANGUAGE, language);
URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, MediaCreditList.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get credits", url, ex);
}
} | java | public MediaCreditList getTVCredits(int tvID, String language) throws MovieDbException {
TmdbParameters parameters = new TmdbParameters();
parameters.add(Param.ID, tvID);
parameters.add(Param.LANGUAGE, language);
URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.CREDITS).buildUrl(parameters);
String webpage = httpTools.getRequest(url);
try {
return MAPPER.readValue(webpage, MediaCreditList.class);
} catch (IOException ex) {
throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get credits", url, ex);
}
} | [
"public",
"MediaCreditList",
"getTVCredits",
"(",
"int",
"tvID",
",",
"String",
"language",
")",
"throws",
"MovieDbException",
"{",
"TmdbParameters",
"parameters",
"=",
"new",
"TmdbParameters",
"(",
")",
";",
"parameters",
".",
"add",
"(",
"Param",
".",
"ID",
... | Get the cast & crew information about a TV series.
@param tvID
@param language
@return
@throws com.omertron.themoviedbapi.MovieDbException | [
"Get",
"the",
"cast",
"&",
"crew",
"information",
"about",
"a",
"TV",
"series",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/methods/TmdbTV.java#L176-L188 |
dlemmermann/CalendarFX | CalendarFXView/src/main/java/com/calendarfx/view/YearMonthView.java | YearMonthView.setCellFactory | public final void setCellFactory(Callback<YearMonthView, DateCell> factory) {
requireNonNull(factory);
cellFactoryProperty().set(factory);
} | java | public final void setCellFactory(Callback<YearMonthView, DateCell> factory) {
requireNonNull(factory);
cellFactoryProperty().set(factory);
} | [
"public",
"final",
"void",
"setCellFactory",
"(",
"Callback",
"<",
"YearMonthView",
",",
"DateCell",
">",
"factory",
")",
"{",
"requireNonNull",
"(",
"factory",
")",
";",
"cellFactoryProperty",
"(",
")",
".",
"set",
"(",
"factory",
")",
";",
"}"
] | Sets the value of {@link #cellFactoryProperty()}.
@param factory
the cell factory | [
"Sets",
"the",
"value",
"of",
"{",
"@link",
"#cellFactoryProperty",
"()",
"}",
"."
] | train | https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/view/YearMonthView.java#L129-L132 |
tootedom/related | app/core/searching/src/main/java/org/greencheek/related/searching/repository/ElasticSearchFrequentlyRelatedItemSearchProcessor.java | ElasticSearchFrequentlyRelatedItemSearchProcessor.createFrequentlyRelatedContentSearch | private SearchRequestBuilder createFrequentlyRelatedContentSearch(RelatedItemSearch search, Client searchClient) {
SearchRequestBuilder sr = searchClient.prepareSearch();
sr.internalBuilder(builder.createFrequentlyRelatedContentSearch(search));
sr.setIndices(indexName);
return sr;
} | java | private SearchRequestBuilder createFrequentlyRelatedContentSearch(RelatedItemSearch search, Client searchClient) {
SearchRequestBuilder sr = searchClient.prepareSearch();
sr.internalBuilder(builder.createFrequentlyRelatedContentSearch(search));
sr.setIndices(indexName);
return sr;
} | [
"private",
"SearchRequestBuilder",
"createFrequentlyRelatedContentSearch",
"(",
"RelatedItemSearch",
"search",
",",
"Client",
"searchClient",
")",
"{",
"SearchRequestBuilder",
"sr",
"=",
"searchClient",
".",
"prepareSearch",
"(",
")",
";",
"sr",
".",
"internalBuilder",
... | /*
Creates a query like:
{
"size" : 0,
"timeout" : 5000,
"query" : {
"constant_score" : {
"filter" : {
"bool" : {
"must" : [ {
"term" : {
"related-with" : "apparentice you're hired"
}
}, {
"term" : {
"channel" : "bbc"
}
} ]
}
}
}
},
"facets" : {
"frequently-related-with" : {
"terms" : {
"field" : "id",
"size" : 5,
"execution_hint" : "map"
}
}
}
} | [
"/",
"*",
"Creates",
"a",
"query",
"like",
":"
] | train | https://github.com/tootedom/related/blob/3782dd5a839bbcdc15661d598e8b895aae8aabb7/app/core/searching/src/main/java/org/greencheek/related/searching/repository/ElasticSearchFrequentlyRelatedItemSearchProcessor.java#L191-L197 |
nguillaumin/slick2d-maven | slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/TTFFile.java | TTFFile.readFont | public boolean readFont(FontFileReader in, String name) throws IOException {
/*
* Check if TrueType collection, and that the name
* exists in the collection
*/
if (!checkTTC(in, name)) {
if (name == null) {
throw new IllegalArgumentException(
"For TrueType collection you must specify which font "
+ "to select (-ttcname)");
} else {
throw new IOException(
"Name does not exist in the TrueType collection: " + name);
}
}
readDirTabs(in);
readFontHeader(in);
getNumGlyphs(in);
log.info("Number of glyphs in font: " + numberOfGlyphs);
readHorizontalHeader(in);
readHorizontalMetrics(in);
initAnsiWidths();
readPostScript(in);
readOS2(in);
determineAscDesc();
readIndexToLocation(in);
//readGlyf(in);
readName(in);
boolean pcltFound = readPCLT(in);
// Read cmap table and fill in ansiwidths
boolean valid = readCMAP(in);
if (!valid) {
return false;
}
// Create cmaps for bfentries
//createCMaps();
// print_max_min();
readKerning(in);
//guessVerticalMetricsFromGlyphBBox();
return true;
} | java | public boolean readFont(FontFileReader in, String name) throws IOException {
/*
* Check if TrueType collection, and that the name
* exists in the collection
*/
if (!checkTTC(in, name)) {
if (name == null) {
throw new IllegalArgumentException(
"For TrueType collection you must specify which font "
+ "to select (-ttcname)");
} else {
throw new IOException(
"Name does not exist in the TrueType collection: " + name);
}
}
readDirTabs(in);
readFontHeader(in);
getNumGlyphs(in);
log.info("Number of glyphs in font: " + numberOfGlyphs);
readHorizontalHeader(in);
readHorizontalMetrics(in);
initAnsiWidths();
readPostScript(in);
readOS2(in);
determineAscDesc();
readIndexToLocation(in);
//readGlyf(in);
readName(in);
boolean pcltFound = readPCLT(in);
// Read cmap table and fill in ansiwidths
boolean valid = readCMAP(in);
if (!valid) {
return false;
}
// Create cmaps for bfentries
//createCMaps();
// print_max_min();
readKerning(in);
//guessVerticalMetricsFromGlyphBBox();
return true;
} | [
"public",
"boolean",
"readFont",
"(",
"FontFileReader",
"in",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"/*\n * Check if TrueType collection, and that the name\n * exists in the collection\n */",
"if",
"(",
"!",
"checkTTC",
"(",
"in",
"... | Read the font data.
If the fontfile is a TrueType Collection (.ttc file)
the name of the font to read data for must be supplied,
else the name is ignored.
@param in The FontFileReader to use
@param name The name of the font
@return boolean Returns true if the font is valid
@throws IOException In case of an I/O problem | [
"Read",
"the",
"font",
"data",
".",
"If",
"the",
"fontfile",
"is",
"a",
"TrueType",
"Collection",
"(",
".",
"ttc",
"file",
")",
"the",
"name",
"of",
"the",
"font",
"to",
"read",
"data",
"for",
"must",
"be",
"supplied",
"else",
"the",
"name",
"is",
"i... | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-hiero/src/main/java/org/newdawn/slick/tools/hiero/truetype/TTFFile.java#L520-L563 |
spotify/scio | scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java | PatchedBigQueryTableRowIterator.fromTable | public static PatchedBigQueryTableRowIterator fromTable(TableReference ref, Bigquery client) {
checkNotNull(ref, "ref");
checkNotNull(client, "client");
return new PatchedBigQueryTableRowIterator(ref, /* queryConfig */null, ref.getProjectId(), client);
} | java | public static PatchedBigQueryTableRowIterator fromTable(TableReference ref, Bigquery client) {
checkNotNull(ref, "ref");
checkNotNull(client, "client");
return new PatchedBigQueryTableRowIterator(ref, /* queryConfig */null, ref.getProjectId(), client);
} | [
"public",
"static",
"PatchedBigQueryTableRowIterator",
"fromTable",
"(",
"TableReference",
"ref",
",",
"Bigquery",
"client",
")",
"{",
"checkNotNull",
"(",
"ref",
",",
"\"ref\"",
")",
";",
"checkNotNull",
"(",
"client",
",",
"\"client\"",
")",
";",
"return",
"ne... | Constructs a {@code PatchedBigQueryTableRowIterator} that reads from the specified table. | [
"Constructs",
"a",
"{"
] | train | https://github.com/spotify/scio/blob/ed9a44428251b0c6834aad231b463d8eda418471/scio-bigquery/src/main/java/org/apache/beam/sdk/io/gcp/bigquery/PatchedBigQueryTableRowIterator.java#L116-L120 |
infinispan/infinispan | tools/src/main/java/org/infinispan/tools/config/v6/Parser60.java | Parser60.parseCommonStoreAttributes | public static void parseCommonStoreAttributes(XMLExtendedStreamReader reader, StoreConfigurationBuilder builder, String attributeName, String value, int i) throws XMLStreamException {
switch (Attribute.forName(attributeName)) {
case FETCH_PERSISTENT_STATE:
builder.fetchPersistentState(Boolean.valueOf(value));
break;
case IGNORE_MODIFICATIONS:
builder.ignoreModifications(Boolean.valueOf(value));
break;
case PURGE_ON_STARTUP:
builder.purgeOnStartup(Boolean.valueOf(value));
break;
case PRELOAD:
builder.preload(Boolean.parseBoolean(value));
break;
case SHARED:
builder.shared(Boolean.parseBoolean(value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
} | java | public static void parseCommonStoreAttributes(XMLExtendedStreamReader reader, StoreConfigurationBuilder builder, String attributeName, String value, int i) throws XMLStreamException {
switch (Attribute.forName(attributeName)) {
case FETCH_PERSISTENT_STATE:
builder.fetchPersistentState(Boolean.valueOf(value));
break;
case IGNORE_MODIFICATIONS:
builder.ignoreModifications(Boolean.valueOf(value));
break;
case PURGE_ON_STARTUP:
builder.purgeOnStartup(Boolean.valueOf(value));
break;
case PRELOAD:
builder.preload(Boolean.parseBoolean(value));
break;
case SHARED:
builder.shared(Boolean.parseBoolean(value));
break;
default:
throw ParseUtils.unexpectedAttribute(reader, i);
}
} | [
"public",
"static",
"void",
"parseCommonStoreAttributes",
"(",
"XMLExtendedStreamReader",
"reader",
",",
"StoreConfigurationBuilder",
"builder",
",",
"String",
"attributeName",
",",
"String",
"value",
",",
"int",
"i",
")",
"throws",
"XMLStreamException",
"{",
"switch",
... | This method is public static so that it can be reused by custom cache store/loader configuration parsers | [
"This",
"method",
"is",
"public",
"static",
"so",
"that",
"it",
"can",
"be",
"reused",
"by",
"custom",
"cache",
"store",
"/",
"loader",
"configuration",
"parsers"
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/tools/src/main/java/org/infinispan/tools/config/v6/Parser60.java#L651-L671 |
couchbase/couchbase-jvm-core | src/main/java/com/couchbase/client/core/endpoint/AbstractEndpoint.java | AbstractEndpoint.logIdent | protected static RedactableArgument logIdent(final Channel chan, final Endpoint endpoint) {
String addr = chan != null ? chan.remoteAddress().toString() : endpoint.remoteAddress();
return system("[" + addr + "][" + endpoint.getClass().getSimpleName() + "]: ");
} | java | protected static RedactableArgument logIdent(final Channel chan, final Endpoint endpoint) {
String addr = chan != null ? chan.remoteAddress().toString() : endpoint.remoteAddress();
return system("[" + addr + "][" + endpoint.getClass().getSimpleName() + "]: ");
} | [
"protected",
"static",
"RedactableArgument",
"logIdent",
"(",
"final",
"Channel",
"chan",
",",
"final",
"Endpoint",
"endpoint",
")",
"{",
"String",
"addr",
"=",
"chan",
"!=",
"null",
"?",
"chan",
".",
"remoteAddress",
"(",
")",
".",
"toString",
"(",
")",
"... | Simple log helper to give logs a common prefix.
@param chan the address.
@param endpoint the endpoint.
@return a prefix string for logs. | [
"Simple",
"log",
"helper",
"to",
"give",
"logs",
"a",
"common",
"prefix",
"."
] | train | https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/endpoint/AbstractEndpoint.java#L761-L764 |
FINRAOS/DataGenerator | dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java | BoundaryDate.getRandomHoliday | public String getRandomHoliday(String earliest, String latest) {
String dateString = "";
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime earlyDate = parser.parseDateTime(earliest);
DateTime lateDate = parser.parseDateTime(latest);
List<Holiday> holidays = new LinkedList<>();
int min = Integer.parseInt(earlyDate.toString().substring(0, 4));
int max = Integer.parseInt(lateDate.toString().substring(0, 4));
int range = max - min + 1;
int randomYear = (int) (Math.random() * range) + min;
for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {
holidays.add(s);
}
Collections.shuffle(holidays);
for (Holiday holiday : holidays) {
dateString = convertToReadableDate(holiday.forYear(randomYear));
if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {
break;
}
}
return dateString;
} | java | public String getRandomHoliday(String earliest, String latest) {
String dateString = "";
DateTimeFormatter parser = ISODateTimeFormat.date();
DateTime earlyDate = parser.parseDateTime(earliest);
DateTime lateDate = parser.parseDateTime(latest);
List<Holiday> holidays = new LinkedList<>();
int min = Integer.parseInt(earlyDate.toString().substring(0, 4));
int max = Integer.parseInt(lateDate.toString().substring(0, 4));
int range = max - min + 1;
int randomYear = (int) (Math.random() * range) + min;
for (Holiday s : EquivalenceClassTransformer.HOLIDAYS) {
holidays.add(s);
}
Collections.shuffle(holidays);
for (Holiday holiday : holidays) {
dateString = convertToReadableDate(holiday.forYear(randomYear));
if (toDate(dateString).after(toDate(earliest)) && toDate(dateString).before(toDate(latest))) {
break;
}
}
return dateString;
} | [
"public",
"String",
"getRandomHoliday",
"(",
"String",
"earliest",
",",
"String",
"latest",
")",
"{",
"String",
"dateString",
"=",
"\"\"",
";",
"DateTimeFormatter",
"parser",
"=",
"ISODateTimeFormat",
".",
"date",
"(",
")",
";",
"DateTime",
"earlyDate",
"=",
"... | Grab random holiday from the equivalence class that falls between the two dates
@param earliest the earliest date parameter as defined in the model
@param latest the latest date parameter as defined in the model
@return a holiday that falls between the dates | [
"Grab",
"random",
"holiday",
"from",
"the",
"equivalence",
"class",
"that",
"falls",
"between",
"the",
"two",
"dates"
] | train | https://github.com/FINRAOS/DataGenerator/blob/1f69f949401cbed4db4f553c3eb8350832c4d45a/dg-core/src/main/java/org/finra/datagenerator/engine/scxml/tags/boundary/BoundaryDate.java#L230-L254 |
jferard/fastods | fastods/src/main/java/com/github/jferard/fastods/util/Container.java | Container.add | public boolean add(final K key, final V value) {
final V curValue = this.valueByKey.get(key);
if (curValue == null) { // key does not exist
if (this.mode == Mode.UPDATE)
return false;
} else { // key exists
if (this.mode == Mode.CREATE)
return false;
}
if (this.closed && !this.valueByKey.containsKey(key)) {
throw new IllegalStateException(
"Container put(" + key + ", " + value + ")");
} else if (this.debug && !this.valueByKey.containsKey(key)) {
Logger.getLogger("debug").severe(
"Container put(" + key + ", " + value + ")");
}
this.valueByKey.put(key, value);
return true;
} | java | public boolean add(final K key, final V value) {
final V curValue = this.valueByKey.get(key);
if (curValue == null) { // key does not exist
if (this.mode == Mode.UPDATE)
return false;
} else { // key exists
if (this.mode == Mode.CREATE)
return false;
}
if (this.closed && !this.valueByKey.containsKey(key)) {
throw new IllegalStateException(
"Container put(" + key + ", " + value + ")");
} else if (this.debug && !this.valueByKey.containsKey(key)) {
Logger.getLogger("debug").severe(
"Container put(" + key + ", " + value + ")");
}
this.valueByKey.put(key, value);
return true;
} | [
"public",
"boolean",
"add",
"(",
"final",
"K",
"key",
",",
"final",
"V",
"value",
")",
"{",
"final",
"V",
"curValue",
"=",
"this",
".",
"valueByKey",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"curValue",
"==",
"null",
")",
"{",
"// key does not ex... | If mode is update, then the key must exist. If the mode is create, then the key must not exist.
Otherwise, the key may exist. If the container is frozen, no new key-value pair is accepted.
@param key the key
@param value the value
@return true if the value was updated | [
"If",
"mode",
"is",
"update",
"then",
"the",
"key",
"must",
"exist",
".",
"If",
"the",
"mode",
"is",
"create",
"then",
"the",
"key",
"must",
"not",
"exist",
".",
"Otherwise",
"the",
"key",
"may",
"exist",
".",
"If",
"the",
"container",
"is",
"frozen",
... | train | https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/util/Container.java#L71-L92 |
jenkinsci/jenkins | core/src/main/java/hudson/model/AbstractProject.java | AbstractProject.findNearest | public static @CheckForNull AbstractProject findNearest(String name, ItemGroup context) {
return Items.findNearest(AbstractProject.class, name, context);
} | java | public static @CheckForNull AbstractProject findNearest(String name, ItemGroup context) {
return Items.findNearest(AbstractProject.class, name, context);
} | [
"public",
"static",
"@",
"CheckForNull",
"AbstractProject",
"findNearest",
"(",
"String",
"name",
",",
"ItemGroup",
"context",
")",
"{",
"return",
"Items",
".",
"findNearest",
"(",
"AbstractProject",
".",
"class",
",",
"name",
",",
"context",
")",
";",
"}"
] | Finds a {@link AbstractProject} whose name (when referenced from the specified context) is closest to the given name.
@since 1.419
@see Items#findNearest | [
"Finds",
"a",
"{",
"@link",
"AbstractProject",
"}",
"whose",
"name",
"(",
"when",
"referenced",
"from",
"the",
"specified",
"context",
")",
"is",
"closest",
"to",
"the",
"given",
"name",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/AbstractProject.java#L2065-L2067 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/auth/AbstractAWSSigner.java | AbstractAWSSigner.getCanonicalizedQueryString | protected String getCanonicalizedQueryString(Map<String, List<String>> parameters) {
final SortedMap<String, List<String>> sorted = new TreeMap<String, List<String>>();
/**
* Signing protocol expects the param values also to be sorted after url
* encoding in addition to sorted parameter names.
*/
for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
final String encodedParamName = SdkHttpUtils.urlEncode(
entry.getKey(), false);
final List<String> paramValues = entry.getValue();
final List<String> encodedValues = new ArrayList<String>(
paramValues.size());
for (String value : paramValues) {
encodedValues.add(SdkHttpUtils.urlEncode(value, false));
}
Collections.sort(encodedValues);
sorted.put(encodedParamName, encodedValues);
}
final StringBuilder result = new StringBuilder();
for(Map.Entry<String, List<String>> entry : sorted.entrySet()) {
for(String value : entry.getValue()) {
if (result.length() > 0) {
result.append("&");
}
result.append(entry.getKey())
.append("=")
.append(value);
}
}
return result.toString();
} | java | protected String getCanonicalizedQueryString(Map<String, List<String>> parameters) {
final SortedMap<String, List<String>> sorted = new TreeMap<String, List<String>>();
/**
* Signing protocol expects the param values also to be sorted after url
* encoding in addition to sorted parameter names.
*/
for (Map.Entry<String, List<String>> entry : parameters.entrySet()) {
final String encodedParamName = SdkHttpUtils.urlEncode(
entry.getKey(), false);
final List<String> paramValues = entry.getValue();
final List<String> encodedValues = new ArrayList<String>(
paramValues.size());
for (String value : paramValues) {
encodedValues.add(SdkHttpUtils.urlEncode(value, false));
}
Collections.sort(encodedValues);
sorted.put(encodedParamName, encodedValues);
}
final StringBuilder result = new StringBuilder();
for(Map.Entry<String, List<String>> entry : sorted.entrySet()) {
for(String value : entry.getValue()) {
if (result.length() > 0) {
result.append("&");
}
result.append(entry.getKey())
.append("=")
.append(value);
}
}
return result.toString();
} | [
"protected",
"String",
"getCanonicalizedQueryString",
"(",
"Map",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"parameters",
")",
"{",
"final",
"SortedMap",
"<",
"String",
",",
"List",
"<",
"String",
">",
">",
"sorted",
"=",
"new",
"TreeMap",
"<",
... | Examines the specified query string parameters and returns a
canonicalized form.
<p>
The canonicalized query string is formed by first sorting all the query
string parameters, then URI encoding both the key and value and then
joining them, in order, separating key value pairs with an '&'.
@param parameters
The query string parameters to be canonicalized.
@return A canonicalized form for the specified query string parameters. | [
"Examines",
"the",
"specified",
"query",
"string",
"parameters",
"and",
"returns",
"a",
"canonicalized",
"form",
".",
"<p",
">",
"The",
"canonicalized",
"query",
"string",
"is",
"formed",
"by",
"first",
"sorting",
"all",
"the",
"query",
"string",
"parameters",
... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/auth/AbstractAWSSigner.java#L216-L251 |
dbracewell/mango | src/main/java/com/davidbracewell/string/StringUtils.java | StringUtils.randomString | public static String randomString(int length, int min, int max) {
return randomString(length, min, max, CharMatcher.ANY);
} | java | public static String randomString(int length, int min, int max) {
return randomString(length, min, max, CharMatcher.ANY);
} | [
"public",
"static",
"String",
"randomString",
"(",
"int",
"length",
",",
"int",
"min",
",",
"int",
"max",
")",
"{",
"return",
"randomString",
"(",
"length",
",",
"min",
",",
"max",
",",
"CharMatcher",
".",
"ANY",
")",
";",
"}"
] | Generates a random string of a given length
@param length The length of the string
@param min The min character in the string
@param max The max character in the string
@return A string of random characters | [
"Generates",
"a",
"random",
"string",
"of",
"a",
"given",
"length"
] | train | https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/string/StringUtils.java#L377-L379 |
ivanceras/orm | src/main/java/com/ivanceras/db/server/core/DB_PostgreSQL.java | DB_PostgreSQL.correctDataTypes | @Override
public void correctDataTypes(DAO[] daoList, ModelDef model) {
for(DAO dao : daoList){
correctDataTypes(dao, model);
}
} | java | @Override
public void correctDataTypes(DAO[] daoList, ModelDef model) {
for(DAO dao : daoList){
correctDataTypes(dao, model);
}
} | [
"@",
"Override",
"public",
"void",
"correctDataTypes",
"(",
"DAO",
"[",
"]",
"daoList",
",",
"ModelDef",
"model",
")",
"{",
"for",
"(",
"DAO",
"dao",
":",
"daoList",
")",
"{",
"correctDataTypes",
"(",
"dao",
",",
"model",
")",
";",
"}",
"}"
] | Most of postgresql database datatype already mapped to the correct data type by the JDBC | [
"Most",
"of",
"postgresql",
"database",
"datatype",
"already",
"mapped",
"to",
"the",
"correct",
"data",
"type",
"by",
"the",
"JDBC"
] | train | https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/server/core/DB_PostgreSQL.java#L856-L861 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java | ReUtil.extractMultiAndDelPre | public static String extractMultiAndDelPre(String regex, Holder<CharSequence> contentHolder, String template) {
if (null == contentHolder || null == regex || null == template) {
return null;
}
// Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Pattern pattern = PatternPool.get(regex, Pattern.DOTALL);
return extractMultiAndDelPre(pattern, contentHolder, template);
} | java | public static String extractMultiAndDelPre(String regex, Holder<CharSequence> contentHolder, String template) {
if (null == contentHolder || null == regex || null == template) {
return null;
}
// Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Pattern pattern = PatternPool.get(regex, Pattern.DOTALL);
return extractMultiAndDelPre(pattern, contentHolder, template);
} | [
"public",
"static",
"String",
"extractMultiAndDelPre",
"(",
"String",
"regex",
",",
"Holder",
"<",
"CharSequence",
">",
"contentHolder",
",",
"String",
"template",
")",
"{",
"if",
"(",
"null",
"==",
"contentHolder",
"||",
"null",
"==",
"regex",
"||",
"null",
... | 从content中匹配出多个值并根据template生成新的字符串<br>
例如:<br>
content 2013年5月 pattern (.*?)年(.*?)月 template: $1-$2 return 2013-5
@param regex 匹配正则字符串
@param contentHolder 被匹配的内容的Holder,value为内容正文,经过这个方法的原文将被去掉匹配之前的内容
@param template 生成内容模板,变量 $1 表示group1的内容,以此类推
@return 按照template拼接后的字符串 | [
"从content中匹配出多个值并根据template生成新的字符串<br",
">",
"例如:<br",
">",
"content",
"2013年5月",
"pattern",
"(",
".",
"*",
"?",
")",
"年",
"(",
".",
"*",
"?",
")",
"月",
"template:",
"$1",
"-",
"$2",
"return",
"2013",
"-",
"5"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReUtil.java#L260-L268 |
GeoLatte/geolatte-common | src/main/java/org/geolatte/common/expressions/Expressions.java | Expressions.isEqual | public static StringIsEqual isEqual(StringExpression left, Object constant) {
if (!(constant instanceof String))
throw new IllegalArgumentException("constant is not a String");
return new StringIsEqual(left, constant((String)constant));
} | java | public static StringIsEqual isEqual(StringExpression left, Object constant) {
if (!(constant instanceof String))
throw new IllegalArgumentException("constant is not a String");
return new StringIsEqual(left, constant((String)constant));
} | [
"public",
"static",
"StringIsEqual",
"isEqual",
"(",
"StringExpression",
"left",
",",
"Object",
"constant",
")",
"{",
"if",
"(",
"!",
"(",
"constant",
"instanceof",
"String",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"constant is not a String\"",
... | Creates an IsEqual expression from the given expression and constant.
@param left The left expression.
@param constant The constant to compare to (must be a String).
@throws IllegalArgumentException If constant is not a String.
@return A new IsEqual binary expression. | [
"Creates",
"an",
"IsEqual",
"expression",
"from",
"the",
"given",
"expression",
"and",
"constant",
"."
] | train | https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/expressions/Expressions.java#L226-L232 |
groupon/monsoon | prometheus/src/main/java/com/groupon/lex/prometheus/PrometheusMetrics.java | PrometheusMetrics.filteredMetrics | public static Stream<PrometheusMetric> filteredMetrics(PullProcessorPipeline registry) throws Exception {
Stream <PrometheusMetric> m = registry.get().stream()
.flatMap((TimeSeriesValue i) -> {
Map<MetricName, MetricValue> metrics = i.getMetrics();
GroupName group = i.getGroup();
return metrics.entrySet().stream()
.filter((kv) -> kv.getValue().value().isPresent())
.map((kv) -> {
final String metric_group = toPrometheusString_(group.getPath().getPath());
final Map<String, String> tags = group.getTags().stream()
.filter(tag -> tag.getValue().asString().isPresent())
.collect(Collectors.toMap(
tag -> escapeprometheus(tag.getKey()),
tag -> escapeLabelValue_(tag.getValue().asString().get())));
final String metric_name = toPrometheusString_(kv.getKey().getPath());
final Number metric_value = kv.getValue().value().get();
return new PrometheusMetric(metric_group, tags, metric_name, metric_value);
});
} | java | public static Stream<PrometheusMetric> filteredMetrics(PullProcessorPipeline registry) throws Exception {
Stream <PrometheusMetric> m = registry.get().stream()
.flatMap((TimeSeriesValue i) -> {
Map<MetricName, MetricValue> metrics = i.getMetrics();
GroupName group = i.getGroup();
return metrics.entrySet().stream()
.filter((kv) -> kv.getValue().value().isPresent())
.map((kv) -> {
final String metric_group = toPrometheusString_(group.getPath().getPath());
final Map<String, String> tags = group.getTags().stream()
.filter(tag -> tag.getValue().asString().isPresent())
.collect(Collectors.toMap(
tag -> escapeprometheus(tag.getKey()),
tag -> escapeLabelValue_(tag.getValue().asString().get())));
final String metric_name = toPrometheusString_(kv.getKey().getPath());
final Number metric_value = kv.getValue().value().get();
return new PrometheusMetric(metric_group, tags, metric_name, metric_value);
});
} | [
"public",
"static",
"Stream",
"<",
"PrometheusMetric",
">",
"filteredMetrics",
"(",
"PullProcessorPipeline",
"registry",
")",
"throws",
"Exception",
"{",
"Stream",
"<",
"PrometheusMetric",
">",
"m",
"=",
"registry",
".",
"get",
"(",
")",
".",
"stream",
"(",
")... | @param registry
@return a Stream of PrometheusMetrics
@throws java.lang.Exception
It will filter out None values and replace all Characters that
Does not confirm to Prometheus Metric Format. | [
"@param",
"registry",
"@return",
"a",
"Stream",
"of",
"PrometheusMetrics",
"@throws",
"java",
".",
"lang",
".",
"Exception"
] | train | https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/prometheus/src/main/java/com/groupon/lex/prometheus/PrometheusMetrics.java#L61-L79 |
mirage-sql/mirage | src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java | SchemaUpdater.getSql | protected String getSql(int version){
Dialect dialect = ((SqlManagerImpl) sqlManager).getDialect();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream in = classLoader.getResourceAsStream(
String.format("%s/%s_%d.sql", packageName, dialect.getName().toLowerCase(), version));
if(in == null){
in = classLoader.getResourceAsStream(
String.format("%s/%d.sql", packageName, version));
if(in == null){
return null;
}
}
byte[] buf = IOUtil.readStream(in);
return new String(buf, StandardCharsets.UTF_8);
} | java | protected String getSql(int version){
Dialect dialect = ((SqlManagerImpl) sqlManager).getDialect();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream in = classLoader.getResourceAsStream(
String.format("%s/%s_%d.sql", packageName, dialect.getName().toLowerCase(), version));
if(in == null){
in = classLoader.getResourceAsStream(
String.format("%s/%d.sql", packageName, version));
if(in == null){
return null;
}
}
byte[] buf = IOUtil.readStream(in);
return new String(buf, StandardCharsets.UTF_8);
} | [
"protected",
"String",
"getSql",
"(",
"int",
"version",
")",
"{",
"Dialect",
"dialect",
"=",
"(",
"(",
"SqlManagerImpl",
")",
"sqlManager",
")",
".",
"getDialect",
"(",
")",
";",
"ClassLoader",
"classLoader",
"=",
"Thread",
".",
"currentThread",
"(",
")",
... | Returns the SQL which located within a package specified by the packageName as
"dialectname_version.sql" or "version.sql".
@param version the version number
@return SQL or null if the SQL file does not exist | [
"Returns",
"the",
"SQL",
"which",
"located",
"within",
"a",
"package",
"specified",
"by",
"the",
"packageName",
"as",
"dialectname_version",
".",
"sql",
"or",
"version",
".",
"sql",
"."
] | train | https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/updater/SchemaUpdater.java#L117-L136 |
elki-project/elki | elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/correlation/UncenteredCorrelationDistanceFunction.java | UncenteredCorrelationDistanceFunction.uncenteredCorrelation | public static double uncenteredCorrelation(NumberVector x, NumberVector y) {
final int xdim = x.getDimensionality(), ydim = y.getDimensionality();
if(xdim != ydim) {
throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality.");
}
double sumXX = 0., sumYY = 0., sumXY = 0.;
for(int i = 0; i < xdim; i++) {
final double xv = x.doubleValue(i), yv = y.doubleValue(i);
sumXX += xv * xv;
sumYY += yv * yv;
sumXY += xv * yv;
}
// One or both series were constant:
if(!(sumXX > 0. && sumYY > 0.)) {
return (sumXX == sumYY) ? 1. : 0.;
}
return sumXY / FastMath.sqrt(sumXX * sumYY);
} | java | public static double uncenteredCorrelation(NumberVector x, NumberVector y) {
final int xdim = x.getDimensionality(), ydim = y.getDimensionality();
if(xdim != ydim) {
throw new IllegalArgumentException("Invalid arguments: number vectors differ in dimensionality.");
}
double sumXX = 0., sumYY = 0., sumXY = 0.;
for(int i = 0; i < xdim; i++) {
final double xv = x.doubleValue(i), yv = y.doubleValue(i);
sumXX += xv * xv;
sumYY += yv * yv;
sumXY += xv * yv;
}
// One or both series were constant:
if(!(sumXX > 0. && sumYY > 0.)) {
return (sumXX == sumYY) ? 1. : 0.;
}
return sumXY / FastMath.sqrt(sumXX * sumYY);
} | [
"public",
"static",
"double",
"uncenteredCorrelation",
"(",
"NumberVector",
"x",
",",
"NumberVector",
"y",
")",
"{",
"final",
"int",
"xdim",
"=",
"x",
".",
"getDimensionality",
"(",
")",
",",
"ydim",
"=",
"y",
".",
"getDimensionality",
"(",
")",
";",
"if",... | Compute the uncentered correlation of two vectors.
@param x first NumberVector
@param y second NumberVector
@return the uncentered correlation coefficient for x and y | [
"Compute",
"the",
"uncentered",
"correlation",
"of",
"two",
"vectors",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-distance/src/main/java/de/lmu/ifi/dbs/elki/distance/distancefunction/correlation/UncenteredCorrelationDistanceFunction.java#L60-L77 |
structr/structr | structr-core/src/main/java/org/structr/core/graph/SyncCommand.java | SyncCommand.exportToStream | public static void exportToStream(final OutputStream outputStream, final Iterable<? extends NodeInterface> nodes, final Iterable<? extends RelationshipInterface> relationships, final Iterable<String> filePaths, final boolean includeFiles) throws FrameworkException {
try (final ZipOutputStream zos = new ZipOutputStream(outputStream)) {
final Set<String> filesToInclude = new LinkedHashSet<>();
if (filePaths != null) {
for (String file : filePaths) {
filesToInclude.add(file);
}
}
// set compression
zos.setLevel(6);
if (includeFiles) {
logger.info("Exporting files..");
// export files first
exportDirectory(zos, new File("files"), "", filesToInclude.isEmpty() ? null : filesToInclude);
}
// export database
exportDatabase(zos, new BufferedOutputStream(zos), nodes, relationships);
// finish ZIP file
zos.finish();
// close stream
zos.flush();
zos.close();
} catch (Throwable t) {
logger.warn("", t);
throw new FrameworkException(500, t.getMessage());
}
} | java | public static void exportToStream(final OutputStream outputStream, final Iterable<? extends NodeInterface> nodes, final Iterable<? extends RelationshipInterface> relationships, final Iterable<String> filePaths, final boolean includeFiles) throws FrameworkException {
try (final ZipOutputStream zos = new ZipOutputStream(outputStream)) {
final Set<String> filesToInclude = new LinkedHashSet<>();
if (filePaths != null) {
for (String file : filePaths) {
filesToInclude.add(file);
}
}
// set compression
zos.setLevel(6);
if (includeFiles) {
logger.info("Exporting files..");
// export files first
exportDirectory(zos, new File("files"), "", filesToInclude.isEmpty() ? null : filesToInclude);
}
// export database
exportDatabase(zos, new BufferedOutputStream(zos), nodes, relationships);
// finish ZIP file
zos.finish();
// close stream
zos.flush();
zos.close();
} catch (Throwable t) {
logger.warn("", t);
throw new FrameworkException(500, t.getMessage());
}
} | [
"public",
"static",
"void",
"exportToStream",
"(",
"final",
"OutputStream",
"outputStream",
",",
"final",
"Iterable",
"<",
"?",
"extends",
"NodeInterface",
">",
"nodes",
",",
"final",
"Iterable",
"<",
"?",
"extends",
"RelationshipInterface",
">",
"relationships",
... | Exports the given part of the structr database to the given output stream.
@param outputStream
@param nodes
@param relationships
@param filePaths
@param includeFiles
@throws FrameworkException | [
"Exports",
"the",
"given",
"part",
"of",
"the",
"structr",
"database",
"to",
"the",
"given",
"output",
"stream",
"."
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-core/src/main/java/org/structr/core/graph/SyncCommand.java#L262-L302 |
JOML-CI/JOML | src/org/joml/Quaterniond.java | Quaterniond.rotationAxis | public Quaterniond rotationAxis(AxisAngle4f axisAngle) {
return rotationAxis(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z);
} | java | public Quaterniond rotationAxis(AxisAngle4f axisAngle) {
return rotationAxis(axisAngle.angle, axisAngle.x, axisAngle.y, axisAngle.z);
} | [
"public",
"Quaterniond",
"rotationAxis",
"(",
"AxisAngle4f",
"axisAngle",
")",
"{",
"return",
"rotationAxis",
"(",
"axisAngle",
".",
"angle",
",",
"axisAngle",
".",
"x",
",",
"axisAngle",
".",
"y",
",",
"axisAngle",
".",
"z",
")",
";",
"}"
] | Set this {@link Quaterniond} to a rotation of the given angle in radians about the supplied
axis, all of which are specified via the {@link AxisAngle4f}.
@see #rotationAxis(double, double, double, double)
@param axisAngle
the {@link AxisAngle4f} giving the rotation angle in radians and the axis to rotate about
@return this | [
"Set",
"this",
"{",
"@link",
"Quaterniond",
"}",
"to",
"a",
"rotation",
"of",
"the",
"given",
"angle",
"in",
"radians",
"about",
"the",
"supplied",
"axis",
"all",
"of",
"which",
"are",
"specified",
"via",
"the",
"{",
"@link",
"AxisAngle4f",
"}",
"."
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaterniond.java#L1991-L1993 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingPoliciesInner.java | StreamingPoliciesInner.listAsync | public Observable<Page<StreamingPolicyInner>> listAsync(final String resourceGroupName, final String accountName) {
return listWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<StreamingPolicyInner>>, Page<StreamingPolicyInner>>() {
@Override
public Page<StreamingPolicyInner> call(ServiceResponse<Page<StreamingPolicyInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<StreamingPolicyInner>> listAsync(final String resourceGroupName, final String accountName) {
return listWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<StreamingPolicyInner>>, Page<StreamingPolicyInner>>() {
@Override
public Page<StreamingPolicyInner> call(ServiceResponse<Page<StreamingPolicyInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"StreamingPolicyInner",
">",
">",
"listAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"accountName",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName... | List Streaming Policies.
Lists the Streaming Policies in the account.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<StreamingPolicyInner> object | [
"List",
"Streaming",
"Policies",
".",
"Lists",
"the",
"Streaming",
"Policies",
"in",
"the",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingPoliciesInner.java#L138-L146 |
teknux-org/jetty-bootstrap | jetty-bootstrap/src/main/java/org/teknux/jettybootstrap/JettyBootstrap.java | JettyBootstrap.addWarAppFromClasspath | public WebAppContext addWarAppFromClasspath(String warFromClasspath, String contextPath) throws JettyBootstrapException {
WarAppFromClasspathJettyHandler warAppFromClasspathJettyHandler = new WarAppFromClasspathJettyHandler(getInitializedConfiguration());
warAppFromClasspathJettyHandler.setWarFromClasspath(warFromClasspath);
warAppFromClasspathJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = warAppFromClasspathJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
} | java | public WebAppContext addWarAppFromClasspath(String warFromClasspath, String contextPath) throws JettyBootstrapException {
WarAppFromClasspathJettyHandler warAppFromClasspathJettyHandler = new WarAppFromClasspathJettyHandler(getInitializedConfiguration());
warAppFromClasspathJettyHandler.setWarFromClasspath(warFromClasspath);
warAppFromClasspathJettyHandler.setContextPath(contextPath);
WebAppContext webAppContext = warAppFromClasspathJettyHandler.getHandler();
handlers.addHandler(webAppContext);
return webAppContext;
} | [
"public",
"WebAppContext",
"addWarAppFromClasspath",
"(",
"String",
"warFromClasspath",
",",
"String",
"contextPath",
")",
"throws",
"JettyBootstrapException",
"{",
"WarAppFromClasspathJettyHandler",
"warAppFromClasspathJettyHandler",
"=",
"new",
"WarAppFromClasspathJettyHandler",
... | Add a War application from the current classpath specifying the context path.
@param warFromClasspath
the path to a war file in the classpath
@param contextPath
the path (base URL) to make the war available
@return WebAppContext
@throws JettyBootstrapException
on failed | [
"Add",
"a",
"War",
"application",
"from",
"the",
"current",
"classpath",
"specifying",
"the",
"context",
"path",
"."
] | train | https://github.com/teknux-org/jetty-bootstrap/blob/c16e710b833084c650fce35aa8c1ccaf83cd93ef/jetty-bootstrap/src/main/java/org/teknux/jettybootstrap/JettyBootstrap.java#L283-L292 |
lisicnu/droidUtil | src/main/java/com/github/lisicnu/libDroid/util/FileUtils.java | FileUtils.isTargetValid | private static boolean isTargetValid(File fi, boolean ignoreCase, String... fileExt) {
if (fi == null || fileExt == null || fileExt.length == 0)
return true;
String ext = getExtension(fi);
for (String str : fileExt) {
if (ignoreCase ? ext.equalsIgnoreCase(str) : ext.equals(str))
return true;
}
return false;
} | java | private static boolean isTargetValid(File fi, boolean ignoreCase, String... fileExt) {
if (fi == null || fileExt == null || fileExt.length == 0)
return true;
String ext = getExtension(fi);
for (String str : fileExt) {
if (ignoreCase ? ext.equalsIgnoreCase(str) : ext.equals(str))
return true;
}
return false;
} | [
"private",
"static",
"boolean",
"isTargetValid",
"(",
"File",
"fi",
",",
"boolean",
"ignoreCase",
",",
"String",
"...",
"fileExt",
")",
"{",
"if",
"(",
"fi",
"==",
"null",
"||",
"fileExt",
"==",
"null",
"||",
"fileExt",
".",
"length",
"==",
"0",
")",
"... | 是否是符合特殊的文件格式, 如果 fi 或者 fileExt 是null, 空, 将会直接返回TRUE.
@param fi
@param ignoreCase
@param fileExt
@return | [
"是否是符合特殊的文件格式",
"如果",
"fi",
"或者",
"fileExt",
"是null",
"空",
"将会直接返回TRUE",
"."
] | train | https://github.com/lisicnu/droidUtil/blob/e4d6cf3e3f60e5efb5a75672607ded94d1725519/src/main/java/com/github/lisicnu/libDroid/util/FileUtils.java#L92-L104 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/VirtualHubsInner.java | VirtualHubsInner.beginCreateOrUpdate | public VirtualHubInner beginCreateOrUpdate(String resourceGroupName, String virtualHubName, VirtualHubInner virtualHubParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualHubName, virtualHubParameters).toBlocking().single().body();
} | java | public VirtualHubInner beginCreateOrUpdate(String resourceGroupName, String virtualHubName, VirtualHubInner virtualHubParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, virtualHubName, virtualHubParameters).toBlocking().single().body();
} | [
"public",
"VirtualHubInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualHubName",
",",
"VirtualHubInner",
"virtualHubParameters",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"virtualHub... | Creates a VirtualHub resource if it doesn't exist else updates the existing VirtualHub.
@param resourceGroupName The resource group name of the VirtualHub.
@param virtualHubName The name of the VirtualHub.
@param virtualHubParameters Parameters supplied to create or update VirtualHub.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the VirtualHubInner object if successful. | [
"Creates",
"a",
"VirtualHub",
"resource",
"if",
"it",
"doesn",
"t",
"exist",
"else",
"updates",
"the",
"existing",
"VirtualHub",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_06_01/src/main/java/com/microsoft/azure/management/network/v2018_06_01/implementation/VirtualHubsInner.java#L286-L288 |
datasift/datasift-java | src/main/java/com/datasift/client/push/connectors/CouchDB.java | CouchDB.useSSL | public CouchDB useSSL(String yesOrNo) {
if (yesOrNo == null || !"yes".equals(yesOrNo) || !"no".equals(yesOrNo)) {
throw new IllegalArgumentException("The strings yes or no are the only valid options for the use ssl " +
"option");
}
return setParam("use_ssl", yesOrNo);
} | java | public CouchDB useSSL(String yesOrNo) {
if (yesOrNo == null || !"yes".equals(yesOrNo) || !"no".equals(yesOrNo)) {
throw new IllegalArgumentException("The strings yes or no are the only valid options for the use ssl " +
"option");
}
return setParam("use_ssl", yesOrNo);
} | [
"public",
"CouchDB",
"useSSL",
"(",
"String",
"yesOrNo",
")",
"{",
"if",
"(",
"yesOrNo",
"==",
"null",
"||",
"!",
"\"yes\"",
".",
"equals",
"(",
"yesOrNo",
")",
"||",
"!",
"\"no\"",
".",
"equals",
"(",
"yesOrNo",
")",
")",
"{",
"throw",
"new",
"Illeg... | /*
Whether SSL should be used when connecting to the database. Possible values are:
yes
no
@return this | [
"/",
"*",
"Whether",
"SSL",
"should",
"be",
"used",
"when",
"connecting",
"to",
"the",
"database",
".",
"Possible",
"values",
"are",
":",
"yes",
"no"
] | train | https://github.com/datasift/datasift-java/blob/09de124f2a1a507ff6181e59875c6f325290850e/src/main/java/com/datasift/client/push/connectors/CouchDB.java#L85-L91 |
lamydev/Android-Notification | core/src/zemin/notification/NotificationBoard.java | NotificationBoard.setRowMargin | public void setRowMargin(int l, int t, int r, int b) {
mRowMargin[0] = l; mRowMargin[1] = t; mRowMargin[2] = r; mRowMargin[3] = b;
} | java | public void setRowMargin(int l, int t, int r, int b) {
mRowMargin[0] = l; mRowMargin[1] = t; mRowMargin[2] = r; mRowMargin[3] = b;
} | [
"public",
"void",
"setRowMargin",
"(",
"int",
"l",
",",
"int",
"t",
",",
"int",
"r",
",",
"int",
"b",
")",
"{",
"mRowMargin",
"[",
"0",
"]",
"=",
"l",
";",
"mRowMargin",
"[",
"1",
"]",
"=",
"t",
";",
"mRowMargin",
"[",
"2",
"]",
"=",
"r",
";"... | Set the margin of each row.
@param l
@param t
@param r
@param b | [
"Set",
"the",
"margin",
"of",
"each",
"row",
"."
] | train | https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationBoard.java#L592-L594 |
DDTH/ddth-kafka | src/main/java/com/github/ddth/kafka/KafkaClient.java | KafkaClient.sendMessage | public KafkaMessage sendMessage(ProducerType type, KafkaMessage message) {
String key = message.key();
ProducerRecord<String, byte[]> record = StringUtils.isEmpty(key)
? new ProducerRecord<>(message.topic(), message.content())
: new ProducerRecord<>(message.topic(), key, message.content());
KafkaProducer<String, byte[]> producer = getJavaProducer(type);
try {
RecordMetadata metadata = producer.send(record).get();
KafkaMessage kafkaMessage = new KafkaMessage(message);
kafkaMessage.partition(metadata.partition());
kafkaMessage.offset(metadata.offset());
return kafkaMessage;
} catch (InterruptedException | ExecutionException e) {
throw new KafkaException(e);
}
} | java | public KafkaMessage sendMessage(ProducerType type, KafkaMessage message) {
String key = message.key();
ProducerRecord<String, byte[]> record = StringUtils.isEmpty(key)
? new ProducerRecord<>(message.topic(), message.content())
: new ProducerRecord<>(message.topic(), key, message.content());
KafkaProducer<String, byte[]> producer = getJavaProducer(type);
try {
RecordMetadata metadata = producer.send(record).get();
KafkaMessage kafkaMessage = new KafkaMessage(message);
kafkaMessage.partition(metadata.partition());
kafkaMessage.offset(metadata.offset());
return kafkaMessage;
} catch (InterruptedException | ExecutionException e) {
throw new KafkaException(e);
}
} | [
"public",
"KafkaMessage",
"sendMessage",
"(",
"ProducerType",
"type",
",",
"KafkaMessage",
"message",
")",
"{",
"String",
"key",
"=",
"message",
".",
"key",
"(",
")",
";",
"ProducerRecord",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"record",
"=",
"StringU... | Sends a message, specifying {@link ProducerType}.
@param type
@param message
@return a copy of message filled with partition number and offset | [
"Sends",
"a",
"message",
"specifying",
"{",
"@link",
"ProducerType",
"}",
"."
] | train | https://github.com/DDTH/ddth-kafka/blob/aaeb8536e28a109ac0b69022f0ea4bbf5696b76f/src/main/java/com/github/ddth/kafka/KafkaClient.java#L677-L692 |
google/jimfs | jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java | JimfsFileStore.getFileAttributeView | @Nullable
<V extends FileAttributeView> V getFileAttributeView(FileLookup lookup, Class<V> type) {
state.checkOpen();
return attributes.getFileAttributeView(lookup, type);
} | java | @Nullable
<V extends FileAttributeView> V getFileAttributeView(FileLookup lookup, Class<V> type) {
state.checkOpen();
return attributes.getFileAttributeView(lookup, type);
} | [
"@",
"Nullable",
"<",
"V",
"extends",
"FileAttributeView",
">",
"V",
"getFileAttributeView",
"(",
"FileLookup",
"lookup",
",",
"Class",
"<",
"V",
">",
"type",
")",
"{",
"state",
".",
"checkOpen",
"(",
")",
";",
"return",
"attributes",
".",
"getFileAttributeV... | Returns an attribute view of the given type for the given file lookup callback, or {@code null}
if the view type is not supported. | [
"Returns",
"an",
"attribute",
"view",
"of",
"the",
"given",
"type",
"for",
"the",
"given",
"file",
"lookup",
"callback",
"or",
"{"
] | train | https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/JimfsFileStore.java#L173-L177 |
JodaOrg/joda-time | src/main/java/org/joda/time/field/FieldUtils.java | FieldUtils.safeMultiplyToInt | public static int safeMultiplyToInt(long val1, long val2) {
long val = FieldUtils.safeMultiply(val1, val2);
return FieldUtils.safeToInt(val);
} | java | public static int safeMultiplyToInt(long val1, long val2) {
long val = FieldUtils.safeMultiply(val1, val2);
return FieldUtils.safeToInt(val);
} | [
"public",
"static",
"int",
"safeMultiplyToInt",
"(",
"long",
"val1",
",",
"long",
"val2",
")",
"{",
"long",
"val",
"=",
"FieldUtils",
".",
"safeMultiply",
"(",
"val1",
",",
"val2",
")",
";",
"return",
"FieldUtils",
".",
"safeToInt",
"(",
"val",
")",
";",... | Multiply two values to return an int throwing an exception if overflow occurs.
@param val1 the first value
@param val2 the second value
@return the new total
@throws ArithmeticException if the value is too big or too small | [
"Multiply",
"two",
"values",
"to",
"return",
"an",
"int",
"throwing",
"an",
"exception",
"if",
"overflow",
"occurs",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/field/FieldUtils.java#L240-L243 |
hypercube1024/firefly | firefly-common/src/main/java/com/firefly/utils/StringUtils.java | StringUtils.normalizeCharset | public static String normalizeCharset(String s, int offset, int length) {
String n = CHARSETS.get(s, offset, length);
return (n == null) ? s.substring(offset, offset + length) : n;
} | java | public static String normalizeCharset(String s, int offset, int length) {
String n = CHARSETS.get(s, offset, length);
return (n == null) ? s.substring(offset, offset + length) : n;
} | [
"public",
"static",
"String",
"normalizeCharset",
"(",
"String",
"s",
",",
"int",
"offset",
",",
"int",
"length",
")",
"{",
"String",
"n",
"=",
"CHARSETS",
".",
"get",
"(",
"s",
",",
"offset",
",",
"length",
")",
";",
"return",
"(",
"n",
"==",
"null"... | Convert alternate charset names (eg utf8) to normalized name (eg UTF-8).
@param s the charset to normalize
@param offset the offset in the charset
@param length the length of the charset in the input param
@return the normalized charset (or null if not found) | [
"Convert",
"alternate",
"charset",
"names",
"(",
"eg",
"utf8",
")",
"to",
"normalized",
"name",
"(",
"eg",
"UTF",
"-",
"8",
")",
"."
] | train | https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/StringUtils.java#L65-L68 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WMultiSelectPairRenderer.java | WMultiSelectPairRenderer.doRender | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WMultiSelectPair multiSelectPair = (WMultiSelectPair) component;
XmlStringBuilder xml = renderContext.getWriter();
boolean readOnly = multiSelectPair.isReadOnly();
xml.appendTagOpen("ui:multiselectpair");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", multiSelectPair.isHidden(), "true");
if (readOnly) {
xml.appendAttribute("readOnly", "true");
} else {
int rows = multiSelectPair.getRows();
int min = multiSelectPair.getMinSelect();
int max = multiSelectPair.getMaxSelect();
xml.appendAttribute("size", rows < 2 ? WMultiSelectPair.DEFAULT_ROWS : rows);
xml.appendOptionalAttribute("disabled", multiSelectPair.isDisabled(), "true");
xml.appendOptionalAttribute("required", multiSelectPair.isMandatory(), "true");
xml.appendOptionalAttribute("shuffle", multiSelectPair.isShuffle(), "true");
xml.appendOptionalAttribute("fromListName", multiSelectPair.getAvailableListName());
xml.appendOptionalAttribute("toListName", multiSelectPair.getSelectedListName());
xml.appendOptionalAttribute("accessibleText", multiSelectPair.getAccessibleText());
xml.appendOptionalAttribute("min", min > 0, min);
xml.appendOptionalAttribute("max", max > 0, max);
}
xml.appendClose();
// Options
List<?> options = multiSelectPair.getOptions();
boolean renderSelectionsOnly = readOnly;
if (options != null) {
if (multiSelectPair.isShuffle()) {
// We need to render the selected options in order
renderOrderedOptions(multiSelectPair, options, 0, xml, renderSelectionsOnly);
} else {
renderUnorderedOptions(multiSelectPair, options, 0, xml, renderSelectionsOnly);
}
}
if (!readOnly) {
DiagnosticRenderUtil.renderDiagnostics(multiSelectPair, renderContext);
}
xml.appendEndTag("ui:multiselectpair");
} | java | @Override
public void doRender(final WComponent component, final WebXmlRenderContext renderContext) {
WMultiSelectPair multiSelectPair = (WMultiSelectPair) component;
XmlStringBuilder xml = renderContext.getWriter();
boolean readOnly = multiSelectPair.isReadOnly();
xml.appendTagOpen("ui:multiselectpair");
xml.appendAttribute("id", component.getId());
xml.appendOptionalAttribute("class", component.getHtmlClass());
xml.appendOptionalAttribute("track", component.isTracking(), "true");
xml.appendOptionalAttribute("hidden", multiSelectPair.isHidden(), "true");
if (readOnly) {
xml.appendAttribute("readOnly", "true");
} else {
int rows = multiSelectPair.getRows();
int min = multiSelectPair.getMinSelect();
int max = multiSelectPair.getMaxSelect();
xml.appendAttribute("size", rows < 2 ? WMultiSelectPair.DEFAULT_ROWS : rows);
xml.appendOptionalAttribute("disabled", multiSelectPair.isDisabled(), "true");
xml.appendOptionalAttribute("required", multiSelectPair.isMandatory(), "true");
xml.appendOptionalAttribute("shuffle", multiSelectPair.isShuffle(), "true");
xml.appendOptionalAttribute("fromListName", multiSelectPair.getAvailableListName());
xml.appendOptionalAttribute("toListName", multiSelectPair.getSelectedListName());
xml.appendOptionalAttribute("accessibleText", multiSelectPair.getAccessibleText());
xml.appendOptionalAttribute("min", min > 0, min);
xml.appendOptionalAttribute("max", max > 0, max);
}
xml.appendClose();
// Options
List<?> options = multiSelectPair.getOptions();
boolean renderSelectionsOnly = readOnly;
if (options != null) {
if (multiSelectPair.isShuffle()) {
// We need to render the selected options in order
renderOrderedOptions(multiSelectPair, options, 0, xml, renderSelectionsOnly);
} else {
renderUnorderedOptions(multiSelectPair, options, 0, xml, renderSelectionsOnly);
}
}
if (!readOnly) {
DiagnosticRenderUtil.renderDiagnostics(multiSelectPair, renderContext);
}
xml.appendEndTag("ui:multiselectpair");
} | [
"@",
"Override",
"public",
"void",
"doRender",
"(",
"final",
"WComponent",
"component",
",",
"final",
"WebXmlRenderContext",
"renderContext",
")",
"{",
"WMultiSelectPair",
"multiSelectPair",
"=",
"(",
"WMultiSelectPair",
")",
"component",
";",
"XmlStringBuilder",
"xml... | Paints the given WMultiSelectPair.
@param component the WMultiSelectPair to paint.
@param renderContext the RenderContext to paint to. | [
"Paints",
"the",
"given",
"WMultiSelectPair",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WMultiSelectPairRenderer.java#L29-L75 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/ui/SeaGlassTableUI.java | SeaGlassTableUI.forceInstallRenderer | public static void forceInstallRenderer(JTable table, Class objectClass) {
if (table.getUI() instanceof SeaGlassTableUI) {
((SeaGlassTableUI) table.getUI()).forceInstallRenderer(objectClass);
}
} | java | public static void forceInstallRenderer(JTable table, Class objectClass) {
if (table.getUI() instanceof SeaGlassTableUI) {
((SeaGlassTableUI) table.getUI()).forceInstallRenderer(objectClass);
}
} | [
"public",
"static",
"void",
"forceInstallRenderer",
"(",
"JTable",
"table",
",",
"Class",
"objectClass",
")",
"{",
"if",
"(",
"table",
".",
"getUI",
"(",
")",
"instanceof",
"SeaGlassTableUI",
")",
"{",
"(",
"(",
"SeaGlassTableUI",
")",
"table",
".",
"getUI",... | Static wrapper around {@link forceInstallRenderer(Class objectClass)}.
@param table the table to install the renderer on.
@param objectClass the class to install the renderer on. | [
"Static",
"wrapper",
"around",
"{",
"@link",
"forceInstallRenderer",
"(",
"Class",
"objectClass",
")",
"}",
"."
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/ui/SeaGlassTableUI.java#L169-L173 |
dmfs/http-client-interfaces | src/org/dmfs/httpclientinterfaces/headers/impl/StringHeaderValueConverter.java | StringHeaderValueConverter.valueString | @Override
public String valueString(String headerValue)
{
// make sure the value is valid
for (int i = 0, count = headerValue.length(); i < count; ++i)
{
char c = headerValue.charAt(i);
if ((c < 0x20 || c > 0xff) && c != 0x09)
{
throw new IllegalArgumentException(String.format("String '%s' contains non-printable or non-ASCII characters, which is not allowed in headers",
headerValue));
}
}
return headerValue;
} | java | @Override
public String valueString(String headerValue)
{
// make sure the value is valid
for (int i = 0, count = headerValue.length(); i < count; ++i)
{
char c = headerValue.charAt(i);
if ((c < 0x20 || c > 0xff) && c != 0x09)
{
throw new IllegalArgumentException(String.format("String '%s' contains non-printable or non-ASCII characters, which is not allowed in headers",
headerValue));
}
}
return headerValue;
} | [
"@",
"Override",
"public",
"String",
"valueString",
"(",
"String",
"headerValue",
")",
"{",
"// make sure the value is valid",
"for",
"(",
"int",
"i",
"=",
"0",
",",
"count",
"=",
"headerValue",
".",
"length",
"(",
")",
";",
"i",
"<",
"count",
";",
"++",
... | {@inheritDoc}
<p />
The given headerValue must not contain any characters that are not allowed in headers. Basically that means only characters in the ASCII range 0x20-0xff
and the tab character (0x09) are allowed.
<pre>
field-value = *( field-content / obs-fold )
field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
field-vchar = VCHAR / obs-text
obs-fold = CRLF 1*( SP / HTAB )
; obsolete line folding
; see Section 3.2.4
VCHAR = %x21-7E
; visible (printing) characters
obs-text = %x80-FF
</pre> | [
"{",
"@inheritDoc",
"}",
"<p",
"/",
">",
"The",
"given",
"headerValue",
"must",
"not",
"contain",
"any",
"characters",
"that",
"are",
"not",
"allowed",
"in",
"headers",
".",
"Basically",
"that",
"means",
"only",
"characters",
"in",
"the",
"ASCII",
"range",
... | train | https://github.com/dmfs/http-client-interfaces/blob/10896c71270ccaf32ac4ed5d706dfa0001fd3862/src/org/dmfs/httpclientinterfaces/headers/impl/StringHeaderValueConverter.java#L60-L74 |
lukas-krecan/JsonUnit | json-unit/src/main/java/net/javacrumbs/jsonunit/JsonMatchers.java | JsonMatchers.jsonStringPartEquals | public static ConfigurableJsonMatcher<String> jsonStringPartEquals(String path, Object expected) {
return jsonPartEquals(path, expected);
} | java | public static ConfigurableJsonMatcher<String> jsonStringPartEquals(String path, Object expected) {
return jsonPartEquals(path, expected);
} | [
"public",
"static",
"ConfigurableJsonMatcher",
"<",
"String",
">",
"jsonStringPartEquals",
"(",
"String",
"path",
",",
"Object",
"expected",
")",
"{",
"return",
"jsonPartEquals",
"(",
"path",
",",
"expected",
")",
";",
"}"
] | Is the part of the JSON equivalent?
<p/>
This method exist only for those cases, when you need to use it as Matcher<String> and Java refuses to
do the type inference correctly. | [
"Is",
"the",
"part",
"of",
"the",
"JSON",
"equivalent?",
"<p",
"/",
">",
"This",
"method",
"exist",
"only",
"for",
"those",
"cases",
"when",
"you",
"need",
"to",
"use",
"it",
"as",
"Matcher<",
";",
"String>",
";",
"and",
"Java",
"refuses",
"to",
"d... | train | https://github.com/lukas-krecan/JsonUnit/blob/2b12ed792e8dd787bddd6f3b8eb2325737435791/json-unit/src/main/java/net/javacrumbs/jsonunit/JsonMatchers.java#L90-L92 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/resource/ResourceUtil.java | ResourceUtil.getResource | public static URL getResource(String resource, Class<?> baseClass) {
return (null != baseClass) ? baseClass.getResource(resource) : ClassLoaderUtil.getClassLoader().getResource(resource);
} | java | public static URL getResource(String resource, Class<?> baseClass) {
return (null != baseClass) ? baseClass.getResource(resource) : ClassLoaderUtil.getClassLoader().getResource(resource);
} | [
"public",
"static",
"URL",
"getResource",
"(",
"String",
"resource",
",",
"Class",
"<",
"?",
">",
"baseClass",
")",
"{",
"return",
"(",
"null",
"!=",
"baseClass",
")",
"?",
"baseClass",
".",
"getResource",
"(",
"resource",
")",
":",
"ClassLoaderUtil",
".",... | 获得资源相对路径对应的URL
@param resource 资源相对路径
@param baseClass 基准Class,获得的相对路径相对于此Class所在路径,如果为{@code null}则相对ClassPath
@return {@link URL} | [
"获得资源相对路径对应的URL"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/resource/ResourceUtil.java#L159-L161 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/util/NodeLocatorHelper.java | NodeLocatorHelper.replicaNodeForId | public InetAddress replicaNodeForId(final String id, int replicaNum) {
if (replicaNum < 1 || replicaNum > 3) {
throw new IllegalArgumentException("Replica number must be between 1 and 3.");
}
BucketConfig config = bucketConfig.get();
if (config instanceof CouchbaseBucketConfig) {
CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
int partitionId = (int) hashId(id) & cbc.numberOfPartitions() - 1;
int nodeId = cbc.nodeIndexForReplica(partitionId, replicaNum - 1, false);
if (nodeId == -1) {
throw new IllegalStateException("No partition assigned to node for Document ID: " + id);
}
if (nodeId == -2) {
throw new IllegalStateException("Replica not configured for this bucket.");
}
try {
return InetAddress.getByName(cbc.nodeAtIndex(nodeId).hostname().address());
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
} else {
throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
}
} | java | public InetAddress replicaNodeForId(final String id, int replicaNum) {
if (replicaNum < 1 || replicaNum > 3) {
throw new IllegalArgumentException("Replica number must be between 1 and 3.");
}
BucketConfig config = bucketConfig.get();
if (config instanceof CouchbaseBucketConfig) {
CouchbaseBucketConfig cbc = (CouchbaseBucketConfig) config;
int partitionId = (int) hashId(id) & cbc.numberOfPartitions() - 1;
int nodeId = cbc.nodeIndexForReplica(partitionId, replicaNum - 1, false);
if (nodeId == -1) {
throw new IllegalStateException("No partition assigned to node for Document ID: " + id);
}
if (nodeId == -2) {
throw new IllegalStateException("Replica not configured for this bucket.");
}
try {
return InetAddress.getByName(cbc.nodeAtIndex(nodeId).hostname().address());
} catch (UnknownHostException e) {
throw new IllegalStateException(e);
}
} else {
throw new UnsupportedOperationException("Bucket type not supported: " + config.getClass().getName());
}
} | [
"public",
"InetAddress",
"replicaNodeForId",
"(",
"final",
"String",
"id",
",",
"int",
"replicaNum",
")",
"{",
"if",
"(",
"replicaNum",
"<",
"1",
"||",
"replicaNum",
">",
"3",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Replica number must be b... | Returns the target replica node {@link InetAddress} for a given document ID and replica number on the bucket.
@param id the document id to convert.
@param replicaNum the replica number.
@return the node for the given document id. | [
"Returns",
"the",
"target",
"replica",
"node",
"{",
"@link",
"InetAddress",
"}",
"for",
"a",
"given",
"document",
"ID",
"and",
"replica",
"number",
"on",
"the",
"bucket",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/util/NodeLocatorHelper.java#L141-L166 |
sinetja/sinetja | src/main/java/sinetja/Response.java | Response.respondJsonP | public ChannelFuture respondJsonP(Object ref, String function) throws Exception {
final String json = jsonObjectMapper.writeValueAsString(ref);
final String text = function + "(" + json + ");\r\n";
return respondJs(text);
} | java | public ChannelFuture respondJsonP(Object ref, String function) throws Exception {
final String json = jsonObjectMapper.writeValueAsString(ref);
final String text = function + "(" + json + ");\r\n";
return respondJs(text);
} | [
"public",
"ChannelFuture",
"respondJsonP",
"(",
"Object",
"ref",
",",
"String",
"function",
")",
"throws",
"Exception",
"{",
"final",
"String",
"json",
"=",
"jsonObjectMapper",
".",
"writeValueAsString",
"(",
"ref",
")",
";",
"final",
"String",
"text",
"=",
"f... | Converts the given Java object to JSON object using Jackson ObjectMapper,
wraps it with the given JavaScript function name, and responds.
If you already have a JSON text, thus no conversion is needed, use respondJsonPText.
<p>
Content-Type header is set to "application/javascript". | [
"Converts",
"the",
"given",
"Java",
"object",
"to",
"JSON",
"object",
"using",
"Jackson",
"ObjectMapper",
"wraps",
"it",
"with",
"the",
"given",
"JavaScript",
"function",
"name",
"and",
"responds",
".",
"If",
"you",
"already",
"have",
"a",
"JSON",
"text",
"t... | train | https://github.com/sinetja/sinetja/blob/eec94dba55ec28263e3503fcdb33532282134775/src/main/java/sinetja/Response.java#L234-L238 |
netty/netty | codec/src/main/java/io/netty/handler/codec/compression/Bzip2DivSufSort.java | Bzip2DivSufSort.bwt | public int bwt() {
final int[] SA = this.SA;
final byte[] T = this.T;
final int n = this.n;
final int[] bucketA = new int[BUCKET_A_SIZE];
final int[] bucketB = new int[BUCKET_B_SIZE];
if (n == 0) {
return 0;
}
if (n == 1) {
SA[0] = T[0];
return 0;
}
int m = sortTypeBstar(bucketA, bucketB);
if (0 < m) {
return constructBWT(bucketA, bucketB);
}
return 0;
} | java | public int bwt() {
final int[] SA = this.SA;
final byte[] T = this.T;
final int n = this.n;
final int[] bucketA = new int[BUCKET_A_SIZE];
final int[] bucketB = new int[BUCKET_B_SIZE];
if (n == 0) {
return 0;
}
if (n == 1) {
SA[0] = T[0];
return 0;
}
int m = sortTypeBstar(bucketA, bucketB);
if (0 < m) {
return constructBWT(bucketA, bucketB);
}
return 0;
} | [
"public",
"int",
"bwt",
"(",
")",
"{",
"final",
"int",
"[",
"]",
"SA",
"=",
"this",
".",
"SA",
";",
"final",
"byte",
"[",
"]",
"T",
"=",
"this",
".",
"T",
";",
"final",
"int",
"n",
"=",
"this",
".",
"n",
";",
"final",
"int",
"[",
"]",
"buck... | Performs a Burrows Wheeler Transform on the input array.
@return the index of the first character of the input array within the output array | [
"Performs",
"a",
"Burrows",
"Wheeler",
"Transform",
"on",
"the",
"input",
"array",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec/src/main/java/io/netty/handler/codec/compression/Bzip2DivSufSort.java#L2095-L2116 |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/service/FullKeyMapper.java | FullKeyMapper.byteBuffer | public ByteBuffer byteBuffer(DecoratedKey partitionKey, CellName cellName) {
return type.builder().add(partitionKey.getKey()).add(cellName.toByteBuffer()).build();
} | java | public ByteBuffer byteBuffer(DecoratedKey partitionKey, CellName cellName) {
return type.builder().add(partitionKey.getKey()).add(cellName.toByteBuffer()).build();
} | [
"public",
"ByteBuffer",
"byteBuffer",
"(",
"DecoratedKey",
"partitionKey",
",",
"CellName",
"cellName",
")",
"{",
"return",
"type",
".",
"builder",
"(",
")",
".",
"add",
"(",
"partitionKey",
".",
"getKey",
"(",
")",
")",
".",
"add",
"(",
"cellName",
".",
... | Returns the {@link ByteBuffer} representation of the full row key formed by the specified partition key and the
clustering key.
@param partitionKey A partition key.
@param cellName A clustering key.
@return The {@link ByteBuffer} representation of the full row key formed by the specified key pair. | [
"Returns",
"the",
"{",
"@link",
"ByteBuffer",
"}",
"representation",
"of",
"the",
"full",
"row",
"key",
"formed",
"by",
"the",
"specified",
"partition",
"key",
"and",
"the",
"clustering",
"key",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/FullKeyMapper.java#L77-L79 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/JobClient.java | JobClient.validateNumberOfTasks | private void validateNumberOfTasks(int splits, int reduceTasks, JobConf conf)
throws IOException {
int maxTasks = conf.getInt("mapred.jobtracker.maxtasks.per.job", -1);
int totalTasks = splits + reduceTasks;
if ((maxTasks!= -1) && (totalTasks > maxTasks)) {
throw new IOException(
"The number of tasks for this job " +
totalTasks +
" exceeds the configured limit " + maxTasks);
}
} | java | private void validateNumberOfTasks(int splits, int reduceTasks, JobConf conf)
throws IOException {
int maxTasks = conf.getInt("mapred.jobtracker.maxtasks.per.job", -1);
int totalTasks = splits + reduceTasks;
if ((maxTasks!= -1) && (totalTasks > maxTasks)) {
throw new IOException(
"The number of tasks for this job " +
totalTasks +
" exceeds the configured limit " + maxTasks);
}
} | [
"private",
"void",
"validateNumberOfTasks",
"(",
"int",
"splits",
",",
"int",
"reduceTasks",
",",
"JobConf",
"conf",
")",
"throws",
"IOException",
"{",
"int",
"maxTasks",
"=",
"conf",
".",
"getInt",
"(",
"\"mapred.jobtracker.maxtasks.per.job\"",
",",
"-",
"1",
"... | JobTrcker applies this limit against the sum of mappers and reducers. | [
"JobTrcker",
"applies",
"this",
"limit",
"against",
"the",
"sum",
"of",
"mappers",
"and",
"reducers",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/JobClient.java#L1353-L1364 |
paypal/SeLion | server/src/main/java/com/paypal/selion/utils/SauceLabsRestApi.java | SauceLabsRestApi.isAuthenticated | public synchronized boolean isAuthenticated(String username, String apiKey) {
LOGGER.entering();
final String key = username + ":" + apiKey;
final String authKey = new String(Base64.encodeBase64(key.getBytes()));
if (accountCache.containsKey(md5(authKey))) {
final boolean authenticated = accountCache.get(md5(authKey));
LOGGER.exiting(authenticated);
return authenticated;
}
SauceLabsHttpResponse response;
try {
final URL url = new URL(SauceConfigReader.getInstance().getSauceURL() + "/users/" + username);
response = doSauceRequest(url, authKey, sauceTimeout, 0);
if (response.getStatus() == HttpStatus.SC_OK) {
addToAccountCache(md5(authKey), true);
LOGGER.exiting(true);
return true;
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to communicate with sauce labs api.", e);
}
// TODO don't add to cache if sauce api is down
addToAccountCache(md5(authKey), false);
LOGGER.exiting(false);
return false;
} | java | public synchronized boolean isAuthenticated(String username, String apiKey) {
LOGGER.entering();
final String key = username + ":" + apiKey;
final String authKey = new String(Base64.encodeBase64(key.getBytes()));
if (accountCache.containsKey(md5(authKey))) {
final boolean authenticated = accountCache.get(md5(authKey));
LOGGER.exiting(authenticated);
return authenticated;
}
SauceLabsHttpResponse response;
try {
final URL url = new URL(SauceConfigReader.getInstance().getSauceURL() + "/users/" + username);
response = doSauceRequest(url, authKey, sauceTimeout, 0);
if (response.getStatus() == HttpStatus.SC_OK) {
addToAccountCache(md5(authKey), true);
LOGGER.exiting(true);
return true;
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Unable to communicate with sauce labs api.", e);
}
// TODO don't add to cache if sauce api is down
addToAccountCache(md5(authKey), false);
LOGGER.exiting(false);
return false;
} | [
"public",
"synchronized",
"boolean",
"isAuthenticated",
"(",
"String",
"username",
",",
"String",
"apiKey",
")",
"{",
"LOGGER",
".",
"entering",
"(",
")",
";",
"final",
"String",
"key",
"=",
"username",
"+",
"\":\"",
"+",
"apiKey",
";",
"final",
"String",
... | Determine if the account credentials specified are valid by calling the sauce rest api. Uses a local account
cache for credentials which have already been presented. Cached credentials expire when the cache reaches a size
of {@link SauceLabsRestApi#MAX_CACHE}
@param username
the user name
@param apiKey
the sauce labs api access key
@return <code>true</code> on success. <code>false</code> if unauthorized or unable to call sauce. | [
"Determine",
"if",
"the",
"account",
"credentials",
"specified",
"are",
"valid",
"by",
"calling",
"the",
"sauce",
"rest",
"api",
".",
"Uses",
"a",
"local",
"account",
"cache",
"for",
"credentials",
"which",
"have",
"already",
"been",
"presented",
".",
"Cached"... | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/server/src/main/java/com/paypal/selion/utils/SauceLabsRestApi.java#L217-L246 |
EdwardRaff/JSAT | JSAT/src/jsat/linear/RowColumnOps.java | RowColumnOps.divCol | public static void divCol(Matrix A, int j, double c)
{
divCol(A, j, 0, A.rows(), c);
} | java | public static void divCol(Matrix A, int j, double c)
{
divCol(A, j, 0, A.rows(), c);
} | [
"public",
"static",
"void",
"divCol",
"(",
"Matrix",
"A",
",",
"int",
"j",
",",
"double",
"c",
")",
"{",
"divCol",
"(",
"A",
",",
"j",
",",
"0",
",",
"A",
".",
"rows",
"(",
")",
",",
"c",
")",
";",
"}"
] | Updates the values of column <tt>j</tt> in the given matrix to be A[:,j] = A[:,j]/c
@param A the matrix to perform he update on
@param j the row to update
@param c the constant to divide each element by | [
"Updates",
"the",
"values",
"of",
"column",
"<tt",
">",
"j<",
"/",
"tt",
">",
"in",
"the",
"given",
"matrix",
"to",
"be",
"A",
"[",
":",
"j",
"]",
"=",
"A",
"[",
":",
"j",
"]",
"/",
"c"
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/linear/RowColumnOps.java#L244-L247 |
Azure/azure-sdk-for-java | labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java | LabAccountsInner.getByResourceGroupAsync | public Observable<LabAccountInner> getByResourceGroupAsync(String resourceGroupName, String labAccountName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, labAccountName, expand).map(new Func1<ServiceResponse<LabAccountInner>, LabAccountInner>() {
@Override
public LabAccountInner call(ServiceResponse<LabAccountInner> response) {
return response.body();
}
});
} | java | public Observable<LabAccountInner> getByResourceGroupAsync(String resourceGroupName, String labAccountName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, labAccountName, expand).map(new Func1<ServiceResponse<LabAccountInner>, LabAccountInner>() {
@Override
public LabAccountInner call(ServiceResponse<LabAccountInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"LabAccountInner",
">",
"getByResourceGroupAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"labAccountName",
",",
"String",
"expand",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"... | Get lab account.
@param resourceGroupName The name of the resource group.
@param labAccountName The name of the lab Account.
@param expand Specify the $expand query. Example: 'properties($expand=sizeConfiguration)'
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the LabAccountInner object | [
"Get",
"lab",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/labservices/resource-manager/v2018_10_15/src/main/java/com/microsoft/azure/management/labservices/v2018_10_15/implementation/LabAccountsInner.java#L713-L720 |
jeremylong/DependencyCheck | core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java | ConnectionFactory.createTables | private void createTables(Connection conn) throws DatabaseException {
LOGGER.debug("Creating database structure");
try (InputStream is = FileUtils.getResourceAsStream(DB_STRUCTURE_RESOURCE)) {
final String dbStructure = IOUtils.toString(is, StandardCharsets.UTF_8);
Statement statement = null;
try {
statement = conn.createStatement();
statement.execute(dbStructure);
} catch (SQLException ex) {
LOGGER.debug("", ex);
throw new DatabaseException("Unable to create database statement", ex);
} finally {
DBUtils.closeStatement(statement);
}
} catch (IOException ex) {
throw new DatabaseException("Unable to create database schema", ex);
}
} | java | private void createTables(Connection conn) throws DatabaseException {
LOGGER.debug("Creating database structure");
try (InputStream is = FileUtils.getResourceAsStream(DB_STRUCTURE_RESOURCE)) {
final String dbStructure = IOUtils.toString(is, StandardCharsets.UTF_8);
Statement statement = null;
try {
statement = conn.createStatement();
statement.execute(dbStructure);
} catch (SQLException ex) {
LOGGER.debug("", ex);
throw new DatabaseException("Unable to create database statement", ex);
} finally {
DBUtils.closeStatement(statement);
}
} catch (IOException ex) {
throw new DatabaseException("Unable to create database schema", ex);
}
} | [
"private",
"void",
"createTables",
"(",
"Connection",
"conn",
")",
"throws",
"DatabaseException",
"{",
"LOGGER",
".",
"debug",
"(",
"\"Creating database structure\"",
")",
";",
"try",
"(",
"InputStream",
"is",
"=",
"FileUtils",
".",
"getResourceAsStream",
"(",
"DB... | Creates the database structure (tables and indexes) to store the CVE
data.
@param conn the database connection
@throws DatabaseException thrown if there is a Database Exception | [
"Creates",
"the",
"database",
"structure",
"(",
"tables",
"and",
"indexes",
")",
"to",
"store",
"the",
"CVE",
"data",
"."
] | train | https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java#L317-L336 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java | SpiderTransaction.addTermIndexColumn | public void addTermIndexColumn(TableDefinition tableDef, DBObject dbObj, String fieldName, String term) {
addColumn(SpiderService.termsStoreName(tableDef),
SpiderService.termIndexRowKey(tableDef, dbObj, fieldName, term),
dbObj.getObjectID());
} | java | public void addTermIndexColumn(TableDefinition tableDef, DBObject dbObj, String fieldName, String term) {
addColumn(SpiderService.termsStoreName(tableDef),
SpiderService.termIndexRowKey(tableDef, dbObj, fieldName, term),
dbObj.getObjectID());
} | [
"public",
"void",
"addTermIndexColumn",
"(",
"TableDefinition",
"tableDef",
",",
"DBObject",
"dbObj",
",",
"String",
"fieldName",
",",
"String",
"term",
")",
"{",
"addColumn",
"(",
"SpiderService",
".",
"termsStoreName",
"(",
"tableDef",
")",
",",
"SpiderService",... | Index the given term by adding a Terms column for the given DBObject, field name,
and term. Non-sharded format:
<pre>
[field name]/[field value]> = {[object ID]:null}
</pre>
Term record for a sharded object:
<pre>
[shard number]/[field name]/[field value] = {[object ID]:null}
</pre>
@param dbObj DBObject that owns field.
@param fieldName Field name.
@param term Term being indexed. | [
"Index",
"the",
"given",
"term",
"by",
"adding",
"a",
"Terms",
"column",
"for",
"the",
"given",
"DBObject",
"field",
"name",
"and",
"term",
".",
"Non",
"-",
"sharded",
"format",
":",
"<pre",
">",
"[",
"field",
"name",
"]",
"/",
"[",
"field",
"value",
... | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java#L330-L334 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java | VirtualNetworkGatewaysInner.getByResourceGroup | public VirtualNetworkGatewayInner getByResourceGroup(String resourceGroupName, String virtualNetworkGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).toBlocking().single().body();
} | java | public VirtualNetworkGatewayInner getByResourceGroup(String resourceGroupName, String virtualNetworkGatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName).toBlocking().single().body();
} | [
"public",
"VirtualNetworkGatewayInner",
"getByResourceGroup",
"(",
"String",
"resourceGroupName",
",",
"String",
"virtualNetworkGatewayName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"virtualNetworkGatewayName",
")",
".",
... | Gets the specified virtual network gateway by resource group.
@param resourceGroupName The name of the resource group.
@param virtualNetworkGatewayName The name of the virtual network gateway.
@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 VirtualNetworkGatewayInner object if successful. | [
"Gets",
"the",
"specified",
"virtual",
"network",
"gateway",
"by",
"resource",
"group",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L376-L378 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/Stream.java | Stream.filterIndexed | @NotNull
public Stream<T> filterIndexed(@NotNull IndexedPredicate<? super T> predicate) {
return filterIndexed(0, 1, predicate);
} | java | @NotNull
public Stream<T> filterIndexed(@NotNull IndexedPredicate<? super T> predicate) {
return filterIndexed(0, 1, predicate);
} | [
"@",
"NotNull",
"public",
"Stream",
"<",
"T",
">",
"filterIndexed",
"(",
"@",
"NotNull",
"IndexedPredicate",
"<",
"?",
"super",
"T",
">",
"predicate",
")",
"{",
"return",
"filterIndexed",
"(",
"0",
",",
"1",
",",
"predicate",
")",
";",
"}"
] | Returns a {@code Stream} with elements that satisfy the given {@code IndexedPredicate}.
<p>This is an intermediate operation.
<p>Example:
<pre>
predicate: (index, value) -> (index + value) > 6
stream: [1, 2, 3, 4, 0, 11]
index: [0, 1, 2, 3, 4, 5]
sum: [1, 3, 5, 7, 4, 16]
filter: [ 7, 16]
result: [4, 11]
</pre>
@param predicate the {@code IndexedPredicate} used to filter elements
@return the new stream
@since 1.1.6 | [
"Returns",
"a",
"{",
"@code",
"Stream",
"}",
"with",
"elements",
"that",
"satisfy",
"the",
"given",
"{",
"@code",
"IndexedPredicate",
"}",
"."
] | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Stream.java#L613-L616 |
undertow-io/undertow | core/src/main/java/io/undertow/util/FlexBase64.java | FlexBase64.encodeString | public static String encodeString(ByteBuffer source, boolean wrap) {
return Encoder.encodeString(source, wrap, false);
} | java | public static String encodeString(ByteBuffer source, boolean wrap) {
return Encoder.encodeString(source, wrap, false);
} | [
"public",
"static",
"String",
"encodeString",
"(",
"ByteBuffer",
"source",
",",
"boolean",
"wrap",
")",
"{",
"return",
"Encoder",
".",
"encodeString",
"(",
"source",
",",
"wrap",
",",
"false",
")",
";",
"}"
] | Encodes a fixed and complete byte buffer into a Base64 String.
<p>This method is only useful for applications which require a String and have all data to be encoded up-front.
Note that byte arrays or buffers are almost always a better storage choice. They consume half the memory and
can be reused (modified). In other words, it is almost always better to use {@link #encodeBytes},
{@link #createEncoder}, or {@link #createEncoderOutputStream} instead.</p>
<pre><code>
// Encodes "hello"
FlexBase64.encodeString(ByteBuffer.wrap("hello".getBytes("US-ASCII")), false);
</code></pre>
@param source the byte buffer to encode from
@param wrap whether or not to wrap the output at 76 chars with CRLFs
@return a new String representing the Base64 output | [
"Encodes",
"a",
"fixed",
"and",
"complete",
"byte",
"buffer",
"into",
"a",
"Base64",
"String",
"."
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/util/FlexBase64.java#L232-L234 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/hash/MurmurHash3.java | MurmurHash3.getLong | private static long getLong(final int[] intArr, final int index, final int rem) {
long out = 0L;
for (int i = rem; i-- > 0;) { //i= 1,0
final int v = intArr[index + i];
out ^= (v & 0xFFFFFFFFL) << (i * 32); //equivalent to |=
}
return out;
} | java | private static long getLong(final int[] intArr, final int index, final int rem) {
long out = 0L;
for (int i = rem; i-- > 0;) { //i= 1,0
final int v = intArr[index + i];
out ^= (v & 0xFFFFFFFFL) << (i * 32); //equivalent to |=
}
return out;
} | [
"private",
"static",
"long",
"getLong",
"(",
"final",
"int",
"[",
"]",
"intArr",
",",
"final",
"int",
"index",
",",
"final",
"int",
"rem",
")",
"{",
"long",
"out",
"=",
"0L",
";",
"for",
"(",
"int",
"i",
"=",
"rem",
";",
"i",
"--",
">",
"0",
";... | Gets a long from the given int array starting at the given int array index and continuing for
remainder (rem) integers. The integers are extracted in little-endian order. There is no limit
checking.
@param intArr The given input int array.
@param index Zero-based index from the start of the int array.
@param rem Remainder integers. An integer in the range [1,2].
@return long | [
"Gets",
"a",
"long",
"from",
"the",
"given",
"int",
"array",
"starting",
"at",
"the",
"given",
"int",
"array",
"index",
"and",
"continuing",
"for",
"remainder",
"(",
"rem",
")",
"integers",
".",
"The",
"integers",
"are",
"extracted",
"in",
"little",
"-",
... | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/hash/MurmurHash3.java#L346-L353 |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java | JsonRpcClient.invokeAndReadResponse | @SuppressWarnings("unchecked")
public <T> T invokeAndReadResponse(String methodName, Object argument, Class<T> clazz, OutputStream output, InputStream input) throws Throwable {
return (T) invokeAndReadResponse(methodName, argument, Type.class.cast(clazz), output, input);
} | java | @SuppressWarnings("unchecked")
public <T> T invokeAndReadResponse(String methodName, Object argument, Class<T> clazz, OutputStream output, InputStream input) throws Throwable {
return (T) invokeAndReadResponse(methodName, argument, Type.class.cast(clazz), output, input);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
">",
"T",
"invokeAndReadResponse",
"(",
"String",
"methodName",
",",
"Object",
"argument",
",",
"Class",
"<",
"T",
">",
"clazz",
",",
"OutputStream",
"output",
",",
"InputStream",
"input",... | Invokes the given method on the remote service
passing the given arguments, a generated id and reads
a response.
@param methodName the method to invoke
@param argument the argument to pass to the method
@param clazz the expected return type
@param output the {@link OutputStream} to write to
@param input the {@link InputStream} to read from
@param <T> the expected return type
@return the returned Object
@throws Throwable on error
@see #writeRequest(String, Object, OutputStream, String) | [
"Invokes",
"the",
"given",
"method",
"on",
"the",
"remote",
"service",
"passing",
"the",
"given",
"arguments",
"a",
"generated",
"id",
"and",
"reads",
"a",
"response",
"."
] | train | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcClient.java#L119-L122 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.recoverDeletedStorageAccountAsync | public Observable<StorageBundle> recoverDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return recoverDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() {
@Override
public StorageBundle call(ServiceResponse<StorageBundle> response) {
return response.body();
}
});
} | java | public Observable<StorageBundle> recoverDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return recoverDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() {
@Override
public StorageBundle call(ServiceResponse<StorageBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StorageBundle",
">",
"recoverDeletedStorageAccountAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"storageAccountName",
")",
"{",
"return",
"recoverDeletedStorageAccountWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"storageAccountName"... | Recovers the deleted storage account.
Recovers the deleted storage account in the specified vault. This operation can only be performed on a soft-delete enabled vault. This operation requires the storage/recover permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageBundle object | [
"Recovers",
"the",
"deleted",
"storage",
"account",
".",
"Recovers",
"the",
"deleted",
"storage",
"account",
"in",
"the",
"specified",
"vault",
".",
"This",
"operation",
"can",
"only",
"be",
"performed",
"on",
"a",
"soft",
"-",
"delete",
"enabled",
"vault",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9459-L9466 |
foundation-runtime/service-directory | 2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java | ServiceDirectoryConfig.getFloat | public float getFloat(String name, float defaultVal){
if(this.configuration.containsKey(name)){
return this.configuration.getFloat(name);
} else {
return defaultVal;
}
} | java | public float getFloat(String name, float defaultVal){
if(this.configuration.containsKey(name)){
return this.configuration.getFloat(name);
} else {
return defaultVal;
}
} | [
"public",
"float",
"getFloat",
"(",
"String",
"name",
",",
"float",
"defaultVal",
")",
"{",
"if",
"(",
"this",
".",
"configuration",
".",
"containsKey",
"(",
"name",
")",
")",
"{",
"return",
"this",
".",
"configuration",
".",
"getFloat",
"(",
"name",
")"... | Get the property object as float, or return defaultVal if property is not defined.
@param name
property name.
@param defaultVal
default property value.
@return
property value as float, return defaultVal if property is undefined. | [
"Get",
"the",
"property",
"object",
"as",
"float",
"or",
"return",
"defaultVal",
"if",
"property",
"is",
"not",
"defined",
"."
] | train | https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/config/ServiceDirectoryConfig.java#L177-L183 |
CenturyLinkCloud/mdw | mdw-services/src/com/centurylink/mdw/services/task/TaskWorkflowHelper.java | TaskWorkflowHelper.updateDue | void updateDue(Instant due, String cuid, String comment)
throws ServiceException, DataAccessException {
boolean hasOldSlaInstance;
EventServices eventManager = ServiceLocator.getEventServices();
EventInstance event = eventManager.getEventInstance(ScheduledEvent.SPECIAL_EVENT_PREFIX + "TaskDueDate." + taskInstance.getId());
boolean isEventExist = event == null ? false : true;
hasOldSlaInstance = !isEventExist;
Map<String,Object> changes = new HashMap<String,Object>();
changes.put("DUE_DATE", Date.from(due));
changes.put("COMMENTS", comment);
TaskDataAccess dataAccess = new TaskDataAccess();
dataAccess.updateTaskInstance(taskInstance.getTaskInstanceId(), changes, false);
if (due == null) {
unscheduleTaskSlaEvent();
}
else {
String alertIntervalString = getTemplate().getAttribute(TaskAttributeConstant.ALERT_INTERVAL);
int alertInterval = StringHelper.isEmpty(alertIntervalString)?0:Integer.parseInt(alertIntervalString);
scheduleTaskSlaEvent(Date.from(due), alertInterval, !hasOldSlaInstance);
}
auditLog(UserAction.Action.Change.toString(), cuid, null, "change due date / comments");
} | java | void updateDue(Instant due, String cuid, String comment)
throws ServiceException, DataAccessException {
boolean hasOldSlaInstance;
EventServices eventManager = ServiceLocator.getEventServices();
EventInstance event = eventManager.getEventInstance(ScheduledEvent.SPECIAL_EVENT_PREFIX + "TaskDueDate." + taskInstance.getId());
boolean isEventExist = event == null ? false : true;
hasOldSlaInstance = !isEventExist;
Map<String,Object> changes = new HashMap<String,Object>();
changes.put("DUE_DATE", Date.from(due));
changes.put("COMMENTS", comment);
TaskDataAccess dataAccess = new TaskDataAccess();
dataAccess.updateTaskInstance(taskInstance.getTaskInstanceId(), changes, false);
if (due == null) {
unscheduleTaskSlaEvent();
}
else {
String alertIntervalString = getTemplate().getAttribute(TaskAttributeConstant.ALERT_INTERVAL);
int alertInterval = StringHelper.isEmpty(alertIntervalString)?0:Integer.parseInt(alertIntervalString);
scheduleTaskSlaEvent(Date.from(due), alertInterval, !hasOldSlaInstance);
}
auditLog(UserAction.Action.Change.toString(), cuid, null, "change due date / comments");
} | [
"void",
"updateDue",
"(",
"Instant",
"due",
",",
"String",
"cuid",
",",
"String",
"comment",
")",
"throws",
"ServiceException",
",",
"DataAccessException",
"{",
"boolean",
"hasOldSlaInstance",
";",
"EventServices",
"eventManager",
"=",
"ServiceLocator",
".",
"getEve... | Updates the due date for a task instance.
The method should only be called in summary (or summary-and-detail) task manager. | [
"Updates",
"the",
"due",
"date",
"for",
"a",
"task",
"instance",
".",
"The",
"method",
"should",
"only",
"be",
"called",
"in",
"summary",
"(",
"or",
"summary",
"-",
"and",
"-",
"detail",
")",
"task",
"manager",
"."
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-services/src/com/centurylink/mdw/services/task/TaskWorkflowHelper.java#L327-L348 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/Graphics.java | Graphics.drawOval | public void drawOval(float x1, float y1, float width, float height) {
drawOval(x1, y1, width, height, DEFAULT_SEGMENTS);
} | java | public void drawOval(float x1, float y1, float width, float height) {
drawOval(x1, y1, width, height, DEFAULT_SEGMENTS);
} | [
"public",
"void",
"drawOval",
"(",
"float",
"x1",
",",
"float",
"y1",
",",
"float",
"width",
",",
"float",
"height",
")",
"{",
"drawOval",
"(",
"x1",
",",
"y1",
",",
"width",
",",
"height",
",",
"DEFAULT_SEGMENTS",
")",
";",
"}"
] | Draw an oval to the canvas
@param x1
The x coordinate of the top left corner of a box containing
the oval
@param y1
The y coordinate of the top left corner of a box containing
the oval
@param width
The width of the oval
@param height
The height of the oval | [
"Draw",
"an",
"oval",
"to",
"the",
"canvas"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/Graphics.java#L915-L917 |
jbundle/webapp | base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java | BaseOsgiServlet.service | public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
boolean fileFound = sendResourceFile(req, resp);
if (!fileFound)
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
// super.service(req, resp);
} | java | public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
boolean fileFound = sendResourceFile(req, resp);
if (!fileFound)
resp.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found");
// super.service(req, resp);
} | [
"public",
"void",
"service",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"boolean",
"fileFound",
"=",
"sendResourceFile",
"(",
"req",
",",
"resp",
")",
";",
"if",
"(",
"!",
"... | process an HTML get or post.
@exception ServletException From inherited class.
@exception IOException From inherited class. | [
"process",
"an",
"HTML",
"get",
"or",
"post",
"."
] | train | https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java#L54-L61 |
lagom/lagom | service/javadsl/client/src/main/java/com/lightbend/lagom/javadsl/client/CircuitBreakingServiceLocator.java | CircuitBreakingServiceLocator.doWithServiceImpl | protected <T> CompletionStage<Optional<T>> doWithServiceImpl(String name, Descriptor.Call<?, ?> serviceCall, Function<URI, CompletionStage<T>> block) {
return locate(name, serviceCall).thenCompose(uri -> {
return uri
.map(u -> block.apply(u).thenApply(Optional::of))
.orElseGet(() -> CompletableFuture.completedFuture(Optional.empty()));
});
} | java | protected <T> CompletionStage<Optional<T>> doWithServiceImpl(String name, Descriptor.Call<?, ?> serviceCall, Function<URI, CompletionStage<T>> block) {
return locate(name, serviceCall).thenCompose(uri -> {
return uri
.map(u -> block.apply(u).thenApply(Optional::of))
.orElseGet(() -> CompletableFuture.completedFuture(Optional.empty()));
});
} | [
"protected",
"<",
"T",
">",
"CompletionStage",
"<",
"Optional",
"<",
"T",
">",
">",
"doWithServiceImpl",
"(",
"String",
"name",
",",
"Descriptor",
".",
"Call",
"<",
"?",
",",
"?",
">",
"serviceCall",
",",
"Function",
"<",
"URI",
",",
"CompletionStage",
"... | Do the given block with the given service looked up.
This is invoked by {@link #doWithService(String, Descriptor.Call, Function)}, after wrapping the passed in block
in a circuit breaker if configured to do so.
The default implementation just delegates to the {@link #locate(String, Descriptor.Call)} method, but this method
can be overridden if the service locator wants to inject other behaviour after the service call is complete.
@param name The service name.
@param serviceCall The service call that needs the service lookup.
@param block A block of code that will use the looked up service, typically, to make a call on that service.
@return A future of the result of the block, if the service lookup was successful. | [
"Do",
"the",
"given",
"block",
"with",
"the",
"given",
"service",
"looked",
"up",
"."
] | train | https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/client/src/main/java/com/lightbend/lagom/javadsl/client/CircuitBreakingServiceLocator.java#L59-L65 |
alkacon/opencms-core | src/org/opencms/ugc/CmsUgcSession.java | CmsUgcSession.loadXmlContent | public CmsResource loadXmlContent(String fileName) throws CmsUgcException {
checkNotFinished();
checkEditResourceNotSet();
if (fileName.contains("/")) {
String message = Messages.get().container(Messages.ERR_INVALID_FILE_NAME_TO_LOAD_1, fileName).key(
getCmsObject().getRequestContext().getLocale());
throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMisc, message);
}
try {
String contentSitePath = m_cms.getRequestContext().removeSiteRoot(
m_configuration.getContentParentFolder().getRootPath());
String path = CmsStringUtil.joinPaths(contentSitePath, fileName);
m_editResource = m_cms.readResource(path);
CmsLock lock = m_cms.getLock(m_editResource);
if (!lock.isOwnedBy(m_cms.getRequestContext().getCurrentUser())) {
m_cms.lockResourceTemporary(m_editResource);
}
return m_editResource;
} catch (CmsException e) {
throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage());
}
} | java | public CmsResource loadXmlContent(String fileName) throws CmsUgcException {
checkNotFinished();
checkEditResourceNotSet();
if (fileName.contains("/")) {
String message = Messages.get().container(Messages.ERR_INVALID_FILE_NAME_TO_LOAD_1, fileName).key(
getCmsObject().getRequestContext().getLocale());
throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMisc, message);
}
try {
String contentSitePath = m_cms.getRequestContext().removeSiteRoot(
m_configuration.getContentParentFolder().getRootPath());
String path = CmsStringUtil.joinPaths(contentSitePath, fileName);
m_editResource = m_cms.readResource(path);
CmsLock lock = m_cms.getLock(m_editResource);
if (!lock.isOwnedBy(m_cms.getRequestContext().getCurrentUser())) {
m_cms.lockResourceTemporary(m_editResource);
}
return m_editResource;
} catch (CmsException e) {
throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMisc, e.getLocalizedMessage());
}
} | [
"public",
"CmsResource",
"loadXmlContent",
"(",
"String",
"fileName",
")",
"throws",
"CmsUgcException",
"{",
"checkNotFinished",
"(",
")",
";",
"checkEditResourceNotSet",
"(",
")",
";",
"if",
"(",
"fileName",
".",
"contains",
"(",
"\"/\"",
")",
")",
"{",
"Stri... | Loads the existing edit resource.<p>
@param fileName the resource file name
@return the edit resource
@throws CmsUgcException if reading the resource fails | [
"Loads",
"the",
"existing",
"edit",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ugc/CmsUgcSession.java#L454-L476 |
atomix/atomix | protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/MemberSelectorManager.java | MemberSelectorManager.createSelector | public MemberSelector createSelector(CommunicationStrategy selectionStrategy) {
MemberSelector selector = new MemberSelector(leader, members, selectionStrategy, this);
selectors.add(selector);
return selector;
} | java | public MemberSelector createSelector(CommunicationStrategy selectionStrategy) {
MemberSelector selector = new MemberSelector(leader, members, selectionStrategy, this);
selectors.add(selector);
return selector;
} | [
"public",
"MemberSelector",
"createSelector",
"(",
"CommunicationStrategy",
"selectionStrategy",
")",
"{",
"MemberSelector",
"selector",
"=",
"new",
"MemberSelector",
"(",
"leader",
",",
"members",
",",
"selectionStrategy",
",",
"this",
")",
";",
"selectors",
".",
"... | Creates a new address selector.
@param selectionStrategy The server selection strategy.
@return A new address selector. | [
"Creates",
"a",
"new",
"address",
"selector",
"."
] | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/session/impl/MemberSelectorManager.java#L80-L84 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/QuerySnapshot.java | QuerySnapshot.withDocuments | public static QuerySnapshot withDocuments(
final Query query, Timestamp readTime, final List<QueryDocumentSnapshot> documents) {
return new QuerySnapshot(query, readTime) {
volatile List<DocumentChange> documentChanges;
@Nonnull
@Override
public List<QueryDocumentSnapshot> getDocuments() {
return Collections.unmodifiableList(documents);
}
@Nonnull
@Override
public List<DocumentChange> getDocumentChanges() {
if (documentChanges == null) {
synchronized (documents) {
if (documentChanges == null) {
documentChanges = new ArrayList<>();
for (int i = 0; i < documents.size(); ++i) {
documentChanges.add(new DocumentChange(documents.get(i), Type.ADDED, -1, i));
}
}
}
}
return Collections.unmodifiableList(documentChanges);
}
@Override
public int size() {
return documents.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QuerySnapshot that = (QuerySnapshot) o;
return Objects.equals(query, that.query)
&& Objects.equals(this.size(), that.size())
&& Objects.equals(this.getDocuments(), that.getDocuments());
}
@Override
public int hashCode() {
return Objects.hash(query, this.getDocuments());
}
};
} | java | public static QuerySnapshot withDocuments(
final Query query, Timestamp readTime, final List<QueryDocumentSnapshot> documents) {
return new QuerySnapshot(query, readTime) {
volatile List<DocumentChange> documentChanges;
@Nonnull
@Override
public List<QueryDocumentSnapshot> getDocuments() {
return Collections.unmodifiableList(documents);
}
@Nonnull
@Override
public List<DocumentChange> getDocumentChanges() {
if (documentChanges == null) {
synchronized (documents) {
if (documentChanges == null) {
documentChanges = new ArrayList<>();
for (int i = 0; i < documents.size(); ++i) {
documentChanges.add(new DocumentChange(documents.get(i), Type.ADDED, -1, i));
}
}
}
}
return Collections.unmodifiableList(documentChanges);
}
@Override
public int size() {
return documents.size();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
QuerySnapshot that = (QuerySnapshot) o;
return Objects.equals(query, that.query)
&& Objects.equals(this.size(), that.size())
&& Objects.equals(this.getDocuments(), that.getDocuments());
}
@Override
public int hashCode() {
return Objects.hash(query, this.getDocuments());
}
};
} | [
"public",
"static",
"QuerySnapshot",
"withDocuments",
"(",
"final",
"Query",
"query",
",",
"Timestamp",
"readTime",
",",
"final",
"List",
"<",
"QueryDocumentSnapshot",
">",
"documents",
")",
"{",
"return",
"new",
"QuerySnapshot",
"(",
"query",
",",
"readTime",
"... | Creates a new QuerySnapshot representing the results of a Query with added documents. | [
"Creates",
"a",
"new",
"QuerySnapshot",
"representing",
"the",
"results",
"of",
"a",
"Query",
"with",
"added",
"documents",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-firestore/src/main/java/com/google/cloud/firestore/QuerySnapshot.java#L43-L94 |
datacleaner/DataCleaner | desktop/ui/src/main/java/org/datacleaner/panels/result/ProgressInformationPanel.java | ProgressInformationPanel.updateProgress | public void updateProgress(final Table table, final int currentRow) {
final TableProgressInformationPanel tableProgressInformationPanel = getTableProgressInformationPanel(table, -1);
final boolean greater = tableProgressInformationPanel.setProgress(currentRow);
if (!greater) {
// this may happen because of the multithreaded nature of the
// execution - sometimes a notification can come in later than
// previous notifications
return;
}
ProgressCounter counter = _progressTimingCounters.get(table);
if (counter == null) {
counter = new ProgressCounter();
final ProgressCounter previous = _progressTimingCounters.put(table, counter);
if (previous != null) {
counter = previous;
}
}
final boolean log;
final int previousCount = counter.get();
if (currentRow - previousCount > 1000) {
log = counter.setIfSignificantToUser(currentRow);
} else {
log = false;
}
if (log) {
addUserLog("Progress of " + table.getName() + ": " + formatNumber(currentRow) + " rows processed");
}
} | java | public void updateProgress(final Table table, final int currentRow) {
final TableProgressInformationPanel tableProgressInformationPanel = getTableProgressInformationPanel(table, -1);
final boolean greater = tableProgressInformationPanel.setProgress(currentRow);
if (!greater) {
// this may happen because of the multithreaded nature of the
// execution - sometimes a notification can come in later than
// previous notifications
return;
}
ProgressCounter counter = _progressTimingCounters.get(table);
if (counter == null) {
counter = new ProgressCounter();
final ProgressCounter previous = _progressTimingCounters.put(table, counter);
if (previous != null) {
counter = previous;
}
}
final boolean log;
final int previousCount = counter.get();
if (currentRow - previousCount > 1000) {
log = counter.setIfSignificantToUser(currentRow);
} else {
log = false;
}
if (log) {
addUserLog("Progress of " + table.getName() + ": " + formatNumber(currentRow) + " rows processed");
}
} | [
"public",
"void",
"updateProgress",
"(",
"final",
"Table",
"table",
",",
"final",
"int",
"currentRow",
")",
"{",
"final",
"TableProgressInformationPanel",
"tableProgressInformationPanel",
"=",
"getTableProgressInformationPanel",
"(",
"table",
",",
"-",
"1",
")",
";",
... | Informs the panel that the progress for a table is updated
@param table
@param currentRow | [
"Informs",
"the",
"panel",
"that",
"the",
"progress",
"for",
"a",
"table",
"is",
"updated"
] | train | https://github.com/datacleaner/DataCleaner/blob/9aa01fdac3560cef51c55df3cb2ac5c690b57639/desktop/ui/src/main/java/org/datacleaner/panels/result/ProgressInformationPanel.java#L227-L257 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java | HttpHeaders.getIntHeader | @Deprecated
public static int getIntHeader(HttpMessage message, CharSequence name) {
String value = message.headers().get(name);
if (value == null) {
throw new NumberFormatException("header not found: " + name);
}
return Integer.parseInt(value);
} | java | @Deprecated
public static int getIntHeader(HttpMessage message, CharSequence name) {
String value = message.headers().get(name);
if (value == null) {
throw new NumberFormatException("header not found: " + name);
}
return Integer.parseInt(value);
} | [
"@",
"Deprecated",
"public",
"static",
"int",
"getIntHeader",
"(",
"HttpMessage",
"message",
",",
"CharSequence",
"name",
")",
"{",
"String",
"value",
"=",
"message",
".",
"headers",
"(",
")",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"value",
"==",
... | @deprecated Use {@link #getInt(CharSequence)} instead.
Returns the integer header value with the specified header name. If
there are more than one header value for the specified header name, the
first value is returned.
@return the header value
@throws NumberFormatException
if there is no such header or the header value is not a number | [
"@deprecated",
"Use",
"{",
"@link",
"#getInt",
"(",
"CharSequence",
")",
"}",
"instead",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java#L725-L732 |
dwdyer/watchmaker | swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/IslandsView.java | IslandsView.createControls | private JComponent createControls()
{
JPanel controls = new JPanel(new FlowLayout(FlowLayout.RIGHT));
final JCheckBox meanCheckBox = new JCheckBox("Show Mean and Standard Deviation", false);
meanCheckBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent itemEvent)
{
chart.setNotify(false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
if (itemEvent.getStateChange() == ItemEvent.SELECTED)
{
plot.setDataset(1, meanDataSet);
plot.setRenderer(1, meanRenderer);
}
else
{
plot.setDataset(1, null);
plot.setRenderer(1, null);
}
chart.setNotify(true);
}
});
controls.add(meanCheckBox);
return controls;
} | java | private JComponent createControls()
{
JPanel controls = new JPanel(new FlowLayout(FlowLayout.RIGHT));
final JCheckBox meanCheckBox = new JCheckBox("Show Mean and Standard Deviation", false);
meanCheckBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent itemEvent)
{
chart.setNotify(false);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
if (itemEvent.getStateChange() == ItemEvent.SELECTED)
{
plot.setDataset(1, meanDataSet);
plot.setRenderer(1, meanRenderer);
}
else
{
plot.setDataset(1, null);
plot.setRenderer(1, null);
}
chart.setNotify(true);
}
});
controls.add(meanCheckBox);
return controls;
} | [
"private",
"JComponent",
"createControls",
"(",
")",
"{",
"JPanel",
"controls",
"=",
"new",
"JPanel",
"(",
"new",
"FlowLayout",
"(",
"FlowLayout",
".",
"RIGHT",
")",
")",
";",
"final",
"JCheckBox",
"meanCheckBox",
"=",
"new",
"JCheckBox",
"(",
"\"Show Mean and... | Creates the GUI controls for toggling graph display options.
@return A component that can be added to the main panel. | [
"Creates",
"the",
"GUI",
"controls",
"for",
"toggling",
"graph",
"display",
"options",
"."
] | train | https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/swing/src/java/main/org/uncommons/watchmaker/swing/evolutionmonitor/IslandsView.java#L104-L131 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbservice_binding.java | gslbservice_binding.get | public static gslbservice_binding get(nitro_service service, String servicename) throws Exception{
gslbservice_binding obj = new gslbservice_binding();
obj.set_servicename(servicename);
gslbservice_binding response = (gslbservice_binding) obj.get_resource(service);
return response;
} | java | public static gslbservice_binding get(nitro_service service, String servicename) throws Exception{
gslbservice_binding obj = new gslbservice_binding();
obj.set_servicename(servicename);
gslbservice_binding response = (gslbservice_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"gslbservice_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"servicename",
")",
"throws",
"Exception",
"{",
"gslbservice_binding",
"obj",
"=",
"new",
"gslbservice_binding",
"(",
")",
";",
"obj",
".",
"set_servicename",
"(",
"s... | Use this API to fetch gslbservice_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"gslbservice_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/gslb/gslbservice_binding.java#L114-L119 |
alkacon/opencms-core | src-modules/org/opencms/workplace/comparison/CmsAttributeComparisonList.java | CmsAttributeComparisonList.readFile | protected static CmsFile readFile(CmsObject cms, CmsUUID structureId, String version) throws CmsException {
if (Integer.parseInt(version) == CmsHistoryResourceHandler.PROJECT_OFFLINE_VERSION) {
// offline
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
return cms.readFile(resource);
} else {
int ver = Integer.parseInt(version);
if (ver < 0) {
// online
CmsProject project = cms.getRequestContext().getCurrentProject();
try {
cms.getRequestContext().setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID));
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
return cms.readFile(resource);
} finally {
cms.getRequestContext().setCurrentProject(project);
}
}
// backup
return cms.readFile((CmsHistoryFile)cms.readResource(structureId, ver));
}
} | java | protected static CmsFile readFile(CmsObject cms, CmsUUID structureId, String version) throws CmsException {
if (Integer.parseInt(version) == CmsHistoryResourceHandler.PROJECT_OFFLINE_VERSION) {
// offline
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
return cms.readFile(resource);
} else {
int ver = Integer.parseInt(version);
if (ver < 0) {
// online
CmsProject project = cms.getRequestContext().getCurrentProject();
try {
cms.getRequestContext().setCurrentProject(cms.readProject(CmsProject.ONLINE_PROJECT_ID));
CmsResource resource = cms.readResource(structureId, CmsResourceFilter.IGNORE_EXPIRATION);
return cms.readFile(resource);
} finally {
cms.getRequestContext().setCurrentProject(project);
}
}
// backup
return cms.readFile((CmsHistoryFile)cms.readResource(structureId, ver));
}
} | [
"protected",
"static",
"CmsFile",
"readFile",
"(",
"CmsObject",
"cms",
",",
"CmsUUID",
"structureId",
",",
"String",
"version",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"Integer",
".",
"parseInt",
"(",
"version",
")",
"==",
"CmsHistoryResourceHandler",
"."... | Returns either the historical file or the offline file, depending on the version number.<p>
@param cms the CmsObject to use
@param structureId the structure id of the file
@param version the historical version number
@return either the historical file or the offline file, depending on the version number
@throws CmsException if something goes wrong | [
"Returns",
"either",
"the",
"historical",
"file",
"or",
"the",
"offline",
"file",
"depending",
"on",
"the",
"version",
"number",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/comparison/CmsAttributeComparisonList.java#L124-L146 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.