repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
201
func_name
stringlengths
4
126
whole_func_string
stringlengths
75
3.57k
language
stringclasses
1 value
func_code_string
stringlengths
75
3.57k
func_code_tokens
listlengths
21
599
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
aalmiray/Json-lib
src/main/java/net/sf/json/JSONObject.java
JSONObject.element
public JSONObject element( String key, boolean value ) { verifyIsNull(); return element( key, value ? Boolean.TRUE : Boolean.FALSE ); }
java
public JSONObject element( String key, boolean value ) { verifyIsNull(); return element( key, value ? Boolean.TRUE : Boolean.FALSE ); }
[ "public", "JSONObject", "element", "(", "String", "key", ",", "boolean", "value", ")", "{", "verifyIsNull", "(", ")", ";", "return", "element", "(", "key", ",", "value", "?", "Boolean", ".", "TRUE", ":", "Boolean", ".", "FALSE", ")", ";", "}" ]
Put a key/boolean pair in the JSONObject. @param key A key string. @param value A boolean which is the value. @return this. @throws JSONException If the key is null.
[ "Put", "a", "key", "/", "boolean", "pair", "in", "the", "JSONObject", "." ]
train
https://github.com/aalmiray/Json-lib/blob/9e2b3376ee8f511a48aa7ac05f75a7414e02280f/src/main/java/net/sf/json/JSONObject.java#L1569-L1572
fabric8io/kubernetes-client
openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/BuildConfigOperationsImpl.java
BuildConfigOperationsImpl.deleteBuilds
private void deleteBuilds() { if (getName() == null) { return; } String buildConfigLabelValue = getName().substring(0, Math.min(getName().length(), 63)); BuildList matchingBuilds = new BuildOperationsImpl(client, (OpenShiftConfig) config).inNamespace(namespace).withLabel(BUILD_CONFIG_LABEL, buildConfigLabelValue).list(); if (matchingBuilds.getItems() != null) { for (Build matchingBuild : matchingBuilds.getItems()) { if (matchingBuild.getMetadata() != null && matchingBuild.getMetadata().getAnnotations() != null && getName().equals(matchingBuild.getMetadata().getAnnotations().get(BUILD_CONFIG_ANNOTATION))) { new BuildOperationsImpl(client, (OpenShiftConfig) config).inNamespace(matchingBuild.getMetadata().getNamespace()).withName(matchingBuild.getMetadata().getName()).delete(); } } } }
java
private void deleteBuilds() { if (getName() == null) { return; } String buildConfigLabelValue = getName().substring(0, Math.min(getName().length(), 63)); BuildList matchingBuilds = new BuildOperationsImpl(client, (OpenShiftConfig) config).inNamespace(namespace).withLabel(BUILD_CONFIG_LABEL, buildConfigLabelValue).list(); if (matchingBuilds.getItems() != null) { for (Build matchingBuild : matchingBuilds.getItems()) { if (matchingBuild.getMetadata() != null && matchingBuild.getMetadata().getAnnotations() != null && getName().equals(matchingBuild.getMetadata().getAnnotations().get(BUILD_CONFIG_ANNOTATION))) { new BuildOperationsImpl(client, (OpenShiftConfig) config).inNamespace(matchingBuild.getMetadata().getNamespace()).withName(matchingBuild.getMetadata().getName()).delete(); } } } }
[ "private", "void", "deleteBuilds", "(", ")", "{", "if", "(", "getName", "(", ")", "==", "null", ")", "{", "return", ";", "}", "String", "buildConfigLabelValue", "=", "getName", "(", ")", ".", "substring", "(", "0", ",", "Math", ".", "min", "(", "getN...
/* Labels are limited to 63 chars so need to first truncate the build config name (if required), retrieve builds with matching label, then check the build config name against the builds' build config annotation which have no such length restriction (but aren't usable for searching). Would be better if referenced build config was available via fields but it currently isn't...
[ "/", "*", "Labels", "are", "limited", "to", "63", "chars", "so", "need", "to", "first", "truncate", "the", "build", "config", "name", "(", "if", "required", ")", "retrieve", "builds", "with", "matching", "label", "then", "check", "the", "build", "config", ...
train
https://github.com/fabric8io/kubernetes-client/blob/141668a882ed8e902c045a5cd0a80f14bd17d132/openshift-client/src/main/java/io/fabric8/openshift/client/dsl/internal/BuildConfigOperationsImpl.java#L178-L200
twilio/twilio-java
src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java
AvailablePhoneNumberCountryReader.getPage
@Override @SuppressWarnings("checkstyle:linelength") public Page<AvailablePhoneNumberCountry> getPage(final String targetUrl, final TwilioRestClient client) { this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid; Request request = new Request( HttpMethod.GET, targetUrl ); return pageForRequest(client, request); }
java
@Override @SuppressWarnings("checkstyle:linelength") public Page<AvailablePhoneNumberCountry> getPage(final String targetUrl, final TwilioRestClient client) { this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid; Request request = new Request( HttpMethod.GET, targetUrl ); return pageForRequest(client, request); }
[ "@", "Override", "@", "SuppressWarnings", "(", "\"checkstyle:linelength\"", ")", "public", "Page", "<", "AvailablePhoneNumberCountry", ">", "getPage", "(", "final", "String", "targetUrl", ",", "final", "TwilioRestClient", "client", ")", "{", "this", ".", "pathAccoun...
Retrieve the target page from the Twilio API. @param targetUrl API-generated URL for the requested results page @param client TwilioRestClient with which to make the request @return AvailablePhoneNumberCountry ResourceSet
[ "Retrieve", "the", "target", "page", "from", "the", "Twilio", "API", "." ]
train
https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/api/v2010/account/AvailablePhoneNumberCountryReader.java#L80-L90
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/LogAnalyticsInner.java
LogAnalyticsInner.exportThrottledRequestsAsync
public Observable<LogAnalyticsOperationResultInner> exportThrottledRequestsAsync(String location, ThrottledRequestsInput parameters) { return exportThrottledRequestsWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<LogAnalyticsOperationResultInner>, LogAnalyticsOperationResultInner>() { @Override public LogAnalyticsOperationResultInner call(ServiceResponse<LogAnalyticsOperationResultInner> response) { return response.body(); } }); }
java
public Observable<LogAnalyticsOperationResultInner> exportThrottledRequestsAsync(String location, ThrottledRequestsInput parameters) { return exportThrottledRequestsWithServiceResponseAsync(location, parameters).map(new Func1<ServiceResponse<LogAnalyticsOperationResultInner>, LogAnalyticsOperationResultInner>() { @Override public LogAnalyticsOperationResultInner call(ServiceResponse<LogAnalyticsOperationResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "LogAnalyticsOperationResultInner", ">", "exportThrottledRequestsAsync", "(", "String", "location", ",", "ThrottledRequestsInput", "parameters", ")", "{", "return", "exportThrottledRequestsWithServiceResponseAsync", "(", "location", ",", "parameters...
Export logs that show total throttled Api requests for this subscription in the given time window. @param location The location upon which virtual-machine-sizes is queried. @param parameters Parameters supplied to the LogAnalytics getThrottledRequests Api. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Export", "logs", "that", "show", "total", "throttled", "Api", "requests", "for", "this", "subscription", "in", "the", "given", "time", "window", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/LogAnalyticsInner.java#L269-L276
lucee/Lucee
core/src/main/java/lucee/runtime/schedule/StorageUtil.java
StorageUtil.toBoolean
public boolean toBoolean(Element el, String attributeName) { return Caster.toBooleanValue(el.getAttribute(attributeName), false); }
java
public boolean toBoolean(Element el, String attributeName) { return Caster.toBooleanValue(el.getAttribute(attributeName), false); }
[ "public", "boolean", "toBoolean", "(", "Element", "el", ",", "String", "attributeName", ")", "{", "return", "Caster", ".", "toBooleanValue", "(", "el", ".", "getAttribute", "(", "attributeName", ")", ",", "false", ")", ";", "}" ]
reads a XML Element Attribute ans cast it to a boolean value @param el XML Element to read Attribute from it @param attributeName Name of the Attribute to read @return Attribute Value
[ "reads", "a", "XML", "Element", "Attribute", "ans", "cast", "it", "to", "a", "boolean", "value" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/schedule/StorageUtil.java#L186-L188
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/cluster/RedisClusterClient.java
RedisClusterClient.forEachCloseable
@SuppressWarnings("unchecked") protected <T extends Closeable> void forEachCloseable(Predicate<? super Closeable> selector, Consumer<T> function) { for (Closeable c : closeableResources) { if (selector.test(c)) { function.accept((T) c); } } }
java
@SuppressWarnings("unchecked") protected <T extends Closeable> void forEachCloseable(Predicate<? super Closeable> selector, Consumer<T> function) { for (Closeable c : closeableResources) { if (selector.test(c)) { function.accept((T) c); } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "<", "T", "extends", "Closeable", ">", "void", "forEachCloseable", "(", "Predicate", "<", "?", "super", "Closeable", ">", "selector", ",", "Consumer", "<", "T", ">", "function", ")", "{", "for"...
Apply a {@link Consumer} of {@link Closeable} to all active connections. @param <T> @param function the {@link Consumer}.
[ "Apply", "a", "{", "@link", "Consumer", "}", "of", "{", "@link", "Closeable", "}", "to", "all", "active", "connections", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/cluster/RedisClusterClient.java#L1061-L1068
legsem/legstar.avro
legstar.avro.cob2avro/src/main/java/com/legstar/avro/cob2avro/io/ZosVarRdwDatumReader.java
ZosVarRdwDatumReader.getRecordLen
private static int getRecordLen(byte[] hostData, int start, int length) { int len = getRawRdw(hostData, start, length); if (len < RDW_LEN || len > hostData.length) { throw new IllegalArgumentException( "Record does not start with a Record Descriptor Word"); } /* Beware that raw rdw accounts for the rdw length (4 bytes) */ return len - RDW_LEN; }
java
private static int getRecordLen(byte[] hostData, int start, int length) { int len = getRawRdw(hostData, start, length); if (len < RDW_LEN || len > hostData.length) { throw new IllegalArgumentException( "Record does not start with a Record Descriptor Word"); } /* Beware that raw rdw accounts for the rdw length (4 bytes) */ return len - RDW_LEN; }
[ "private", "static", "int", "getRecordLen", "(", "byte", "[", "]", "hostData", ",", "int", "start", ",", "int", "length", ")", "{", "int", "len", "=", "getRawRdw", "(", "hostData", ",", "start", ",", "length", ")", ";", "if", "(", "len", "<", "RDW_LE...
RDW is a 4 bytes numeric stored in Big Endian as a binary 2's complement. @param hostData the mainframe data @param start where the RDW starts @param length the total size of the mainframe data @return the size of the record (actual data without the rdw itself)
[ "RDW", "is", "a", "4", "bytes", "numeric", "stored", "in", "Big", "Endian", "as", "a", "binary", "2", "s", "complement", "." ]
train
https://github.com/legsem/legstar.avro/blob/bad5e0bf41700951eee1ad6a5d6d0c47b3da8f0b/legstar.avro.cob2avro/src/main/java/com/legstar/avro/cob2avro/io/ZosVarRdwDatumReader.java#L96-L105
crowmagnumb/s6-util
src/main/java/net/crowmagnumb/util/reflect/SimpleMethodInvoker.java
SimpleMethodInvoker.invokeMethod
private static Object invokeMethod( final Object obj, final String methodName, final Object[] args, final Class<?>[] parameterTypes ) throws UtilException { return invokeMethod( obj, obj.getClass(), methodName, args, parameterTypes ); }
java
private static Object invokeMethod( final Object obj, final String methodName, final Object[] args, final Class<?>[] parameterTypes ) throws UtilException { return invokeMethod( obj, obj.getClass(), methodName, args, parameterTypes ); }
[ "private", "static", "Object", "invokeMethod", "(", "final", "Object", "obj", ",", "final", "String", "methodName", ",", "final", "Object", "[", "]", "args", ",", "final", "Class", "<", "?", ">", "[", "]", "parameterTypes", ")", "throws", "UtilException", ...
We have an object and a method name, but in order to invoke a method on an object, we need the object's Class (type). Given this Class we can then check that such a method exists and throw an exception if it doesn't. @param obj to invoke method on @param methodName to invoke @param args to use @param parameterTypes types of arguments @return method result @throws net.crowmagnumb.util.UtilException if problem
[ "We", "have", "an", "object", "and", "a", "method", "name", "but", "in", "order", "to", "invoke", "a", "method", "on", "an", "object", "we", "need", "the", "object", "s", "Class", "(", "type", ")", "." ]
train
https://github.com/crowmagnumb/s6-util/blob/0f9969bc0809e8a617501fa57c135e9b3984fae0/src/main/java/net/crowmagnumb/util/reflect/SimpleMethodInvoker.java#L301-L309
drinkjava2/jBeanBox
jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/util/CheckClassAdapter.java
CheckClassAdapter.checkTypeRefAndPath
static void checkTypeRefAndPath(int typeRef, TypePath typePath) { int mask = 0; switch (typeRef >>> 24) { case TypeReference.CLASS_TYPE_PARAMETER: case TypeReference.METHOD_TYPE_PARAMETER: case TypeReference.METHOD_FORMAL_PARAMETER: mask = 0xFFFF0000; break; case TypeReference.FIELD: case TypeReference.METHOD_RETURN: case TypeReference.METHOD_RECEIVER: case TypeReference.LOCAL_VARIABLE: case TypeReference.RESOURCE_VARIABLE: case TypeReference.INSTANCEOF: case TypeReference.NEW: case TypeReference.CONSTRUCTOR_REFERENCE: case TypeReference.METHOD_REFERENCE: mask = 0xFF000000; break; case TypeReference.CLASS_EXTENDS: case TypeReference.CLASS_TYPE_PARAMETER_BOUND: case TypeReference.METHOD_TYPE_PARAMETER_BOUND: case TypeReference.THROWS: case TypeReference.EXCEPTION_PARAMETER: mask = 0xFFFFFF00; break; case TypeReference.CAST: case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: mask = 0xFF0000FF; break; default: throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(typeRef >>> 24)); } if ((typeRef & ~mask) != 0) { throw new IllegalArgumentException("Invalid type reference 0x" + Integer.toHexString(typeRef)); } if (typePath != null) { for (int i = 0; i < typePath.getLength(); ++i) { int step = typePath.getStep(i); if (step != TypePath.ARRAY_ELEMENT && step != TypePath.INNER_TYPE && step != TypePath.TYPE_ARGUMENT && step != TypePath.WILDCARD_BOUND) { throw new IllegalArgumentException( "Invalid type path step " + i + " in " + typePath); } if (step != TypePath.TYPE_ARGUMENT && typePath.getStepArgument(i) != 0) { throw new IllegalArgumentException( "Invalid type path step argument for step " + i + " in " + typePath); } } } }
java
static void checkTypeRefAndPath(int typeRef, TypePath typePath) { int mask = 0; switch (typeRef >>> 24) { case TypeReference.CLASS_TYPE_PARAMETER: case TypeReference.METHOD_TYPE_PARAMETER: case TypeReference.METHOD_FORMAL_PARAMETER: mask = 0xFFFF0000; break; case TypeReference.FIELD: case TypeReference.METHOD_RETURN: case TypeReference.METHOD_RECEIVER: case TypeReference.LOCAL_VARIABLE: case TypeReference.RESOURCE_VARIABLE: case TypeReference.INSTANCEOF: case TypeReference.NEW: case TypeReference.CONSTRUCTOR_REFERENCE: case TypeReference.METHOD_REFERENCE: mask = 0xFF000000; break; case TypeReference.CLASS_EXTENDS: case TypeReference.CLASS_TYPE_PARAMETER_BOUND: case TypeReference.METHOD_TYPE_PARAMETER_BOUND: case TypeReference.THROWS: case TypeReference.EXCEPTION_PARAMETER: mask = 0xFFFFFF00; break; case TypeReference.CAST: case TypeReference.CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT: case TypeReference.METHOD_INVOCATION_TYPE_ARGUMENT: case TypeReference.CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT: case TypeReference.METHOD_REFERENCE_TYPE_ARGUMENT: mask = 0xFF0000FF; break; default: throw new IllegalArgumentException("Invalid type reference sort 0x" + Integer.toHexString(typeRef >>> 24)); } if ((typeRef & ~mask) != 0) { throw new IllegalArgumentException("Invalid type reference 0x" + Integer.toHexString(typeRef)); } if (typePath != null) { for (int i = 0; i < typePath.getLength(); ++i) { int step = typePath.getStep(i); if (step != TypePath.ARRAY_ELEMENT && step != TypePath.INNER_TYPE && step != TypePath.TYPE_ARGUMENT && step != TypePath.WILDCARD_BOUND) { throw new IllegalArgumentException( "Invalid type path step " + i + " in " + typePath); } if (step != TypePath.TYPE_ARGUMENT && typePath.getStepArgument(i) != 0) { throw new IllegalArgumentException( "Invalid type path step argument for step " + i + " in " + typePath); } } } }
[ "static", "void", "checkTypeRefAndPath", "(", "int", "typeRef", ",", "TypePath", "typePath", ")", "{", "int", "mask", "=", "0", ";", "switch", "(", "typeRef", ">>>", "24", ")", "{", "case", "TypeReference", ".", "CLASS_TYPE_PARAMETER", ":", "case", "TypeRefe...
Checks the reference to a type in a type annotation. @param typeRef a reference to an annotated type. @param typePath the path to the annotated type argument, wildcard bound, array element type, or static inner type within 'typeRef'. May be <tt>null</tt> if the annotation targets 'typeRef' as a whole.
[ "Checks", "the", "reference", "to", "a", "type", "in", "a", "type", "annotation", "." ]
train
https://github.com/drinkjava2/jBeanBox/blob/01c216599ffa2e5f2d9c01df2adaad0f45567c04/jbeanbox/src/main/java/com/github/drinkjava2/asm5_0_3/util/CheckClassAdapter.java#L705-L764
OpenLiberty/open-liberty
dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/client/injection/WebServiceRefBinding.java
WebServiceRefBinding.processExistingWSDL
private void processExistingWSDL(String wsdlLocation, Member newMember) throws InjectionException { // if the wsdlLocation for this service reference is specified in the DD, log a debug statement and continue if (wsrInfo.getWsdlLocation() != null && !"".equals(wsrInfo.getWsdlLocation())) { if (tc.isDebugEnabled()) { Tr.debug(tc, "For the " + wsrInfo.getJndiName() + " service reference, " + "the " + wsrInfo.getWsdlLocation() + " WSDL file is specified in the " + "deployment descriptor. Annotation metadata referencing a WSDL file for " + "this service reference will be ignored."); } } else { // else we want to set the value to whatever is in the annotation if (tc.isDebugEnabled()) { Tr.debug(tc, "For the " + wsrInfo.getJndiName() + " service reference, " + "setting the wsdlLocation: " + wsdlLocation); } wsrInfo.setWsdlLocation(wsdlLocation); } }
java
private void processExistingWSDL(String wsdlLocation, Member newMember) throws InjectionException { // if the wsdlLocation for this service reference is specified in the DD, log a debug statement and continue if (wsrInfo.getWsdlLocation() != null && !"".equals(wsrInfo.getWsdlLocation())) { if (tc.isDebugEnabled()) { Tr.debug(tc, "For the " + wsrInfo.getJndiName() + " service reference, " + "the " + wsrInfo.getWsdlLocation() + " WSDL file is specified in the " + "deployment descriptor. Annotation metadata referencing a WSDL file for " + "this service reference will be ignored."); } } else { // else we want to set the value to whatever is in the annotation if (tc.isDebugEnabled()) { Tr.debug(tc, "For the " + wsrInfo.getJndiName() + " service reference, " + "setting the wsdlLocation: " + wsdlLocation); } wsrInfo.setWsdlLocation(wsdlLocation); } }
[ "private", "void", "processExistingWSDL", "(", "String", "wsdlLocation", ",", "Member", "newMember", ")", "throws", "InjectionException", "{", "// if the wsdlLocation for this service reference is specified in the DD, log a debug statement and continue", "if", "(", "wsrInfo", ".", ...
This will compare the wsdlLocation attribute of the various annotations that have refer to the same service reference. If they differ we will throw an exception as the runtime will not be able to determine which WSDL to use. We will only do this checking if there was not a WSDL location specified in the deployment descriptor. If the DD specifies a deployment descriptor that value will be used, and other values will be ignored.
[ "This", "will", "compare", "the", "wsdlLocation", "attribute", "of", "the", "various", "annotations", "that", "have", "refer", "to", "the", "same", "service", "reference", ".", "If", "they", "differ", "we", "will", "throw", "an", "exception", "as", "the", "r...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jaxws.clientcontainer/src/com/ibm/ws/jaxws/client/injection/WebServiceRefBinding.java#L343-L357
GwtMaterialDesign/gwt-material-addins
src/main/java/gwt/material/design/addins/client/combobox/MaterialComboBox.java
MaterialComboBox.setValues
public void setValues(List<T> values, boolean fireEvents) { String[] stringValues = new String[values.size()]; for (int i = 0; i < values.size(); i++) { stringValues[i] = keyFactory.generateKey(values.get(i)); } suppressChangeEvent = !fireEvents; $(listbox.getElement()).val(stringValues).trigger("change", selectedIndex); suppressChangeEvent = false; }
java
public void setValues(List<T> values, boolean fireEvents) { String[] stringValues = new String[values.size()]; for (int i = 0; i < values.size(); i++) { stringValues[i] = keyFactory.generateKey(values.get(i)); } suppressChangeEvent = !fireEvents; $(listbox.getElement()).val(stringValues).trigger("change", selectedIndex); suppressChangeEvent = false; }
[ "public", "void", "setValues", "(", "List", "<", "T", ">", "values", ",", "boolean", "fireEvents", ")", "{", "String", "[", "]", "stringValues", "=", "new", "String", "[", "values", ".", "size", "(", ")", "]", ";", "for", "(", "int", "i", "=", "0",...
Set directly all the values that will be stored into combobox and build options into it.
[ "Set", "directly", "all", "the", "values", "that", "will", "be", "stored", "into", "combobox", "and", "build", "options", "into", "it", "." ]
train
https://github.com/GwtMaterialDesign/gwt-material-addins/blob/11aec9d92918225f70f936285d0ae94f2178c36e/src/main/java/gwt/material/design/addins/client/combobox/MaterialComboBox.java#L584-L592
att/AAF
cadi/aaf/src/main/java/com/att/cadi/aaf/client/ErrMessage.java
ErrMessage.toMsg
public StringBuilder toMsg(StringBuilder sb, String attErrJson) throws APIException { return toMsg(sb,errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()); }
java
public StringBuilder toMsg(StringBuilder sb, String attErrJson) throws APIException { return toMsg(sb,errDF.newData().in(TYPE.JSON).load(attErrJson).asObject()); }
[ "public", "StringBuilder", "toMsg", "(", "StringBuilder", "sb", ",", "String", "attErrJson", ")", "throws", "APIException", "{", "return", "toMsg", "(", "sb", ",", "errDF", ".", "newData", "(", ")", ".", "in", "(", "TYPE", ".", "JSON", ")", ".", "load", ...
AT&T Requires a specific Error Format for RESTful Services, which AAF complies with. This code will create a meaningful string from this format. @param sb @param df @param r @throws APIException
[ "AT&T", "Requires", "a", "specific", "Error", "Format", "for", "RESTful", "Services", "which", "AAF", "complies", "with", "." ]
train
https://github.com/att/AAF/blob/090562e956c0035db972aafba844dc6d3fc948ee/cadi/aaf/src/main/java/com/att/cadi/aaf/client/ErrMessage.java#L50-L52
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/operations/Variable.java
Variable.fixupVariables
public void fixupVariables(java.util.Vector vars, int globalsSize) { m_fixUpWasCalled = true; int sz = vars.size(); for (int i = vars.size()-1; i >= 0; i--) { QName qn = (QName)vars.elementAt(i); // System.out.println("qn: "+qn); if(qn.equals(m_qname)) { if(i < globalsSize) { m_isGlobal = true; m_index = i; } else { m_index = i-globalsSize; } return; } } java.lang.String msg = XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULD_NOT_FIND_VAR, new Object[]{m_qname.toString()}); TransformerException te = new TransformerException(msg, this); throw new org.apache.xml.utils.WrappedRuntimeException(te); }
java
public void fixupVariables(java.util.Vector vars, int globalsSize) { m_fixUpWasCalled = true; int sz = vars.size(); for (int i = vars.size()-1; i >= 0; i--) { QName qn = (QName)vars.elementAt(i); // System.out.println("qn: "+qn); if(qn.equals(m_qname)) { if(i < globalsSize) { m_isGlobal = true; m_index = i; } else { m_index = i-globalsSize; } return; } } java.lang.String msg = XSLMessages.createXPATHMessage(XPATHErrorResources.ER_COULD_NOT_FIND_VAR, new Object[]{m_qname.toString()}); TransformerException te = new TransformerException(msg, this); throw new org.apache.xml.utils.WrappedRuntimeException(te); }
[ "public", "void", "fixupVariables", "(", "java", ".", "util", ".", "Vector", "vars", ",", "int", "globalsSize", ")", "{", "m_fixUpWasCalled", "=", "true", ";", "int", "sz", "=", "vars", ".", "size", "(", ")", ";", "for", "(", "int", "i", "=", "vars",...
This function is used to fixup variables from QNames to stack frame indexes at stylesheet build time. @param vars List of QNames that correspond to variables. This list should be searched backwards for the first qualified name that corresponds to the variable reference qname. The position of the QName in the vector from the start of the vector will be its position in the stack frame (but variables above the globalsTop value will need to be offset to the current stack frame).
[ "This", "function", "is", "used", "to", "fixup", "variables", "from", "QNames", "to", "stack", "frame", "indexes", "at", "stylesheet", "build", "time", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/operations/Variable.java#L117-L150
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Extern.java
Extern.readPackageListFromFile
private void readPackageListFromFile(String path, DocFile pkgListPath) throws Fault { DocFile file = pkgListPath.resolve(DocPaths.PACKAGE_LIST); if (! (file.isAbsolute() || linkoffline)){ file = file.resolveAgainst(DocumentationTool.Location.DOCUMENTATION_OUTPUT); } try { if (file.exists() && file.canRead()) { boolean pathIsRelative = !DocFile.createFileForInput(configuration, path).isAbsolute() && !isUrl(path); readPackageList(file.openInputStream(), path, pathIsRelative); } else { throw new Fault(configuration.getText("doclet.File_error", file.getPath()), null); } } catch (IOException exc) { throw new Fault(configuration.getText("doclet.File_error", file.getPath()), exc); } }
java
private void readPackageListFromFile(String path, DocFile pkgListPath) throws Fault { DocFile file = pkgListPath.resolve(DocPaths.PACKAGE_LIST); if (! (file.isAbsolute() || linkoffline)){ file = file.resolveAgainst(DocumentationTool.Location.DOCUMENTATION_OUTPUT); } try { if (file.exists() && file.canRead()) { boolean pathIsRelative = !DocFile.createFileForInput(configuration, path).isAbsolute() && !isUrl(path); readPackageList(file.openInputStream(), path, pathIsRelative); } else { throw new Fault(configuration.getText("doclet.File_error", file.getPath()), null); } } catch (IOException exc) { throw new Fault(configuration.getText("doclet.File_error", file.getPath()), exc); } }
[ "private", "void", "readPackageListFromFile", "(", "String", "path", ",", "DocFile", "pkgListPath", ")", "throws", "Fault", "{", "DocFile", "file", "=", "pkgListPath", ".", "resolve", "(", "DocPaths", ".", "PACKAGE_LIST", ")", ";", "if", "(", "!", "(", "file...
Read the "package-list" file which is available locally. @param path URL or directory path to the packages. @param pkgListPath Path to the local "package-list" file.
[ "Read", "the", "package", "-", "list", "file", "which", "is", "available", "locally", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Extern.java#L252-L270
tvesalainen/bcc
src/main/java/org/vesalainen/bcc/ClassFile.java
ClassFile.getMethodIndex
int getMethodIndex(ExecutableElement method) { TypeElement declaringClass = (TypeElement) method.getEnclosingElement(); String fullyQualifiedname = declaringClass.getQualifiedName().toString(); return getRefIndex(Methodref.class, fullyQualifiedname, method.getSimpleName().toString(), Descriptor.getDesriptor(method)); }
java
int getMethodIndex(ExecutableElement method) { TypeElement declaringClass = (TypeElement) method.getEnclosingElement(); String fullyQualifiedname = declaringClass.getQualifiedName().toString(); return getRefIndex(Methodref.class, fullyQualifiedname, method.getSimpleName().toString(), Descriptor.getDesriptor(method)); }
[ "int", "getMethodIndex", "(", "ExecutableElement", "method", ")", "{", "TypeElement", "declaringClass", "=", "(", "TypeElement", ")", "method", ".", "getEnclosingElement", "(", ")", ";", "String", "fullyQualifiedname", "=", "declaringClass", ".", "getQualifiedName", ...
Returns the constant map index to method @param method @return
[ "Returns", "the", "constant", "map", "index", "to", "method" ]
train
https://github.com/tvesalainen/bcc/blob/4e84e313018d487f1a8cca3952d71bc21e77d16b/src/main/java/org/vesalainen/bcc/ClassFile.java#L234-L239
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/net/BlockingClient.java
BlockingClient.runReadLoop
public static void runReadLoop(InputStream stream, StreamConnection connection) throws Exception { ByteBuffer dbuf = ByteBuffer.allocateDirect(Math.min(Math.max(connection.getMaxMessageSize(), BUFFER_SIZE_LOWER_BOUND), BUFFER_SIZE_UPPER_BOUND)); byte[] readBuff = new byte[dbuf.capacity()]; while (true) { // TODO Kill the message duplication here checkState(dbuf.remaining() > 0 && dbuf.remaining() <= readBuff.length); int read = stream.read(readBuff, 0, Math.max(1, Math.min(dbuf.remaining(), stream.available()))); if (read == -1) return; dbuf.put(readBuff, 0, read); // "flip" the buffer - setting the limit to the current position and setting position to 0 dbuf.flip(); // Use connection.receiveBytes's return value as a double-check that it stopped reading at the right // location int bytesConsumed = connection.receiveBytes(dbuf); checkState(dbuf.position() == bytesConsumed); // Now drop the bytes which were read by compacting dbuf (resetting limit and keeping relative // position) dbuf.compact(); } }
java
public static void runReadLoop(InputStream stream, StreamConnection connection) throws Exception { ByteBuffer dbuf = ByteBuffer.allocateDirect(Math.min(Math.max(connection.getMaxMessageSize(), BUFFER_SIZE_LOWER_BOUND), BUFFER_SIZE_UPPER_BOUND)); byte[] readBuff = new byte[dbuf.capacity()]; while (true) { // TODO Kill the message duplication here checkState(dbuf.remaining() > 0 && dbuf.remaining() <= readBuff.length); int read = stream.read(readBuff, 0, Math.max(1, Math.min(dbuf.remaining(), stream.available()))); if (read == -1) return; dbuf.put(readBuff, 0, read); // "flip" the buffer - setting the limit to the current position and setting position to 0 dbuf.flip(); // Use connection.receiveBytes's return value as a double-check that it stopped reading at the right // location int bytesConsumed = connection.receiveBytes(dbuf); checkState(dbuf.position() == bytesConsumed); // Now drop the bytes which were read by compacting dbuf (resetting limit and keeping relative // position) dbuf.compact(); } }
[ "public", "static", "void", "runReadLoop", "(", "InputStream", "stream", ",", "StreamConnection", "connection", ")", "throws", "Exception", "{", "ByteBuffer", "dbuf", "=", "ByteBuffer", ".", "allocateDirect", "(", "Math", ".", "min", "(", "Math", ".", "max", "...
A blocking call that never returns, except by throwing an exception. It reads bytes from the input stream and feeds them to the provided {@link StreamConnection}, for example, a {@link Peer}.
[ "A", "blocking", "call", "that", "never", "returns", "except", "by", "throwing", "an", "exception", ".", "It", "reads", "bytes", "from", "the", "input", "stream", "and", "feeds", "them", "to", "the", "provided", "{" ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/net/BlockingClient.java#L108-L128
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/CASH.java
CASH.runDerivator
private LinearEquationSystem runDerivator(Relation<ParameterizationFunction> relation, int dimensionality, DBIDs ids) { try { // build database for derivator Database derivatorDB = buildDerivatorDB(relation, ids); PCARunner pca = new PCARunner(new StandardCovarianceMatrixBuilder()); EigenPairFilter filter = new FirstNEigenPairFilter(dimensionality); DependencyDerivator<DoubleVector> derivator = new DependencyDerivator<>(null, FormatUtil.NF4, pca, filter, 0, false); CorrelationAnalysisSolution<DoubleVector> model = derivator.run(derivatorDB); LinearEquationSystem les = model.getNormalizedLinearEquationSystem(null); return les; } catch(NonNumericFeaturesException e) { throw new IllegalStateException("Error during normalization" + e); } }
java
private LinearEquationSystem runDerivator(Relation<ParameterizationFunction> relation, int dimensionality, DBIDs ids) { try { // build database for derivator Database derivatorDB = buildDerivatorDB(relation, ids); PCARunner pca = new PCARunner(new StandardCovarianceMatrixBuilder()); EigenPairFilter filter = new FirstNEigenPairFilter(dimensionality); DependencyDerivator<DoubleVector> derivator = new DependencyDerivator<>(null, FormatUtil.NF4, pca, filter, 0, false); CorrelationAnalysisSolution<DoubleVector> model = derivator.run(derivatorDB); LinearEquationSystem les = model.getNormalizedLinearEquationSystem(null); return les; } catch(NonNumericFeaturesException e) { throw new IllegalStateException("Error during normalization" + e); } }
[ "private", "LinearEquationSystem", "runDerivator", "(", "Relation", "<", "ParameterizationFunction", ">", "relation", ",", "int", "dimensionality", ",", "DBIDs", "ids", ")", "{", "try", "{", "// build database for derivator", "Database", "derivatorDB", "=", "buildDeriva...
Runs the derivator on the specified interval and assigns all points having a distance less then the standard deviation of the derivator model to the model to this model. @param relation the database containing the parameterization functions @param ids the ids to build the model @param dimensionality the dimensionality of the subspace @return a basis of the found subspace
[ "Runs", "the", "derivator", "on", "the", "specified", "interval", "and", "assigns", "all", "points", "having", "a", "distance", "less", "then", "the", "standard", "deviation", "of", "the", "derivator", "model", "to", "the", "model", "to", "this", "model", "....
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/correlation/CASH.java#L692-L708
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java
BootstrapConfig.substituteSymbols
protected void substituteSymbols(Map<String, String> initProps) { for (Entry<String, String> entry : initProps.entrySet()) { Object value = entry.getValue(); if (value instanceof String) { String strValue = (String) value; Matcher m = SYMBOL_DEF.matcher(strValue); int i = 0; while (m.find() && i++ < 4) { String symbol = m.group(1); Object expansion = initProps.get(symbol); if (expansion != null && expansion instanceof String) { strValue = strValue.replace(m.group(0), (String) expansion); entry.setValue(strValue); } } } } }
java
protected void substituteSymbols(Map<String, String> initProps) { for (Entry<String, String> entry : initProps.entrySet()) { Object value = entry.getValue(); if (value instanceof String) { String strValue = (String) value; Matcher m = SYMBOL_DEF.matcher(strValue); int i = 0; while (m.find() && i++ < 4) { String symbol = m.group(1); Object expansion = initProps.get(symbol); if (expansion != null && expansion instanceof String) { strValue = strValue.replace(m.group(0), (String) expansion); entry.setValue(strValue); } } } } }
[ "protected", "void", "substituteSymbols", "(", "Map", "<", "String", ",", "String", ">", "initProps", ")", "{", "for", "(", "Entry", "<", "String", ",", "String", ">", "entry", ":", "initProps", ".", "entrySet", "(", ")", ")", "{", "Object", "value", "...
Perform substitution of symbols used in config @param initProps
[ "Perform", "substitution", "of", "symbols", "used", "in", "config" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/BootstrapConfig.java#L748-L765
palatable/lambda
src/main/java/com/jnape/palatable/lambda/optics/lenses/CollectionLens.java
CollectionLens.asCopy
public static <X, CX extends Collection<X>> Lens.Simple<CX, CX> asCopy(Function<? super CX, ? extends CX> copyFn) { return simpleLens(copyFn, (__, copy) -> copy); }
java
public static <X, CX extends Collection<X>> Lens.Simple<CX, CX> asCopy(Function<? super CX, ? extends CX> copyFn) { return simpleLens(copyFn, (__, copy) -> copy); }
[ "public", "static", "<", "X", ",", "CX", "extends", "Collection", "<", "X", ">", ">", "Lens", ".", "Simple", "<", "CX", ",", "CX", ">", "asCopy", "(", "Function", "<", "?", "super", "CX", ",", "?", "extends", "CX", ">", "copyFn", ")", "{", "retur...
Convenience static factory method for creating a lens that focuses on a copy of a <code>Collection</code>, given a function that creates the copy. Useful for composition to avoid mutating a <code>Collection</code> reference. @param copyFn the copying function @param <X> the collection element type @param <CX> the type of the collection @return a lens that focuses on a copy of CX
[ "Convenience", "static", "factory", "method", "for", "creating", "a", "lens", "that", "focuses", "on", "a", "copy", "of", "a", "<code", ">", "Collection<", "/", "code", ">", "given", "a", "function", "that", "creates", "the", "copy", ".", "Useful", "for", ...
train
https://github.com/palatable/lambda/blob/b643ba836c5916d1d8193822e5efb4e7b40c489a/src/main/java/com/jnape/palatable/lambda/optics/lenses/CollectionLens.java#L30-L32
bignerdranch/expandable-recycler-view
expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java
ExpandableRecyclerAdapter.notifyParentMoved
@UiThread public void notifyParentMoved(int fromParentPosition, int toParentPosition) { int fromFlatParentPosition = getFlatParentPosition(fromParentPosition); ExpandableWrapper<P, C> fromParentWrapper = mFlatItemList.get(fromFlatParentPosition); // If the parent is collapsed we can take advantage of notifyItemMoved otherwise // we are forced to do a "manual" move by removing and then adding the parent + children // (no notifyItemRangeMovedAvailable) boolean isCollapsed = !fromParentWrapper.isExpanded(); boolean isExpandedNoChildren = !isCollapsed && (fromParentWrapper.getWrappedChildList().size() == 0); if (isCollapsed || isExpandedNoChildren) { int toFlatParentPosition = getFlatParentPosition(toParentPosition); ExpandableWrapper<P, C> toParentWrapper = mFlatItemList.get(toFlatParentPosition); mFlatItemList.remove(fromFlatParentPosition); int childOffset = 0; if (toParentWrapper.isExpanded()) { childOffset = toParentWrapper.getWrappedChildList().size(); } mFlatItemList.add(toFlatParentPosition + childOffset, fromParentWrapper); notifyItemMoved(fromFlatParentPosition, toFlatParentPosition + childOffset); } else { // Remove the parent and children int sizeChanged = 0; int childListSize = fromParentWrapper.getWrappedChildList().size(); for (int i = 0; i < childListSize + 1; i++) { mFlatItemList.remove(fromFlatParentPosition); sizeChanged++; } notifyItemRangeRemoved(fromFlatParentPosition, sizeChanged); // Add the parent and children at new position int toFlatParentPosition = getFlatParentPosition(toParentPosition); int childOffset = 0; if (toFlatParentPosition != INVALID_FLAT_POSITION) { ExpandableWrapper<P, C> toParentWrapper = mFlatItemList.get(toFlatParentPosition); if (toParentWrapper.isExpanded()) { childOffset = toParentWrapper.getWrappedChildList().size(); } } else { toFlatParentPosition = mFlatItemList.size(); } mFlatItemList.add(toFlatParentPosition + childOffset, fromParentWrapper); List<ExpandableWrapper<P, C>> wrappedChildList = fromParentWrapper.getWrappedChildList(); sizeChanged = wrappedChildList.size() + 1; mFlatItemList.addAll(toFlatParentPosition + childOffset + 1, wrappedChildList); notifyItemRangeInserted(toFlatParentPosition + childOffset, sizeChanged); } }
java
@UiThread public void notifyParentMoved(int fromParentPosition, int toParentPosition) { int fromFlatParentPosition = getFlatParentPosition(fromParentPosition); ExpandableWrapper<P, C> fromParentWrapper = mFlatItemList.get(fromFlatParentPosition); // If the parent is collapsed we can take advantage of notifyItemMoved otherwise // we are forced to do a "manual" move by removing and then adding the parent + children // (no notifyItemRangeMovedAvailable) boolean isCollapsed = !fromParentWrapper.isExpanded(); boolean isExpandedNoChildren = !isCollapsed && (fromParentWrapper.getWrappedChildList().size() == 0); if (isCollapsed || isExpandedNoChildren) { int toFlatParentPosition = getFlatParentPosition(toParentPosition); ExpandableWrapper<P, C> toParentWrapper = mFlatItemList.get(toFlatParentPosition); mFlatItemList.remove(fromFlatParentPosition); int childOffset = 0; if (toParentWrapper.isExpanded()) { childOffset = toParentWrapper.getWrappedChildList().size(); } mFlatItemList.add(toFlatParentPosition + childOffset, fromParentWrapper); notifyItemMoved(fromFlatParentPosition, toFlatParentPosition + childOffset); } else { // Remove the parent and children int sizeChanged = 0; int childListSize = fromParentWrapper.getWrappedChildList().size(); for (int i = 0; i < childListSize + 1; i++) { mFlatItemList.remove(fromFlatParentPosition); sizeChanged++; } notifyItemRangeRemoved(fromFlatParentPosition, sizeChanged); // Add the parent and children at new position int toFlatParentPosition = getFlatParentPosition(toParentPosition); int childOffset = 0; if (toFlatParentPosition != INVALID_FLAT_POSITION) { ExpandableWrapper<P, C> toParentWrapper = mFlatItemList.get(toFlatParentPosition); if (toParentWrapper.isExpanded()) { childOffset = toParentWrapper.getWrappedChildList().size(); } } else { toFlatParentPosition = mFlatItemList.size(); } mFlatItemList.add(toFlatParentPosition + childOffset, fromParentWrapper); List<ExpandableWrapper<P, C>> wrappedChildList = fromParentWrapper.getWrappedChildList(); sizeChanged = wrappedChildList.size() + 1; mFlatItemList.addAll(toFlatParentPosition + childOffset + 1, wrappedChildList); notifyItemRangeInserted(toFlatParentPosition + childOffset, sizeChanged); } }
[ "@", "UiThread", "public", "void", "notifyParentMoved", "(", "int", "fromParentPosition", ",", "int", "toParentPosition", ")", "{", "int", "fromFlatParentPosition", "=", "getFlatParentPosition", "(", "fromParentPosition", ")", ";", "ExpandableWrapper", "<", "P", ",", ...
Notify any registered observers that the parent and its children reflected at {@code fromParentPosition} has been moved to {@code toParentPosition}. <p> <p>This is a structural change event. Representations of other existing items in the data set are still considered up to date and will not be rebound, though their positions may be altered.</p> @param fromParentPosition Previous position of the parent, relative to the list of parents only. @param toParentPosition New position of the parent, relative to the list of parents only.
[ "Notify", "any", "registered", "observers", "that", "the", "parent", "and", "its", "children", "reflected", "at", "{", "@code", "fromParentPosition", "}", "has", "been", "moved", "to", "{", "@code", "toParentPosition", "}", ".", "<p", ">", "<p", ">", "This",...
train
https://github.com/bignerdranch/expandable-recycler-view/blob/930912510620894c531d236856fa79d646e2f1ed/expandablerecyclerview/src/main/java/com/bignerdranch/expandablerecyclerview/ExpandableRecyclerAdapter.java#L1057-L1109
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java
AMPManager.isActionSupported
public static boolean isActionSupported(XMPPConnection connection, AMPExtension.Action action) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { String featureName = AMPExtension.NAMESPACE + "?action=" + action.toString(); return isFeatureSupportedByServer(connection, featureName); }
java
public static boolean isActionSupported(XMPPConnection connection, AMPExtension.Action action) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException { String featureName = AMPExtension.NAMESPACE + "?action=" + action.toString(); return isFeatureSupportedByServer(connection, featureName); }
[ "public", "static", "boolean", "isActionSupported", "(", "XMPPConnection", "connection", ",", "AMPExtension", ".", "Action", "action", ")", "throws", "NoResponseException", ",", "XMPPErrorException", ",", "NotConnectedException", ",", "InterruptedException", "{", "String"...
Check if server supports specified action. @param connection active xmpp connection @param action action to check @return true if this action is supported. @throws XMPPErrorException @throws NoResponseException @throws NotConnectedException @throws InterruptedException
[ "Check", "if", "server", "supports", "specified", "action", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/amp/AMPManager.java#L93-L96
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/BaseGraph.java
BaseGraph.initNodeRefs
void initNodeRefs(long oldCapacity, long newCapacity) { for (long pointer = oldCapacity + N_EDGE_REF; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, EdgeIterator.NO_EDGE); } if (extStorage.isRequireNodeField()) { for (long pointer = oldCapacity + N_ADDITIONAL; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, extStorage.getDefaultNodeFieldValue()); } } }
java
void initNodeRefs(long oldCapacity, long newCapacity) { for (long pointer = oldCapacity + N_EDGE_REF; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, EdgeIterator.NO_EDGE); } if (extStorage.isRequireNodeField()) { for (long pointer = oldCapacity + N_ADDITIONAL; pointer < newCapacity; pointer += nodeEntryBytes) { nodes.setInt(pointer, extStorage.getDefaultNodeFieldValue()); } } }
[ "void", "initNodeRefs", "(", "long", "oldCapacity", ",", "long", "newCapacity", ")", "{", "for", "(", "long", "pointer", "=", "oldCapacity", "+", "N_EDGE_REF", ";", "pointer", "<", "newCapacity", ";", "pointer", "+=", "nodeEntryBytes", ")", "{", "nodes", "."...
Initializes the node area with the empty edge value and default additional value.
[ "Initializes", "the", "node", "area", "with", "the", "empty", "edge", "value", "and", "default", "additional", "value", "." ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/BaseGraph.java#L258-L267
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/ChatApi.java
ChatApi.sendMessage
public ApiSuccessResponse sendMessage(String id, AcceptData1 acceptData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = sendMessageWithHttpInfo(id, acceptData); return resp.getData(); }
java
public ApiSuccessResponse sendMessage(String id, AcceptData1 acceptData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = sendMessageWithHttpInfo(id, acceptData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "sendMessage", "(", "String", "id", ",", "AcceptData1", "acceptData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "sendMessageWithHttpInfo", "(", "id", ",", "acceptData", ")", ";", ...
Send a message Send a message to participants in the specified chat. @param id The ID of the chat interaction. (required) @param acceptData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Send", "a", "message", "Send", "a", "message", "to", "participants", "in", "the", "specified", "chat", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/ChatApi.java#L1572-L1575
bwkimmel/java-util
src/main/java/ca/eandb/util/FloatArray.java
FloatArray.addAll
public boolean addAll(int index, float[] items) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } ensureCapacity(size + items.length); if (index < size) { for (int i = size - 1; i >= index; i--) { elements[i + items.length] = elements[i]; } } for (float e : items) { elements[index++] = e; } size += items.length; return items.length > 0; }
java
public boolean addAll(int index, float[] items) { if (index < 0 || index > size) { throw new IndexOutOfBoundsException(); } ensureCapacity(size + items.length); if (index < size) { for (int i = size - 1; i >= index; i--) { elements[i + items.length] = elements[i]; } } for (float e : items) { elements[index++] = e; } size += items.length; return items.length > 0; }
[ "public", "boolean", "addAll", "(", "int", "index", ",", "float", "[", "]", "items", ")", "{", "if", "(", "index", "<", "0", "||", "index", ">", "size", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "}", "ensureCapacity", "(", ...
Inserts values into the array at the specified index. @param index The index at which to insert the new values. @param items An array of values to insert. @return A value indicating if the array has changed. @throws IndexOutOfBoundsException if <code>index &lt; 0 || index &gt; size()</code>.
[ "Inserts", "values", "into", "the", "array", "at", "the", "specified", "index", "." ]
train
https://github.com/bwkimmel/java-util/blob/0c03664d42f0e6b111f64447f222aa73c2819e5c/src/main/java/ca/eandb/util/FloatArray.java#L429-L444
motown-io/motown
chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java
DomainService.deleteEvse
public void deleteEvse(Long chargingStationTypeId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); chargingStationType.getEvses().remove(getEvseById(chargingStationType, id)); updateChargingStationType(chargingStationType.getId(), chargingStationType); }
java
public void deleteEvse(Long chargingStationTypeId, Long id) { ChargingStationType chargingStationType = chargingStationTypeRepository.findOne(chargingStationTypeId); chargingStationType.getEvses().remove(getEvseById(chargingStationType, id)); updateChargingStationType(chargingStationType.getId(), chargingStationType); }
[ "public", "void", "deleteEvse", "(", "Long", "chargingStationTypeId", ",", "Long", "id", ")", "{", "ChargingStationType", "chargingStationType", "=", "chargingStationTypeRepository", ".", "findOne", "(", "chargingStationTypeId", ")", ";", "chargingStationType", ".", "ge...
Delete an evse. @param chargingStationTypeId charging station identifier. @param id the id of the evse to delete.
[ "Delete", "an", "evse", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/chargingstation-configuration/view-model/src/main/java/io/motown/chargingstationconfiguration/viewmodel/domain/DomainService.java#L304-L310
hypercube1024/firefly
firefly/src/main/java/com/firefly/codec/websocket/utils/QuoteUtil.java
QuoteUtil.quoteIfNeeded
public static void quoteIfNeeded(StringBuilder buf, String str, String delim) { if (str == null) { return; } // check for delimiters in input string int len = str.length(); if (len == 0) { return; } int ch; for (int i = 0; i < len; i++) { ch = str.codePointAt(i); if (delim.indexOf(ch) >= 0) { // found a delimiter codepoint. we need to quote it. quote(buf, str); return; } } // no special delimiters used, no quote needed. buf.append(str); }
java
public static void quoteIfNeeded(StringBuilder buf, String str, String delim) { if (str == null) { return; } // check for delimiters in input string int len = str.length(); if (len == 0) { return; } int ch; for (int i = 0; i < len; i++) { ch = str.codePointAt(i); if (delim.indexOf(ch) >= 0) { // found a delimiter codepoint. we need to quote it. quote(buf, str); return; } } // no special delimiters used, no quote needed. buf.append(str); }
[ "public", "static", "void", "quoteIfNeeded", "(", "StringBuilder", "buf", ",", "String", "str", ",", "String", "delim", ")", "{", "if", "(", "str", "==", "null", ")", "{", "return", ";", "}", "// check for delimiters in input string", "int", "len", "=", "str...
Append into buf the provided string, adding quotes if needed. <p> Quoting is determined if any of the characters in the <code>delim</code> are found in the input <code>str</code>. @param buf the buffer to append to @param str the string to possibly quote @param delim the delimiter characters that will trigger automatic quoting
[ "Append", "into", "buf", "the", "provided", "string", "adding", "quotes", "if", "needed", ".", "<p", ">", "Quoting", "is", "determined", "if", "any", "of", "the", "characters", "in", "the", "<code", ">", "delim<", "/", "code", ">", "are", "found", "in", ...
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly/src/main/java/com/firefly/codec/websocket/utils/QuoteUtil.java#L245-L266
UrielCh/ovh-java-sdk
ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java
ApiOvhTelephony.spare_spare_serviceInfos_GET
public OvhService spare_spare_serviceInfos_GET(String spare) throws IOException { String qPath = "/telephony/spare/{spare}/serviceInfos"; StringBuilder sb = path(qPath, spare); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhService.class); }
java
public OvhService spare_spare_serviceInfos_GET(String spare) throws IOException { String qPath = "/telephony/spare/{spare}/serviceInfos"; StringBuilder sb = path(qPath, spare); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhService.class); }
[ "public", "OvhService", "spare_spare_serviceInfos_GET", "(", "String", "spare", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/telephony/spare/{spare}/serviceInfos\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "spare", ")", ";", "St...
Get this object properties REST: GET /telephony/spare/{spare}/serviceInfos @param spare [required] The internal name of your spare
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L9065-L9070
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.addVariableMappingForField
public void addVariableMappingForField(DifferentialFunction function, String fieldName, String varName) { fieldVariableResolutionMapping.put(function.getOwnName(), fieldName, varName); }
java
public void addVariableMappingForField(DifferentialFunction function, String fieldName, String varName) { fieldVariableResolutionMapping.put(function.getOwnName(), fieldName, varName); }
[ "public", "void", "addVariableMappingForField", "(", "DifferentialFunction", "function", ",", "String", "fieldName", ",", "String", "varName", ")", "{", "fieldVariableResolutionMapping", ".", "put", "(", "function", ".", "getOwnName", "(", ")", ",", "fieldName", ","...
Adds a field name -> variable name mapping for a given function.<br> This is used for model import where there is an unresolved variable at the time of calling any {@link org.nd4j.imports.graphmapper.GraphMapper#importGraph(File)} . <p> This data structure is typically accessed during {@link DifferentialFunction#resolvePropertiesFromSameDiffBeforeExecution()} <p> When a function attempts to resolve variables right before execution, there needs to be a way of knowing which variable in a samediff graph should map to a function's particular field name @param function the function to map @param fieldName the field name for the function to map @param varName the variable name of the array to get from samediff
[ "Adds", "a", "field", "name", "-", ">", "variable", "name", "mapping", "for", "a", "given", "function", ".", "<br", ">", "This", "is", "used", "for", "model", "import", "where", "there", "is", "an", "unresolved", "variable", "at", "the", "time", "of", ...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L1033-L1035
wonderpush/wonderpush-android-sdk
sdk/src/main/java/com/wonderpush/sdk/DataManager.java
DataManager.downloadAllData
static boolean downloadAllData() { String data; try { data = export().get(); } catch (InterruptedException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } catch (ExecutionException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); File folder = new File(WonderPush.getApplicationContext().getFilesDir(), "exports"); folder.mkdirs(); String fn = "wonderpush-android-dataexport-" + sdf.format(new Date()) + ".json"; File f = new File(folder, fn); OutputStream os = new FileOutputStream(f); os.write(data.getBytes()); os.close(); File fz = new File(folder, fn + ".zip"); ZipOutputStream osz = new ZipOutputStream(new FileOutputStream(fz)); osz.putNextEntry(new ZipEntry(fn)); osz.write(data.getBytes()); osz.closeEntry(); osz.finish(); osz.close(); Uri uri = FileProvider.getUriForFile(WonderPush.getApplicationContext(), WonderPush.getApplicationContext().getPackageName() + ".wonderpush.fileprovider", fz); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_STREAM, uri); sendIntent.setType("application/zip"); sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); WonderPush.getApplicationContext().startActivity(Intent.createChooser(sendIntent, WonderPush.getApplicationContext().getResources().getText(R.string.wonderpush_export_data_chooser))); return true; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } }
java
static boolean downloadAllData() { String data; try { data = export().get(); } catch (InterruptedException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } catch (ExecutionException ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); File folder = new File(WonderPush.getApplicationContext().getFilesDir(), "exports"); folder.mkdirs(); String fn = "wonderpush-android-dataexport-" + sdf.format(new Date()) + ".json"; File f = new File(folder, fn); OutputStream os = new FileOutputStream(f); os.write(data.getBytes()); os.close(); File fz = new File(folder, fn + ".zip"); ZipOutputStream osz = new ZipOutputStream(new FileOutputStream(fz)); osz.putNextEntry(new ZipEntry(fn)); osz.write(data.getBytes()); osz.closeEntry(); osz.finish(); osz.close(); Uri uri = FileProvider.getUriForFile(WonderPush.getApplicationContext(), WonderPush.getApplicationContext().getPackageName() + ".wonderpush.fileprovider", fz); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_STREAM, uri); sendIntent.setType("application/zip"); sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); WonderPush.getApplicationContext().startActivity(Intent.createChooser(sendIntent, WonderPush.getApplicationContext().getResources().getText(R.string.wonderpush_export_data_chooser))); return true; } catch (Exception ex) { Log.e(WonderPush.TAG, "Unexpected error while exporting data", ex); return false; } }
[ "static", "boolean", "downloadAllData", "(", ")", "{", "String", "data", ";", "try", "{", "data", "=", "export", "(", ")", ".", "get", "(", ")", ";", "}", "catch", "(", "InterruptedException", "ex", ")", "{", "Log", ".", "e", "(", "WonderPush", ".", ...
Blocks until interrupted or completed. @return {@code true} if successfully called startActivity() with a sharing intent.
[ "Blocks", "until", "interrupted", "or", "completed", "." ]
train
https://github.com/wonderpush/wonderpush-android-sdk/blob/ba0a1568f705cdd6206639bfab1e5cf529084b59/sdk/src/main/java/com/wonderpush/sdk/DataManager.java#L191-L234
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuGLGetDevices
public static int cuGLGetDevices(int pCudaDeviceCount[], CUdevice pCudaDevices[], int cudaDeviceCount, int CUGLDeviceList_deviceList) { return checkResult(cuGLGetDevicesNative(pCudaDeviceCount, pCudaDevices, cudaDeviceCount, CUGLDeviceList_deviceList)); }
java
public static int cuGLGetDevices(int pCudaDeviceCount[], CUdevice pCudaDevices[], int cudaDeviceCount, int CUGLDeviceList_deviceList) { return checkResult(cuGLGetDevicesNative(pCudaDeviceCount, pCudaDevices, cudaDeviceCount, CUGLDeviceList_deviceList)); }
[ "public", "static", "int", "cuGLGetDevices", "(", "int", "pCudaDeviceCount", "[", "]", ",", "CUdevice", "pCudaDevices", "[", "]", ",", "int", "cudaDeviceCount", ",", "int", "CUGLDeviceList_deviceList", ")", "{", "return", "checkResult", "(", "cuGLGetDevicesNative", ...
Gets the CUDA devices associated with the current OpenGL context. <pre> CUresult cuGLGetDevices ( unsigned int* pCudaDeviceCount, CUdevice* pCudaDevices, unsigned int cudaDeviceCount, CUGLDeviceList deviceList ) </pre> <div> <p>Gets the CUDA devices associated with the current OpenGL context. Returns in <tt>*pCudaDeviceCount</tt> the number of CUDA-compatible devices corresponding to the current OpenGL context. Also returns in <tt>*pCudaDevices</tt> at most cudaDeviceCount of the CUDA-compatible devices corresponding to the current OpenGL context. If any of the GPUs being used by the current OpenGL context are not CUDA capable then the call will return CUDA_ERROR_NO_DEVICE. </p> <p>The <tt>deviceList</tt> argument may be any of the following: <ul> <li> <p>CU_GL_DEVICE_LIST_ALL: Query all devices used by the current OpenGL context. </p> </li> <li> <p>CU_GL_DEVICE_LIST_CURRENT_FRAME: Query the devices used by the current OpenGL context to render the current frame (in SLI). </p> </li> <li> <p>CU_GL_DEVICE_LIST_NEXT_FRAME: Query the devices used by the current OpenGL context to render the next frame (in SLI). Note that this is a prediction, it can't be guaranteed that this is correct in all cases. </p> </li> </ul> </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param pCudaDeviceCount Returned number of CUDA devices. @param pCudaDevices Returned CUDA devices. @param cudaDeviceCount The size of the output device array pCudaDevices. @param deviceList The set of devices to return. @return CUDA_SUCCESS, CUDA_ERROR_NO_DEVICE, CUDA_ERROR_INVALID_VALUECUDA_ERROR_INVALID_CONTEXT
[ "Gets", "the", "CUDA", "devices", "associated", "with", "the", "current", "OpenGL", "context", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L15187-L15190
xmlet/XsdAsmFaster
src/main/java/org/xmlet/xsdasmfaster/classes/XsdSupportingStructure.java
XsdSupportingStructure.textGroupMethod
private static void textGroupMethod(ClassWriter classWriter, String varName, String visitName){ MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, varName, "(" + JAVA_OBJECT_DESC + ")" + elementTypeDesc, "<R:" + JAVA_OBJECT_DESC + ">(TR;)TT;", null); mVisitor.visitLocalVariable(varName, JAVA_STRING_DESC, null, new Label(), new Label(),1); mVisitor.visitCode(); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "getVisitor", "()" + elementVisitorTypeDesc, true); mVisitor.visitTypeInsn(NEW, textType); mVisitor.visitInsn(DUP); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "self", "()" + elementTypeDesc, true); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "getVisitor", "()" + elementVisitorTypeDesc, true); mVisitor.visitVarInsn(ALOAD, 1); mVisitor.visitMethodInsn(INVOKESPECIAL, textType, CONSTRUCTOR, "(" + elementTypeDesc + elementVisitorTypeDesc + JAVA_OBJECT_DESC + ")V", false); mVisitor.visitMethodInsn(INVOKEVIRTUAL, elementVisitorType, visitName, "(" + textTypeDesc + ")V", false); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "self", "()" + elementTypeDesc, true); mVisitor.visitInsn(ARETURN); mVisitor.visitMaxs(6, 2); mVisitor.visitEnd(); }
java
private static void textGroupMethod(ClassWriter classWriter, String varName, String visitName){ MethodVisitor mVisitor = classWriter.visitMethod(ACC_PUBLIC, varName, "(" + JAVA_OBJECT_DESC + ")" + elementTypeDesc, "<R:" + JAVA_OBJECT_DESC + ">(TR;)TT;", null); mVisitor.visitLocalVariable(varName, JAVA_STRING_DESC, null, new Label(), new Label(),1); mVisitor.visitCode(); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "getVisitor", "()" + elementVisitorTypeDesc, true); mVisitor.visitTypeInsn(NEW, textType); mVisitor.visitInsn(DUP); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "self", "()" + elementTypeDesc, true); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "getVisitor", "()" + elementVisitorTypeDesc, true); mVisitor.visitVarInsn(ALOAD, 1); mVisitor.visitMethodInsn(INVOKESPECIAL, textType, CONSTRUCTOR, "(" + elementTypeDesc + elementVisitorTypeDesc + JAVA_OBJECT_DESC + ")V", false); mVisitor.visitMethodInsn(INVOKEVIRTUAL, elementVisitorType, visitName, "(" + textTypeDesc + ")V", false); mVisitor.visitVarInsn(ALOAD, 0); mVisitor.visitMethodInsn(INVOKEINTERFACE, textGroupType, "self", "()" + elementTypeDesc, true); mVisitor.visitInsn(ARETURN); mVisitor.visitMaxs(6, 2); mVisitor.visitEnd(); }
[ "private", "static", "void", "textGroupMethod", "(", "ClassWriter", "classWriter", ",", "String", "varName", ",", "String", "visitName", ")", "{", "MethodVisitor", "mVisitor", "=", "classWriter", ".", "visitMethod", "(", "ACC_PUBLIC", ",", "varName", ",", "\"(\"",...
Creates a method present in the TextGroup interface. Code: getVisitor().visitComment(new Text<>(self(), getVisitor(), text)); return this.self(); @param classWriter The TextGroup {@link ClassWriter} object. @param varName The name of the method, i.e. text or comment. @param visitName The name of the visit method to invoke on the method, i.e. visitText or visitComment.
[ "Creates", "a", "method", "present", "in", "the", "TextGroup", "interface", ".", "Code", ":", "getVisitor", "()", ".", "visitComment", "(", "new", "Text<", ">", "(", "self", "()", "getVisitor", "()", "text", "))", ";", "return", "this", ".", "self", "()"...
train
https://github.com/xmlet/XsdAsmFaster/blob/ccb78f9dd4b957ad5ac1ca349eaf24338c421e94/src/main/java/org/xmlet/xsdasmfaster/classes/XsdSupportingStructure.java#L181-L201
DV8FromTheWorld/JDA
src/main/java/net/dv8tion/jda/core/utils/PermissionUtil.java
PermissionUtil.getEffectivePermission
public static long getEffectivePermission(Channel channel, Role role) { Checks.notNull(channel, "Channel"); Checks.notNull(role, "Role"); Guild guild = channel.getGuild(); if (!guild.equals(role.getGuild())) throw new IllegalArgumentException("Provided channel and role are not of the same guild!"); long permissions = role.getPermissionsRaw() | guild.getPublicRole().getPermissionsRaw(); PermissionOverride publicOverride = channel.getPermissionOverride(guild.getPublicRole()); PermissionOverride roleOverride = channel.getPermissionOverride(role); if (publicOverride != null) { permissions &= ~publicOverride.getDeniedRaw(); permissions |= publicOverride.getAllowedRaw(); } if (roleOverride != null) { permissions &= ~roleOverride.getDeniedRaw(); permissions |= roleOverride.getAllowedRaw(); } return permissions; }
java
public static long getEffectivePermission(Channel channel, Role role) { Checks.notNull(channel, "Channel"); Checks.notNull(role, "Role"); Guild guild = channel.getGuild(); if (!guild.equals(role.getGuild())) throw new IllegalArgumentException("Provided channel and role are not of the same guild!"); long permissions = role.getPermissionsRaw() | guild.getPublicRole().getPermissionsRaw(); PermissionOverride publicOverride = channel.getPermissionOverride(guild.getPublicRole()); PermissionOverride roleOverride = channel.getPermissionOverride(role); if (publicOverride != null) { permissions &= ~publicOverride.getDeniedRaw(); permissions |= publicOverride.getAllowedRaw(); } if (roleOverride != null) { permissions &= ~roleOverride.getDeniedRaw(); permissions |= roleOverride.getAllowedRaw(); } return permissions; }
[ "public", "static", "long", "getEffectivePermission", "(", "Channel", "channel", ",", "Role", "role", ")", "{", "Checks", ".", "notNull", "(", "channel", ",", "\"Channel\"", ")", ";", "Checks", ".", "notNull", "(", "role", ",", "\"Role\"", ")", ";", "Guild...
Gets the {@code long} representation of the effective permissions allowed for this {@link net.dv8tion.jda.core.entities.Role Role} in this {@link net.dv8tion.jda.core.entities.Channel Channel}. This can be used in conjunction with {@link net.dv8tion.jda.core.Permission#getPermissions(long) Permission.getPermissions(long)} to easily get a list of all {@link net.dv8tion.jda.core.Permission Permissions} that this role can use in this {@link net.dv8tion.jda.core.entities.Channel Channel}. @param channel The {@link net.dv8tion.jda.core.entities.Channel Channel} in which permissions are being checked. @param role The {@link net.dv8tion.jda.core.entities.Role Role} whose permissions are being checked. @throws IllegalArgumentException if any of the provided parameters is {@code null} or the provided entities are not from the same guild @return The {@code long} representation of the effective permissions that this {@link net.dv8tion.jda.core.entities.Role Role} has in this {@link net.dv8tion.jda.core.entities.Channel Channel}
[ "Gets", "the", "{", "@code", "long", "}", "representation", "of", "the", "effective", "permissions", "allowed", "for", "this", "{", "@link", "net", ".", "dv8tion", ".", "jda", ".", "core", ".", "entities", ".", "Role", "Role", "}", "in", "this", "{", "...
train
https://github.com/DV8FromTheWorld/JDA/blob/8ecbbe354d03f6bf448411bba573d0d4c268b560/src/main/java/net/dv8tion/jda/core/utils/PermissionUtil.java#L424-L451
lessthanoptimal/ejml
main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java
CommonOps_DDRM.elementDiv
public static void elementDiv(DMatrixD1 a , DMatrixD1 b ) { if( a.numCols != b.numCols || a.numRows != b.numRows ) { throw new MatrixDimensionException("The 'a' and 'b' matrices do not have compatible dimensions"); } int length = a.getNumElements(); for( int i = 0; i < length; i++ ) { a.div(i, b.get(i)); } }
java
public static void elementDiv(DMatrixD1 a , DMatrixD1 b ) { if( a.numCols != b.numCols || a.numRows != b.numRows ) { throw new MatrixDimensionException("The 'a' and 'b' matrices do not have compatible dimensions"); } int length = a.getNumElements(); for( int i = 0; i < length; i++ ) { a.div(i, b.get(i)); } }
[ "public", "static", "void", "elementDiv", "(", "DMatrixD1", "a", ",", "DMatrixD1", "b", ")", "{", "if", "(", "a", ".", "numCols", "!=", "b", ".", "numCols", "||", "a", ".", "numRows", "!=", "b", ".", "numRows", ")", "{", "throw", "new", "MatrixDimens...
<p>Performs the an element by element division operation:<br> <br> a<sub>ij</sub> = a<sub>ij</sub> / b<sub>ij</sub> <br> </p> @param a The left matrix in the division operation. Modified. @param b The right matrix in the division operation. Not modified.
[ "<p", ">", "Performs", "the", "an", "element", "by", "element", "division", "operation", ":", "<br", ">", "<br", ">", "a<sub", ">", "ij<", "/", "sub", ">", "=", "a<sub", ">", "ij<", "/", "sub", ">", "/", "b<sub", ">", "ij<", "/", "sub", ">", "<br...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L1551-L1562
bozaro/git-lfs-java
gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java
Client.getObject
@NotNull public <T> T getObject(@Nullable final Meta meta, @NotNull final Links links, @NotNull final StreamHandler<T> handler) throws IOException { final Link link = links.getLinks().get(LinkType.Download); if (link == null) { throw new FileNotFoundException(); } return doRequest(link, new ObjectGet<>(inputStream -> handler.accept(meta != null ? new InputStreamValidator(inputStream, meta) : inputStream)), link.getHref()); }
java
@NotNull public <T> T getObject(@Nullable final Meta meta, @NotNull final Links links, @NotNull final StreamHandler<T> handler) throws IOException { final Link link = links.getLinks().get(LinkType.Download); if (link == null) { throw new FileNotFoundException(); } return doRequest(link, new ObjectGet<>(inputStream -> handler.accept(meta != null ? new InputStreamValidator(inputStream, meta) : inputStream)), link.getHref()); }
[ "@", "NotNull", "public", "<", "T", ">", "T", "getObject", "(", "@", "Nullable", "final", "Meta", "meta", ",", "@", "NotNull", "final", "Links", "links", ",", "@", "NotNull", "final", "StreamHandler", "<", "T", ">", "handler", ")", "throws", "IOException...
Download object by metadata. @param meta Object metadata for stream validation. @param links Object links. @param handler Stream handler. @return Stream handler result. @throws FileNotFoundException File not found exception if object don't exists on LFS server. @throws IOException On some errors.
[ "Download", "object", "by", "metadata", "." ]
train
https://github.com/bozaro/git-lfs-java/blob/ee05bf0472ee61bf362cf93d283e5ee5d44ef685/gitlfs-client/src/main/java/ru/bozaro/gitlfs/client/Client.java#L151-L158
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java
AppServicePlansInner.listUsagesWithServiceResponseAsync
public Observable<ServiceResponse<Page<CsmUsageQuotaInner>>> listUsagesWithServiceResponseAsync(final String resourceGroupName, final String name, final String filter) { return listUsagesSinglePageAsync(resourceGroupName, name, filter) .concatMap(new Func1<ServiceResponse<Page<CsmUsageQuotaInner>>, Observable<ServiceResponse<Page<CsmUsageQuotaInner>>>>() { @Override public Observable<ServiceResponse<Page<CsmUsageQuotaInner>>> call(ServiceResponse<Page<CsmUsageQuotaInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listUsagesNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<CsmUsageQuotaInner>>> listUsagesWithServiceResponseAsync(final String resourceGroupName, final String name, final String filter) { return listUsagesSinglePageAsync(resourceGroupName, name, filter) .concatMap(new Func1<ServiceResponse<Page<CsmUsageQuotaInner>>, Observable<ServiceResponse<Page<CsmUsageQuotaInner>>>>() { @Override public Observable<ServiceResponse<Page<CsmUsageQuotaInner>>> call(ServiceResponse<Page<CsmUsageQuotaInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listUsagesNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "CsmUsageQuotaInner", ">", ">", ">", "listUsagesWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ",", "final", "String", "filter", ")", "{", "r...
Gets server farm usage information. Gets server farm usage information. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of App Service Plan @param filter Return only usages/metrics specified in the filter. Filter conforms to odata syntax. Example: $filter=(name.value eq 'Metric1' or name.value eq 'Metric2'). @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;CsmUsageQuotaInner&gt; object
[ "Gets", "server", "farm", "usage", "information", ".", "Gets", "server", "farm", "usage", "information", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L2915-L2927
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/AbstractInputHandler.java
AbstractInputHandler.handleControlMessage
public void handleControlMessage(SIBUuid8 sourceMEUuid, ControlMessage cMsg) throws SIIncorrectCallException, SIErrorException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "handleControlMessage", new Object[] { sourceMEUuid, cMsg }); // Next work out type of ControlMessage and process it ControlMessageType type = cMsg.getControlMessageType(); // First check to see whether this is an "are you flushed" reply. // Such messages will not be mappable to a stream ID since we // don't yet have a stream data structure (that's why we sent the // query in the first place). Or...these could be stale messages // for streams we don't care about. Either way, handle them // elsewhere. if(type == ControlMessageType.FLUSHED) { _targetStreamManager.handleFlushedMessage((ControlFlushed)cMsg); } else if(type == ControlMessageType.NOTFLUSHED) { _targetStreamManager.handleNotFlushedMessage((ControlNotFlushed)cMsg); } else if (type == ControlMessageType.SILENCE) { _targetStreamManager.handleSilenceMessage((ControlSilence) cMsg); } else if (type == ControlMessageType.ACKEXPECTED) { _targetStreamManager.handleAckExpectedMessage((ControlAckExpected) cMsg); } else { // Not a recognised type // throw exception } }
java
public void handleControlMessage(SIBUuid8 sourceMEUuid, ControlMessage cMsg) throws SIIncorrectCallException, SIErrorException, SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "handleControlMessage", new Object[] { sourceMEUuid, cMsg }); // Next work out type of ControlMessage and process it ControlMessageType type = cMsg.getControlMessageType(); // First check to see whether this is an "are you flushed" reply. // Such messages will not be mappable to a stream ID since we // don't yet have a stream data structure (that's why we sent the // query in the first place). Or...these could be stale messages // for streams we don't care about. Either way, handle them // elsewhere. if(type == ControlMessageType.FLUSHED) { _targetStreamManager.handleFlushedMessage((ControlFlushed)cMsg); } else if(type == ControlMessageType.NOTFLUSHED) { _targetStreamManager.handleNotFlushedMessage((ControlNotFlushed)cMsg); } else if (type == ControlMessageType.SILENCE) { _targetStreamManager.handleSilenceMessage((ControlSilence) cMsg); } else if (type == ControlMessageType.ACKEXPECTED) { _targetStreamManager.handleAckExpectedMessage((ControlAckExpected) cMsg); } else { // Not a recognised type // throw exception } }
[ "public", "void", "handleControlMessage", "(", "SIBUuid8", "sourceMEUuid", ",", "ControlMessage", "cMsg", ")", "throws", "SIIncorrectCallException", ",", "SIErrorException", ",", "SIResourceException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", "...
/* (non-Javadoc) @see com.ibm.ws.sib.processor.impl.interfaces.ControlHandler#handleControlMessage(com.ibm.ws.sib.trm.topology.Cellule, com.ibm.ws.sib.mfp.control.ControlMessage) Handle all downstream control messages i.e. target control messages
[ "/", "*", "(", "non", "-", "Javadoc", ")", "@see", "com", ".", "ibm", ".", "ws", ".", "sib", ".", "processor", ".", "impl", ".", "interfaces", ".", "ControlHandler#handleControlMessage", "(", "com", ".", "ibm", ".", "ws", ".", "sib", ".", "trm", ".",...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/AbstractInputHandler.java#L674-L710
looly/hutool
hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java
MapUtil.sort
public static <K, V> TreeMap<K, V> sort(Map<K, V> map) { return sort(map, null); }
java
public static <K, V> TreeMap<K, V> sort(Map<K, V> map) { return sort(map, null); }
[ "public", "static", "<", "K", ",", "V", ">", "TreeMap", "<", "K", ",", "V", ">", "sort", "(", "Map", "<", "K", ",", "V", ">", "map", ")", "{", "return", "sort", "(", "map", ",", "null", ")", ";", "}" ]
排序已有Map,Key有序的Map,使用默认Key排序方式(字母顺序) @param map Map @return TreeMap @since 4.0.1 @see #newTreeMap(Map, Comparator)
[ "排序已有Map,Key有序的Map,使用默认Key排序方式(字母顺序)" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/map/MapUtil.java#L638-L640
finmath/finmath-lib
src/main/java/net/finmath/modelling/descriptor/xmlparser/FIPXMLParser.java
FIPXMLParser.getSwapLegProductDescriptor
private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName, DayCountConvention daycountConvention) { boolean isFixed = leg.getElementsByTagName("interestType").item(0).getTextContent().equalsIgnoreCase("FIX"); ArrayList<Period> periods = new ArrayList<>(); ArrayList<Double> notionalsList = new ArrayList<>(); ArrayList<Double> rates = new ArrayList<>(); //extracting data for each period NodeList periodsXML = leg.getElementsByTagName("incomePayment"); for(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) { Element periodXML = (Element) periodsXML.item(periodIndex); LocalDate startDate = LocalDate.parse(periodXML.getElementsByTagName("startDate").item(0).getTextContent()); LocalDate endDate = LocalDate.parse(periodXML.getElementsByTagName("endDate").item(0).getTextContent()); LocalDate fixingDate = startDate; LocalDate paymentDate = LocalDate.parse(periodXML.getElementsByTagName("payDate").item(0).getTextContent()); if(! isFixed) { fixingDate = LocalDate.parse(periodXML.getElementsByTagName("fixingDate").item(0).getTextContent()); } periods.add(new Period(fixingDate, paymentDate, startDate, endDate)); double notional = Double.parseDouble(periodXML.getElementsByTagName("nominal").item(0).getTextContent()); notionalsList.add(new Double(notional)); if(isFixed) { double fixedRate = Double.parseDouble(periodXML.getElementsByTagName("fixedRate").item(0).getTextContent()); rates.add(new Double(fixedRate)); } else { rates.add(new Double(0)); } } ScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention); double[] notionals = notionalsList.stream().mapToDouble(Double::doubleValue).toArray(); double[] spreads = rates.stream().mapToDouble(Double::doubleValue).toArray(); return new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false); }
java
private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName, DayCountConvention daycountConvention) { boolean isFixed = leg.getElementsByTagName("interestType").item(0).getTextContent().equalsIgnoreCase("FIX"); ArrayList<Period> periods = new ArrayList<>(); ArrayList<Double> notionalsList = new ArrayList<>(); ArrayList<Double> rates = new ArrayList<>(); //extracting data for each period NodeList periodsXML = leg.getElementsByTagName("incomePayment"); for(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) { Element periodXML = (Element) periodsXML.item(periodIndex); LocalDate startDate = LocalDate.parse(periodXML.getElementsByTagName("startDate").item(0).getTextContent()); LocalDate endDate = LocalDate.parse(periodXML.getElementsByTagName("endDate").item(0).getTextContent()); LocalDate fixingDate = startDate; LocalDate paymentDate = LocalDate.parse(periodXML.getElementsByTagName("payDate").item(0).getTextContent()); if(! isFixed) { fixingDate = LocalDate.parse(periodXML.getElementsByTagName("fixingDate").item(0).getTextContent()); } periods.add(new Period(fixingDate, paymentDate, startDate, endDate)); double notional = Double.parseDouble(periodXML.getElementsByTagName("nominal").item(0).getTextContent()); notionalsList.add(new Double(notional)); if(isFixed) { double fixedRate = Double.parseDouble(periodXML.getElementsByTagName("fixedRate").item(0).getTextContent()); rates.add(new Double(fixedRate)); } else { rates.add(new Double(0)); } } ScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention); double[] notionals = notionalsList.stream().mapToDouble(Double::doubleValue).toArray(); double[] spreads = rates.stream().mapToDouble(Double::doubleValue).toArray(); return new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false); }
[ "private", "static", "InterestRateSwapLegProductDescriptor", "getSwapLegProductDescriptor", "(", "Element", "leg", ",", "String", "forwardCurveName", ",", "String", "discountCurveName", ",", "DayCountConvention", "daycountConvention", ")", "{", "boolean", "isFixed", "=", "l...
Construct an InterestRateSwapLegProductDescriptor from a node in a FIPXML file. @param leg The node containing the leg. @param forwardCurveName Forward curve name form outside the node. @param discountCurveName Discount curve name form outside the node. @param daycountConvention Daycount convention from outside the node. @return Descriptor of the swap leg.
[ "Construct", "an", "InterestRateSwapLegProductDescriptor", "from", "a", "node", "in", "a", "FIPXML", "file", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/modelling/descriptor/xmlparser/FIPXMLParser.java#L152-L196
reactor/reactor-netty
src/main/java/reactor/netty/tcp/TcpServer.java
TcpServer.bindUntilJavaShutdown
public final void bindUntilJavaShutdown(Duration timeout, @Nullable Consumer<DisposableServer> onStart) { Objects.requireNonNull(timeout, "timeout"); DisposableServer facade = bindNow(); Objects.requireNonNull(facade, "facade"); if (onStart != null) { onStart.accept(facade); } Runtime.getRuntime() .addShutdownHook(new Thread(() -> facade.disposeNow(timeout))); facade.onDispose() .block(); }
java
public final void bindUntilJavaShutdown(Duration timeout, @Nullable Consumer<DisposableServer> onStart) { Objects.requireNonNull(timeout, "timeout"); DisposableServer facade = bindNow(); Objects.requireNonNull(facade, "facade"); if (onStart != null) { onStart.accept(facade); } Runtime.getRuntime() .addShutdownHook(new Thread(() -> facade.disposeNow(timeout))); facade.onDispose() .block(); }
[ "public", "final", "void", "bindUntilJavaShutdown", "(", "Duration", "timeout", ",", "@", "Nullable", "Consumer", "<", "DisposableServer", ">", "onStart", ")", "{", "Objects", ".", "requireNonNull", "(", "timeout", ",", "\"timeout\"", ")", ";", "DisposableServer",...
Start the server in a fully blocking fashion, not only waiting for it to initialize but also blocking during the full lifecycle of the server. Since most servers will be long-lived, this is more adapted to running a server out of a main method, only allowing shutdown of the servers through {@code sigkill}. <p> Note: {@link Runtime#addShutdownHook(Thread) JVM shutdown hook} is added by this method in order to properly disconnect the server upon receiving a {@code sigkill} signal.</p> @param timeout a timeout for server shutdown @param onStart an optional callback on server start
[ "Start", "the", "server", "in", "a", "fully", "blocking", "fashion", "not", "only", "waiting", "for", "it", "to", "initialize", "but", "also", "blocking", "during", "the", "full", "lifecycle", "of", "the", "server", ".", "Since", "most", "servers", "will", ...
train
https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/tcp/TcpServer.java#L211-L227
pravega/pravega
segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/LogMetadata.java
LogMetadata.removeEmptyLedgers
LogMetadata removeEmptyLedgers(int skipCountFromEnd) { val newLedgers = new ArrayList<LedgerMetadata>(); int cutoffIndex = this.ledgers.size() - skipCountFromEnd; for (int i = 0; i < cutoffIndex; i++) { LedgerMetadata lm = this.ledgers.get(i); if (lm.getStatus() != LedgerMetadata.Status.Empty) { // Not Empty or Unknown: keep it! newLedgers.add(lm); } } // Add the ones from the end, as instructed. for (int i = cutoffIndex; i < this.ledgers.size(); i++) { newLedgers.add(this.ledgers.get(i)); } return new LogMetadata(this.epoch, this.enabled, Collections.unmodifiableList(newLedgers), this.truncationAddress, this.updateVersion.get()); }
java
LogMetadata removeEmptyLedgers(int skipCountFromEnd) { val newLedgers = new ArrayList<LedgerMetadata>(); int cutoffIndex = this.ledgers.size() - skipCountFromEnd; for (int i = 0; i < cutoffIndex; i++) { LedgerMetadata lm = this.ledgers.get(i); if (lm.getStatus() != LedgerMetadata.Status.Empty) { // Not Empty or Unknown: keep it! newLedgers.add(lm); } } // Add the ones from the end, as instructed. for (int i = cutoffIndex; i < this.ledgers.size(); i++) { newLedgers.add(this.ledgers.get(i)); } return new LogMetadata(this.epoch, this.enabled, Collections.unmodifiableList(newLedgers), this.truncationAddress, this.updateVersion.get()); }
[ "LogMetadata", "removeEmptyLedgers", "(", "int", "skipCountFromEnd", ")", "{", "val", "newLedgers", "=", "new", "ArrayList", "<", "LedgerMetadata", ">", "(", ")", ";", "int", "cutoffIndex", "=", "this", ".", "ledgers", ".", "size", "(", ")", "-", "skipCountF...
Removes LedgerMetadata instances for those Ledgers that are known to be empty. @param skipCountFromEnd The number of Ledgers to spare, counting from the end of the LedgerMetadata list. @return A new instance of LogMetadata with the updated ledger list.
[ "Removes", "LedgerMetadata", "instances", "for", "those", "Ledgers", "that", "are", "known", "to", "be", "empty", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/storage/impl/src/main/java/io/pravega/segmentstore/storage/impl/bookkeeper/LogMetadata.java#L165-L182
RestComm/media-core
stun/src/main/java/org/restcomm/media/core/stun/messages/StunMessage.java
StunMessage.validateFingerprint
private static boolean validateFingerprint(FingerprintAttribute fingerprint, byte[] message, int offset, int length) { byte[] incomingCrcBytes = fingerprint.getChecksum(); // now check whether the CRC really is what it's supposed to be. // re calculate the check sum byte[] realCrcBytes = FingerprintAttribute.calculateXorCRC32(message, offset, length); // CRC validation. if (!Arrays.equals(incomingCrcBytes, realCrcBytes)) { if (logger.isDebugEnabled()) { logger.debug("An incoming message arrived with a wrong FINGERPRINT attribute value. " + "CRC Was:" + Arrays.toString(incomingCrcBytes) + ". Should have been:" + Arrays.toString(realCrcBytes) + ". Will ignore."); } return false; } return true; }
java
private static boolean validateFingerprint(FingerprintAttribute fingerprint, byte[] message, int offset, int length) { byte[] incomingCrcBytes = fingerprint.getChecksum(); // now check whether the CRC really is what it's supposed to be. // re calculate the check sum byte[] realCrcBytes = FingerprintAttribute.calculateXorCRC32(message, offset, length); // CRC validation. if (!Arrays.equals(incomingCrcBytes, realCrcBytes)) { if (logger.isDebugEnabled()) { logger.debug("An incoming message arrived with a wrong FINGERPRINT attribute value. " + "CRC Was:" + Arrays.toString(incomingCrcBytes) + ". Should have been:" + Arrays.toString(realCrcBytes) + ". Will ignore."); } return false; } return true; }
[ "private", "static", "boolean", "validateFingerprint", "(", "FingerprintAttribute", "fingerprint", ",", "byte", "[", "]", "message", ",", "int", "offset", ",", "int", "length", ")", "{", "byte", "[", "]", "incomingCrcBytes", "=", "fingerprint", ".", "getChecksum...
Recalculates the FINGERPRINT CRC32 checksum of the <tt>message</tt> array so that we could compare it with the value brought by the {@link FingerprintAttribute}. @param fingerprint the attribute that we need to validate. @param message the message whose CRC32 checksum we'd need to recalculate. @param offset the index in <tt>message</tt> where data starts. @param length the number of bytes in <tt>message</tt> that the CRC32 would need to be calculated over. @return <tt>true</tt> if <tt>FINGERPRINT</tt> contains a valid CRC32 value and <tt>false</tt> otherwise.
[ "Recalculates", "the", "FINGERPRINT", "CRC32", "checksum", "of", "the", "<tt", ">", "message<", "/", "tt", ">", "array", "so", "that", "we", "could", "compare", "it", "with", "the", "value", "brought", "by", "the", "{", "@link", "FingerprintAttribute", "}", ...
train
https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/stun/src/main/java/org/restcomm/media/core/stun/messages/StunMessage.java#L956-L973
mygreen/excel-cellformatter
src/main/java/com/github/mygreen/cellformatter/FormatterResolver.java
FormatterResolver.createDefaultFormatter
protected CellFormatter createDefaultFormatter(final String name, final Locale... locales) { final String key = String.format("format.%s", name); final String defaultFormat = messageResolver.getMessage(key); if(defaultFormat == null) { return null; } CellFormatter formatter = createFormatter(defaultFormat); // ロケールのフォーマットの取得 for(Locale locale : locales) { final String localeFormat = messageResolver.getMessage(locale, key, null); if(localeFormat == null) { continue; } final LocaleSwitchFormatter switchFormatter; if(formatter instanceof LocaleSwitchFormatter) { switchFormatter = (LocaleSwitchFormatter) formatter; } else { // LocaleSwitchFormatterに入れ替える。 switchFormatter = new LocaleSwitchFormatter(formatter); formatter = switchFormatter; } // ロケールごとのフォーマットの登録 if(locale.equals(Locale.JAPANESE)) { switchFormatter.register(createFormatter(localeFormat), JAPANESE_LOCALES); } else { switchFormatter.register(createFormatter(localeFormat), locale); } } return formatter; }
java
protected CellFormatter createDefaultFormatter(final String name, final Locale... locales) { final String key = String.format("format.%s", name); final String defaultFormat = messageResolver.getMessage(key); if(defaultFormat == null) { return null; } CellFormatter formatter = createFormatter(defaultFormat); // ロケールのフォーマットの取得 for(Locale locale : locales) { final String localeFormat = messageResolver.getMessage(locale, key, null); if(localeFormat == null) { continue; } final LocaleSwitchFormatter switchFormatter; if(formatter instanceof LocaleSwitchFormatter) { switchFormatter = (LocaleSwitchFormatter) formatter; } else { // LocaleSwitchFormatterに入れ替える。 switchFormatter = new LocaleSwitchFormatter(formatter); formatter = switchFormatter; } // ロケールごとのフォーマットの登録 if(locale.equals(Locale.JAPANESE)) { switchFormatter.register(createFormatter(localeFormat), JAPANESE_LOCALES); } else { switchFormatter.register(createFormatter(localeFormat), locale); } } return formatter; }
[ "protected", "CellFormatter", "createDefaultFormatter", "(", "final", "String", "name", ",", "final", "Locale", "...", "locales", ")", "{", "final", "String", "key", "=", "String", ".", "format", "(", "\"format.%s\"", ",", "name", ")", ";", "final", "String", ...
指定したインデックスでプロパティに定義されているフォーマットを作成する。 @param name 書式の名前。({@literal format.<書式の名前>=}) @param locales 検索するロケール。 @return 存在しないインデックス番号の時は、nullを返す。
[ "指定したインデックスでプロパティに定義されているフォーマットを作成する。" ]
train
https://github.com/mygreen/excel-cellformatter/blob/e802af273d49889500591e03799c9262cbf29185/src/main/java/com/github/mygreen/cellformatter/FormatterResolver.java#L114-L155
jfinal/jfinal
src/main/java/com/jfinal/plugin/activerecord/Db.java
Db.findByIds
public static Record findByIds(String tableName, String primaryKey, Object... idValues) { return MAIN.findByIds(tableName, primaryKey, idValues); }
java
public static Record findByIds(String tableName, String primaryKey, Object... idValues) { return MAIN.findByIds(tableName, primaryKey, idValues); }
[ "public", "static", "Record", "findByIds", "(", "String", "tableName", ",", "String", "primaryKey", ",", "Object", "...", "idValues", ")", "{", "return", "MAIN", ".", "findByIds", "(", "tableName", ",", "primaryKey", ",", "idValues", ")", ";", "}" ]
Find record by ids. <pre> Example: Record user = Db.findByIds("user", "user_id", 123); Record userRole = Db.findByIds("user_role", "user_id, role_id", 123, 456); </pre> @param tableName the table name of the table @param primaryKey the primary key of the table, composite primary key is separated by comma character: "," @param idValues the id value of the record, it can be composite id values
[ "Find", "record", "by", "ids", ".", "<pre", ">", "Example", ":", "Record", "user", "=", "Db", ".", "findByIds", "(", "user", "user_id", "123", ")", ";", "Record", "userRole", "=", "Db", ".", "findByIds", "(", "user_role", "user_id", "role_id", "123", "...
train
https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/activerecord/Db.java#L332-L334
tractionsoftware/gwt-traction
src/main/java/com/tractionsoftware/gwt/user/client/ui/impl/UTCTimeBoxImplShared.java
UTCTimeBoxImplShared.parseUsingFallbacksWithColon
protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) { if (text.indexOf(':') == -1) { text = text.replace(" ", ""); int numdigits = 0; int lastdigit = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (Character.isDigit(c)) { numdigits++; lastdigit = i; } } if (numdigits == 1 || numdigits == 2) { // insert :00 int colon = lastdigit + 1; text = text.substring(0, colon) + ":00" + text.substring(colon); } else if (numdigits > 2) { // insert : int colon = lastdigit - 1; text = text.substring(0, colon) + ":" + text.substring(colon); } return parseUsingFallbacks(text, timeFormat); } else { return null; } }
java
protected static final Long parseUsingFallbacksWithColon(String text, DateTimeFormat timeFormat) { if (text.indexOf(':') == -1) { text = text.replace(" ", ""); int numdigits = 0; int lastdigit = 0; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (Character.isDigit(c)) { numdigits++; lastdigit = i; } } if (numdigits == 1 || numdigits == 2) { // insert :00 int colon = lastdigit + 1; text = text.substring(0, colon) + ":00" + text.substring(colon); } else if (numdigits > 2) { // insert : int colon = lastdigit - 1; text = text.substring(0, colon) + ":" + text.substring(colon); } return parseUsingFallbacks(text, timeFormat); } else { return null; } }
[ "protected", "static", "final", "Long", "parseUsingFallbacksWithColon", "(", "String", "text", ",", "DateTimeFormat", "timeFormat", ")", "{", "if", "(", "text", ".", "indexOf", "(", "'", "'", ")", "==", "-", "1", ")", "{", "text", "=", "text", ".", "repl...
Attempts to insert a colon so that a value without a colon can be parsed.
[ "Attempts", "to", "insert", "a", "colon", "so", "that", "a", "value", "without", "a", "colon", "can", "be", "parsed", "." ]
train
https://github.com/tractionsoftware/gwt-traction/blob/efc1423c619439763fb064b777b7235e9ce414a3/src/main/java/com/tractionsoftware/gwt/user/client/ui/impl/UTCTimeBoxImplShared.java#L129-L156
craterdog/java-smart-objects
src/main/java/craterdog/smart/SmartObject.java
SmartObject.addSerializableClass
protected void addSerializableClass(Class<?> serializable, Class<?> mixin) { safeMapper.addMixIn(serializable, mixin); fullMapper.addMixIn(serializable, mixin); }
java
protected void addSerializableClass(Class<?> serializable, Class<?> mixin) { safeMapper.addMixIn(serializable, mixin); fullMapper.addMixIn(serializable, mixin); }
[ "protected", "void", "addSerializableClass", "(", "Class", "<", "?", ">", "serializable", ",", "Class", "<", "?", ">", "mixin", ")", "{", "safeMapper", ".", "addMixIn", "(", "serializable", ",", "mixin", ")", ";", "fullMapper", ".", "addMixIn", "(", "seria...
This protected method allows a subclass to add to the mappers a class type that can be serialized using mixin class. @param serializable The type of class that can be serialized using its toString() method. @param mixin The type of class that can be used to serialized the serializable class.
[ "This", "protected", "method", "allows", "a", "subclass", "to", "add", "to", "the", "mappers", "a", "class", "type", "that", "can", "be", "serialized", "using", "mixin", "class", "." ]
train
https://github.com/craterdog/java-smart-objects/blob/6d11e2f345e4d2836e3aca3990c8ed2db330d856/src/main/java/craterdog/smart/SmartObject.java#L265-L268
Samsung/GearVRf
GVRf/Extensions/3DCursor/IODevices/gearwear/PhoneSide/gearinputprovider/src/main/java/com/samsung/mpl/gearinputprovider/backend/InputProviderService.java
InputProviderService.sendEvent
public static void sendEvent(Context context, Parcelable event) { Intent intent = new Intent(EventManager.ACTION_ACCESSORY_EVENT); intent.putExtra(EventManager.EXTRA_EVENT, event); context.sendBroadcast(intent); }
java
public static void sendEvent(Context context, Parcelable event) { Intent intent = new Intent(EventManager.ACTION_ACCESSORY_EVENT); intent.putExtra(EventManager.EXTRA_EVENT, event); context.sendBroadcast(intent); }
[ "public", "static", "void", "sendEvent", "(", "Context", "context", ",", "Parcelable", "event", ")", "{", "Intent", "intent", "=", "new", "Intent", "(", "EventManager", ".", "ACTION_ACCESSORY_EVENT", ")", ";", "intent", ".", "putExtra", "(", "EventManager", "....
Send an event to other applications @param context context in which to send the broadcast @param event event to send
[ "Send", "an", "event", "to", "other", "applications" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/3DCursor/IODevices/gearwear/PhoneSide/gearinputprovider/src/main/java/com/samsung/mpl/gearinputprovider/backend/InputProviderService.java#L286-L290
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/StringUtils.java
StringUtils.joinKeys
public static String joinKeys(final Map<String, ?> aMap, final char aSeparator) { if (aMap.isEmpty()) { return ""; } final Iterator<String> iterator = aMap.keySet().iterator(); final StringBuilder buffer = new StringBuilder(); while (iterator.hasNext()) { buffer.append(iterator.next()).append(aSeparator); } final int length = buffer.length() - 1; return buffer.charAt(length) == aSeparator ? buffer.substring(0, length) : buffer.toString(); }
java
public static String joinKeys(final Map<String, ?> aMap, final char aSeparator) { if (aMap.isEmpty()) { return ""; } final Iterator<String> iterator = aMap.keySet().iterator(); final StringBuilder buffer = new StringBuilder(); while (iterator.hasNext()) { buffer.append(iterator.next()).append(aSeparator); } final int length = buffer.length() - 1; return buffer.charAt(length) == aSeparator ? buffer.substring(0, length) : buffer.toString(); }
[ "public", "static", "String", "joinKeys", "(", "final", "Map", "<", "String", ",", "?", ">", "aMap", ",", "final", "char", "aSeparator", ")", "{", "if", "(", "aMap", ".", "isEmpty", "(", ")", ")", "{", "return", "\"\"", ";", "}", "final", "Iterator",...
Turns the keys in a map into a character delimited string. The order is only consistent if the map is sorted. @param aMap The map from which to pull the keys @param aSeparator The character separator for the construction of the string @return A string constructed from the keys in the map
[ "Turns", "the", "keys", "in", "a", "map", "into", "a", "character", "delimited", "string", ".", "The", "order", "is", "only", "consistent", "if", "the", "map", "is", "sorted", "." ]
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/StringUtils.java#L399-L414
ist-dresden/composum
sling/core/commons/src/main/java/com/composum/sling/core/CoreAdapterFactory.java
CoreAdapterFactory.getAdapter
protected static <AdapterType> AdapterType getAdapter(Resource resource, Class<AdapterType> type) { if (type == ResourceHandle.class) { return type.cast(new ResourceHandle(resource)); } log.info("Unable to adapt resource on {} to type {}", resource.getPath(), type.getName()); return null; }
java
protected static <AdapterType> AdapterType getAdapter(Resource resource, Class<AdapterType> type) { if (type == ResourceHandle.class) { return type.cast(new ResourceHandle(resource)); } log.info("Unable to adapt resource on {} to type {}", resource.getPath(), type.getName()); return null; }
[ "protected", "static", "<", "AdapterType", ">", "AdapterType", "getAdapter", "(", "Resource", "resource", ",", "Class", "<", "AdapterType", ">", "type", ")", "{", "if", "(", "type", "==", "ResourceHandle", ".", "class", ")", "{", "return", "type", ".", "ca...
Handles <code>resource.adaptTo(ResourceHandle.class)</code>, to wrap a resource with an ResourceHandle. @param resource resource to adapt/wrap @param type target type @return wrapped resource
[ "Handles", "<code", ">", "resource", ".", "adaptTo", "(", "ResourceHandle", ".", "class", ")", "<", "/", "code", ">", "to", "wrap", "a", "resource", "with", "an", "ResourceHandle", "." ]
train
https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/core/CoreAdapterFactory.java#L71-L77
hal/core
gui/src/main/java/org/useware/kernel/gui/behaviour/Integrity.java
Integrity.assertConsumer
private static void assertConsumer(InteractionUnit unit, Map<QName, Set<Procedure>> behaviours, IntegrityErrors err) { Set<Resource<ResourceType>> producedTypes = unit.getOutputs(); for (Resource<ResourceType> resource : producedTypes) { boolean match = false; for(QName id : behaviours.keySet()) { for (Behaviour behaviour : behaviours.get(id)) { if (behaviour.doesConsume(resource)) { match = true; break; } } } if (!match) err.add(unit.getId(), "Missing consumer for <<" + resource + ">>"); } }
java
private static void assertConsumer(InteractionUnit unit, Map<QName, Set<Procedure>> behaviours, IntegrityErrors err) { Set<Resource<ResourceType>> producedTypes = unit.getOutputs(); for (Resource<ResourceType> resource : producedTypes) { boolean match = false; for(QName id : behaviours.keySet()) { for (Behaviour behaviour : behaviours.get(id)) { if (behaviour.doesConsume(resource)) { match = true; break; } } } if (!match) err.add(unit.getId(), "Missing consumer for <<" + resource + ">>"); } }
[ "private", "static", "void", "assertConsumer", "(", "InteractionUnit", "unit", ",", "Map", "<", "QName", ",", "Set", "<", "Procedure", ">", ">", "behaviours", ",", "IntegrityErrors", "err", ")", "{", "Set", "<", "Resource", "<", "ResourceType", ">>", "produc...
Assertion that a consumer exists for the produced resources of an interaction unit. @param unit @param err
[ "Assertion", "that", "a", "consumer", "exists", "for", "the", "produced", "resources", "of", "an", "interaction", "unit", "." ]
train
https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/useware/kernel/gui/behaviour/Integrity.java#L63-L84
groupby/api-java
src/main/java/com/groupbyinc/api/Query.java
Query.setRestrictNavigation
public Query setRestrictNavigation(String name, int count) { this.restrictNavigation = new RestrictNavigation().setName(name).setCount(count); return this; }
java
public Query setRestrictNavigation(String name, int count) { this.restrictNavigation = new RestrictNavigation().setName(name).setCount(count); return this; }
[ "public", "Query", "setRestrictNavigation", "(", "String", "name", ",", "int", "count", ")", "{", "this", ".", "restrictNavigation", "=", "new", "RestrictNavigation", "(", ")", ".", "setName", "(", "name", ")", ".", "setCount", "(", "count", ")", ";", "ret...
<code> <b>Warning</b> See {@link Query#setRestrictNavigation(RestrictNavigation)}. This is a convenience method. </code> @param name the name of the field should be used in the navigation restriction in the second query. @param count the number of fields matches @return this query
[ "<code", ">", "<b", ">", "Warning<", "/", "b", ">", "See", "{", "@link", "Query#setRestrictNavigation", "(", "RestrictNavigation", ")", "}", ".", "This", "is", "a", "convenience", "method", ".", "<", "/", "code", ">" ]
train
https://github.com/groupby/api-java/blob/257c4ed0777221e5e4ade3b29b9921300fac4e2e/src/main/java/com/groupbyinc/api/Query.java#L1123-L1126
dnsjava/dnsjava
org/xbill/DNS/TSIG.java
TSIG.apply
public void apply(Message m, TSIGRecord old) { apply(m, Rcode.NOERROR, old); }
java
public void apply(Message m, TSIGRecord old) { apply(m, Rcode.NOERROR, old); }
[ "public", "void", "apply", "(", "Message", "m", ",", "TSIGRecord", "old", ")", "{", "apply", "(", "m", ",", "Rcode", ".", "NOERROR", ",", "old", ")", ";", "}" ]
Generates a TSIG record for a message and adds it to the message @param m The message @param old If this message is a response, the TSIG from the request
[ "Generates", "a", "TSIG", "record", "for", "a", "message", "and", "adds", "it", "to", "the", "message" ]
train
https://github.com/dnsjava/dnsjava/blob/d97b6a0685d59143372bb392ab591dd8dd840b61/org/xbill/DNS/TSIG.java#L362-L365
bazaarvoice/emodb
web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java
RoleResource1.updateRoleFromUpdateRequest
@PUT @Path("{group}/{id}") @Consumes("application/x.json-update-role") public SuccessResponse updateRoleFromUpdateRequest(@PathParam("group") String group, @PathParam("id") String id, UpdateEmoRoleRequest request, @Authenticated Subject subject) { _uac.updateRole(subject, request.setRoleKey(new EmoRoleKey(group, id))); return SuccessResponse.instance(); }
java
@PUT @Path("{group}/{id}") @Consumes("application/x.json-update-role") public SuccessResponse updateRoleFromUpdateRequest(@PathParam("group") String group, @PathParam("id") String id, UpdateEmoRoleRequest request, @Authenticated Subject subject) { _uac.updateRole(subject, request.setRoleKey(new EmoRoleKey(group, id))); return SuccessResponse.instance(); }
[ "@", "PUT", "@", "Path", "(", "\"{group}/{id}\"", ")", "@", "Consumes", "(", "\"application/x.json-update-role\"", ")", "public", "SuccessResponse", "updateRoleFromUpdateRequest", "(", "@", "PathParam", "(", "\"group\"", ")", "String", "group", ",", "@", "PathParam"...
Alternate endpoint for updating a role. Although not REST compliant it provides a more flexible interface for specifying role attributes, such as by supporting partial updates.
[ "Alternate", "endpoint", "for", "updating", "a", "role", ".", "Although", "not", "REST", "compliant", "it", "provides", "a", "more", "flexible", "interface", "for", "specifying", "role", "attributes", "such", "as", "by", "supporting", "partial", "updates", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/web/src/main/java/com/bazaarvoice/emodb/web/resources/uac/RoleResource1.java#L137-L144
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java
JsonUtil.getBoolean
public static boolean getBoolean(JsonObject object, String field) { final JsonValue value = object.get(field); throwExceptionIfNull(value, field); return value.asBoolean(); }
java
public static boolean getBoolean(JsonObject object, String field) { final JsonValue value = object.get(field); throwExceptionIfNull(value, field); return value.asBoolean(); }
[ "public", "static", "boolean", "getBoolean", "(", "JsonObject", "object", ",", "String", "field", ")", "{", "final", "JsonValue", "value", "=", "object", ".", "get", "(", "field", ")", ";", "throwExceptionIfNull", "(", "value", ",", "field", ")", ";", "ret...
Returns a field in a Json object as a boolean. Throws IllegalArgumentException if the field value is null. @param object the Json Object @param field the field in the Json object to return @return the Json field value as a boolean
[ "Returns", "a", "field", "in", "a", "Json", "object", "as", "a", "boolean", ".", "Throws", "IllegalArgumentException", "if", "the", "field", "value", "is", "null", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/JsonUtil.java#L199-L203
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.longSupplier
public static LongSupplier longSupplier(CheckedLongSupplier supplier, Consumer<Throwable> handler) { return () -> { try { return supplier.getAsLong(); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
java
public static LongSupplier longSupplier(CheckedLongSupplier supplier, Consumer<Throwable> handler) { return () -> { try { return supplier.getAsLong(); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
[ "public", "static", "LongSupplier", "longSupplier", "(", "CheckedLongSupplier", "supplier", ",", "Consumer", "<", "Throwable", ">", "handler", ")", "{", "return", "(", ")", "->", "{", "try", "{", "return", "supplier", ".", "getAsLong", "(", ")", ";", "}", ...
Wrap a {@link CheckedLongSupplier} in a {@link LongSupplier} with a custom handler for checked exceptions. <p> Example: <code><pre> ResultSet rs = statement.executeQuery(); Stream.generate(Unchecked.longSupplier( () -> rs.getLong(1), e -> { throw new IllegalStateException(e); } )); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedLongSupplier", "}", "in", "a", "{", "@link", "LongSupplier", "}", "with", "a", "custom", "handler", "for", "checked", "exceptions", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "ResultSet", "rs", "=", "sta...
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1774-L1785
pravega/pravega
segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/IndexWriter.java
IndexWriter.generateBackpointerUpdates
private void generateBackpointerUpdates(BucketUpdate update, UpdateInstructions updateInstructions) { // Keep track of the previous, non-deleted Key's offset. The first one points to nothing. AtomicLong previousOffset = new AtomicLong(Attributes.NULL_ATTRIBUTE_VALUE); // Keep track of whether the previous Key has been replaced. AtomicBoolean previousReplaced = new AtomicBoolean(false); // Process all existing Keys, in order of Offsets, and either unlink them (if replaced) or update pointers as needed. AtomicBoolean first = new AtomicBoolean(true); update.getExistingKeys().stream() .sorted(Comparator.comparingLong(BucketUpdate.KeyInfo::getOffset)) .forEach(keyInfo -> { boolean replaced = update.isKeyUpdated(keyInfo.getKey()); if (replaced) { // This one has been replaced or removed; delete any backpointer originating from it. if (!first.get()) { // ... except if this is the first one in the list, which means it doesn't have a backpointer. updateInstructions.withAttribute(generateBackpointerRemoval(keyInfo.getOffset())); } // Record that this has been replaced. updateInstructions.entryRemoved(); previousReplaced.set(true); } else { if (previousReplaced.get()) { // This one hasn't been replaced or removed, however its previous one has been. // Repoint it to whatever key is now ahead of it, or remove it (if previousOffset is nothing). updateInstructions.withAttribute(generateBackpointerUpdate(keyInfo.getOffset(), previousOffset.get())); previousReplaced.set(false); } previousOffset.set(keyInfo.getOffset()); // Record the last valid offset. } first.set(false); }); // Process all the new Keys, in order of offsets, and add any backpointers as needed, making sure to also link them // to whatever surviving existing Keys we might still have. update.getKeyUpdates().stream() .filter(keyUpdate -> !keyUpdate.isDeleted()) .sorted(Comparator.comparingLong(BucketUpdate.KeyUpdate::getOffset)) .forEach(keyUpdate -> { if (previousOffset.get() != Attributes.NULL_ATTRIBUTE_VALUE) { // Only add a backpointer if we have another Key ahead of it. updateInstructions.withAttribute(generateBackpointerUpdate(keyUpdate.getOffset(), previousOffset.get())); } updateInstructions.entryAdded(); previousOffset.set(keyUpdate.getOffset()); }); }
java
private void generateBackpointerUpdates(BucketUpdate update, UpdateInstructions updateInstructions) { // Keep track of the previous, non-deleted Key's offset. The first one points to nothing. AtomicLong previousOffset = new AtomicLong(Attributes.NULL_ATTRIBUTE_VALUE); // Keep track of whether the previous Key has been replaced. AtomicBoolean previousReplaced = new AtomicBoolean(false); // Process all existing Keys, in order of Offsets, and either unlink them (if replaced) or update pointers as needed. AtomicBoolean first = new AtomicBoolean(true); update.getExistingKeys().stream() .sorted(Comparator.comparingLong(BucketUpdate.KeyInfo::getOffset)) .forEach(keyInfo -> { boolean replaced = update.isKeyUpdated(keyInfo.getKey()); if (replaced) { // This one has been replaced or removed; delete any backpointer originating from it. if (!first.get()) { // ... except if this is the first one in the list, which means it doesn't have a backpointer. updateInstructions.withAttribute(generateBackpointerRemoval(keyInfo.getOffset())); } // Record that this has been replaced. updateInstructions.entryRemoved(); previousReplaced.set(true); } else { if (previousReplaced.get()) { // This one hasn't been replaced or removed, however its previous one has been. // Repoint it to whatever key is now ahead of it, or remove it (if previousOffset is nothing). updateInstructions.withAttribute(generateBackpointerUpdate(keyInfo.getOffset(), previousOffset.get())); previousReplaced.set(false); } previousOffset.set(keyInfo.getOffset()); // Record the last valid offset. } first.set(false); }); // Process all the new Keys, in order of offsets, and add any backpointers as needed, making sure to also link them // to whatever surviving existing Keys we might still have. update.getKeyUpdates().stream() .filter(keyUpdate -> !keyUpdate.isDeleted()) .sorted(Comparator.comparingLong(BucketUpdate.KeyUpdate::getOffset)) .forEach(keyUpdate -> { if (previousOffset.get() != Attributes.NULL_ATTRIBUTE_VALUE) { // Only add a backpointer if we have another Key ahead of it. updateInstructions.withAttribute(generateBackpointerUpdate(keyUpdate.getOffset(), previousOffset.get())); } updateInstructions.entryAdded(); previousOffset.set(keyUpdate.getOffset()); }); }
[ "private", "void", "generateBackpointerUpdates", "(", "BucketUpdate", "update", ",", "UpdateInstructions", "updateInstructions", ")", "{", "// Keep track of the previous, non-deleted Key's offset. The first one points to nothing.", "AtomicLong", "previousOffset", "=", "new", "AtomicL...
Generates the necessary Backpointer updates for the given {@link BucketUpdate}. @param update The BucketUpdate to generate Backpointers for. @param updateInstructions A {@link UpdateInstructions} object to collect updates into.
[ "Generates", "the", "necessary", "Backpointer", "updates", "for", "the", "given", "{", "@link", "BucketUpdate", "}", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/IndexWriter.java#L256-L307
box/box-java-sdk
src/main/java/com/box/sdk/BoxCollaboration.java
BoxCollaboration.getInfo
public Info getInfo() { BoxAPIConnection api = this.getAPI(); URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); return new Info(jsonObject); }
java
public Info getInfo() { BoxAPIConnection api = this.getAPI(); URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID()); BoxAPIRequest request = new BoxAPIRequest(api, url, "GET"); BoxJSONResponse response = (BoxJSONResponse) request.send(); JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); return new Info(jsonObject); }
[ "public", "Info", "getInfo", "(", ")", "{", "BoxAPIConnection", "api", "=", "this", ".", "getAPI", "(", ")", ";", "URL", "url", "=", "COLLABORATION_URL_TEMPLATE", ".", "build", "(", "api", ".", "getBaseURL", "(", ")", ",", "this", ".", "getID", "(", ")...
Gets information about this collaboration. @return info about this collaboration.
[ "Gets", "information", "about", "this", "collaboration", "." ]
train
https://github.com/box/box-java-sdk/blob/35b4ba69417f9d6a002c19dfaab57527750ef349/src/main/java/com/box/sdk/BoxCollaboration.java#L132-L140
puniverse/capsule
capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java
Jar.addEntries
public Jar addEntries(String path, Path dirOrZip, Filter filter) throws IOException { return addEntries(path != null ? Paths.get(path) : null, dirOrZip, filter); }
java
public Jar addEntries(String path, Path dirOrZip, Filter filter) throws IOException { return addEntries(path != null ? Paths.get(path) : null, dirOrZip, filter); }
[ "public", "Jar", "addEntries", "(", "String", "path", ",", "Path", "dirOrZip", ",", "Filter", "filter", ")", "throws", "IOException", "{", "return", "addEntries", "(", "path", "!=", "null", "?", "Paths", ".", "get", "(", "path", ")", ":", "null", ",", ...
Adds a directory (with all its subdirectories) or the contents of a zip/JAR to this JAR. @param path the path within the JAR where the root of the directory/zip will be placed, or {@code null} for the JAR's root @param dirOrZip the directory to add as an entry or a zip/JAR file whose contents will be extracted and added as entries @param filter a filter to select particular classes @return {@code this}
[ "Adds", "a", "directory", "(", "with", "all", "its", "subdirectories", ")", "or", "the", "contents", "of", "a", "zip", "/", "JAR", "to", "this", "JAR", "." ]
train
https://github.com/puniverse/capsule/blob/291a54e501a32aaf0284707b8c1fbff6a566822b/capsule-util/src/main/java/co/paralleluniverse/capsule/Jar.java#L422-L424
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java
SpiderTransaction.addIDValueColumn
public void addIDValueColumn(TableDefinition tableDef, String objID) { addColumn(SpiderService.objectsStoreName(tableDef), objID, CommonDefs.ID_FIELD, Utils.toBytes(objID)); }
java
public void addIDValueColumn(TableDefinition tableDef, String objID) { addColumn(SpiderService.objectsStoreName(tableDef), objID, CommonDefs.ID_FIELD, Utils.toBytes(objID)); }
[ "public", "void", "addIDValueColumn", "(", "TableDefinition", "tableDef", ",", "String", "objID", ")", "{", "addColumn", "(", "SpiderService", ".", "objectsStoreName", "(", "tableDef", ")", ",", "objID", ",", "CommonDefs", ".", "ID_FIELD", ",", "Utils", ".", "...
Similar to {@link #addScalarValueColumn(DBObject, String, String)} but specialized for the _ID field. Adds the _ID column for the object's primary store. @param tableDef {@link TableDefinition} of owning table. @param objID ID of object whose _ID value to set. @see #addScalarValueColumn(DBObject, String, String)
[ "Similar", "to", "{", "@link", "#addScalarValueColumn", "(", "DBObject", "String", "String", ")", "}", "but", "specialized", "for", "the", "_ID", "field", ".", "Adds", "the", "_ID", "column", "for", "the", "object", "s", "primary", "store", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java#L223-L225
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/release/maven/MavenReleaseWrapper.java
MavenReleaseWrapper.getMavenModules
private List<String> getMavenModules(MavenModuleSetBuild mavenBuild) throws IOException, InterruptedException { FilePath pathToModuleRoot = mavenBuild.getModuleRoot(); FilePath pathToPom = new FilePath(pathToModuleRoot, mavenBuild.getProject().getRootPOM(null)); return pathToPom.act(new MavenModulesExtractor()); }
java
private List<String> getMavenModules(MavenModuleSetBuild mavenBuild) throws IOException, InterruptedException { FilePath pathToModuleRoot = mavenBuild.getModuleRoot(); FilePath pathToPom = new FilePath(pathToModuleRoot, mavenBuild.getProject().getRootPOM(null)); return pathToPom.act(new MavenModulesExtractor()); }
[ "private", "List", "<", "String", ">", "getMavenModules", "(", "MavenModuleSetBuild", "mavenBuild", ")", "throws", "IOException", ",", "InterruptedException", "{", "FilePath", "pathToModuleRoot", "=", "mavenBuild", ".", "getModuleRoot", "(", ")", ";", "FilePath", "p...
Retrieve from the parent pom the path to the modules of the project
[ "Retrieve", "from", "the", "parent", "pom", "the", "path", "to", "the", "modules", "of", "the", "project" ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/release/maven/MavenReleaseWrapper.java#L238-L242
devnied/EMV-NFC-Paycard-Enrollment
library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java
DataFactory.getString
private static String getString(final AnnotationData pAnnotation, final BitUtils pBit) { String obj = null; if (pAnnotation.isReadHexa()) { obj = pBit.getNextHexaString(pAnnotation.getSize()); } else { obj = pBit.getNextString(pAnnotation.getSize()).trim(); } return obj; }
java
private static String getString(final AnnotationData pAnnotation, final BitUtils pBit) { String obj = null; if (pAnnotation.isReadHexa()) { obj = pBit.getNextHexaString(pAnnotation.getSize()); } else { obj = pBit.getNextString(pAnnotation.getSize()).trim(); } return obj; }
[ "private", "static", "String", "getString", "(", "final", "AnnotationData", "pAnnotation", ",", "final", "BitUtils", "pBit", ")", "{", "String", "obj", "=", "null", ";", "if", "(", "pAnnotation", ".", "isReadHexa", "(", ")", ")", "{", "obj", "=", "pBit", ...
This method get a string (Hexa or ASCII) from a bit table @param pAnnotation annotation data @param pBit bit table @return A string
[ "This", "method", "get", "a", "string", "(", "Hexa", "or", "ASCII", ")", "from", "a", "bit", "table" ]
train
https://github.com/devnied/EMV-NFC-Paycard-Enrollment/blob/bfbd3960708689154a7a75c8a9a934197d738a5b/library/src/main/java/com/github/devnied/emvnfccard/parser/apdu/impl/DataFactory.java#L212-L222
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java
VirtualMachineScaleSetsInner.performMaintenanceAsync
public Observable<OperationStatusResponseInner> performMaintenanceAsync(String resourceGroupName, String vmScaleSetName) { return performMaintenanceWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
java
public Observable<OperationStatusResponseInner> performMaintenanceAsync(String resourceGroupName, String vmScaleSetName) { return performMaintenanceWithServiceResponseAsync(resourceGroupName, vmScaleSetName).map(new Func1<ServiceResponse<OperationStatusResponseInner>, OperationStatusResponseInner>() { @Override public OperationStatusResponseInner call(ServiceResponse<OperationStatusResponseInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatusResponseInner", ">", "performMaintenanceAsync", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ")", "{", "return", "performMaintenanceWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmScaleSetName", ...
Perform maintenance on one or more virtual machines in a VM scale set. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Perform", "maintenance", "on", "one", "or", "more", "virtual", "machines", "in", "a", "VM", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineScaleSetsInner.java#L3218-L3225
undera/jmeter-plugins
plugins/functions/src/main/java/kg/apc/jmeter/functions/CaseFormat.java
CaseFormat.caseFormatWithDelimiter
private static String caseFormatWithDelimiter(String str, String delimiter, boolean isAllUpper, boolean isAllLower) { StringBuilder builder = new StringBuilder(str.length()); String[] tokens = NOT_ALPHANUMERIC_REGEX.split(str); boolean shouldAddDelimiter = StringUtils.isNotEmpty(delimiter); for (int i = 0; i < tokens.length; i++) { String currentToken = tokens[i]; builder.append(currentToken); boolean hasNextToken = i + 1 != tokens.length; if (hasNextToken && shouldAddDelimiter) { builder.append(delimiter); } } String outputString = builder.toString(); if (isAllLower) { return StringUtils.lowerCase(outputString); } else if (isAllUpper) { return StringUtils.upperCase(outputString); } return outputString; }
java
private static String caseFormatWithDelimiter(String str, String delimiter, boolean isAllUpper, boolean isAllLower) { StringBuilder builder = new StringBuilder(str.length()); String[] tokens = NOT_ALPHANUMERIC_REGEX.split(str); boolean shouldAddDelimiter = StringUtils.isNotEmpty(delimiter); for (int i = 0; i < tokens.length; i++) { String currentToken = tokens[i]; builder.append(currentToken); boolean hasNextToken = i + 1 != tokens.length; if (hasNextToken && shouldAddDelimiter) { builder.append(delimiter); } } String outputString = builder.toString(); if (isAllLower) { return StringUtils.lowerCase(outputString); } else if (isAllUpper) { return StringUtils.upperCase(outputString); } return outputString; }
[ "private", "static", "String", "caseFormatWithDelimiter", "(", "String", "str", ",", "String", "delimiter", ",", "boolean", "isAllUpper", ",", "boolean", "isAllLower", ")", "{", "StringBuilder", "builder", "=", "new", "StringBuilder", "(", "str", ".", "length", ...
Change case using delimiter between words @param str @param delimiter @param isAllUpper @param isAllLower @return string after change case
[ "Change", "case", "using", "delimiter", "between", "words" ]
train
https://github.com/undera/jmeter-plugins/blob/416d2a77249ab921c7e4134c3e6a9639901ef7e8/plugins/functions/src/main/java/kg/apc/jmeter/functions/CaseFormat.java#L178-L197
landawn/AbacusUtil
src/com/landawn/abacus/util/N.java
N.mapToInt
public static <T, E extends Exception> IntList mapToInt(final T[] a, final int fromIndex, final int toIndex, final Try.ToIntFunction<? super T, E> func) throws E { checkFromToIndex(fromIndex, toIndex, len(a)); N.checkArgNotNull(func); if (N.isNullOrEmpty(a)) { return new IntList(); } final IntList result = new IntList(toIndex - fromIndex); for (int i = fromIndex; i < toIndex; i++) { result.add(func.applyAsInt(a[i])); } return result; }
java
public static <T, E extends Exception> IntList mapToInt(final T[] a, final int fromIndex, final int toIndex, final Try.ToIntFunction<? super T, E> func) throws E { checkFromToIndex(fromIndex, toIndex, len(a)); N.checkArgNotNull(func); if (N.isNullOrEmpty(a)) { return new IntList(); } final IntList result = new IntList(toIndex - fromIndex); for (int i = fromIndex; i < toIndex; i++) { result.add(func.applyAsInt(a[i])); } return result; }
[ "public", "static", "<", "T", ",", "E", "extends", "Exception", ">", "IntList", "mapToInt", "(", "final", "T", "[", "]", "a", ",", "final", "int", "fromIndex", ",", "final", "int", "toIndex", ",", "final", "Try", ".", "ToIntFunction", "<", "?", "super"...
Mostly it's designed for one-step operation to complete the operation in one step. <code>java.util.stream.Stream</code> is preferred for multiple phases operation. @param a @param fromIndex @param toIndex @param func @return
[ "Mostly", "it", "s", "designed", "for", "one", "-", "step", "operation", "to", "complete", "the", "operation", "in", "one", "step", ".", "<code", ">", "java", ".", "util", ".", "stream", ".", "Stream<", "/", "code", ">", "is", "preferred", "for", "mult...
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/N.java#L14883-L14899
scalecube/scalecube-services
services-api/src/main/java/io/scalecube/services/api/ServiceMessage.java
ServiceMessage.setHeaders
void setHeaders(Map<String, String> headers) { this.headers = Collections.unmodifiableMap(new HashMap<>(headers)); }
java
void setHeaders(Map<String, String> headers) { this.headers = Collections.unmodifiableMap(new HashMap<>(headers)); }
[ "void", "setHeaders", "(", "Map", "<", "String", ",", "String", ">", "headers", ")", "{", "this", ".", "headers", "=", "Collections", ".", "unmodifiableMap", "(", "new", "HashMap", "<>", "(", "headers", ")", ")", ";", "}" ]
Sets headers for deserialization purpose. @param headers headers to set
[ "Sets", "headers", "for", "deserialization", "purpose", "." ]
train
https://github.com/scalecube/scalecube-services/blob/76c8de6019e5480a1436d12b37acf163f70eea47/services-api/src/main/java/io/scalecube/services/api/ServiceMessage.java#L93-L95
icode/ameba
src/main/java/ameba/feature/AmebaFeature.java
AmebaFeature.subscribeSystemEvent
protected <E extends Event> void subscribeSystemEvent(Class<E> eventClass, final Listener<E> listener) { locator.inject(listener); locator.postConstruct(listener); SystemEventBus.subscribe(eventClass, listener); }
java
protected <E extends Event> void subscribeSystemEvent(Class<E> eventClass, final Listener<E> listener) { locator.inject(listener); locator.postConstruct(listener); SystemEventBus.subscribe(eventClass, listener); }
[ "protected", "<", "E", "extends", "Event", ">", "void", "subscribeSystemEvent", "(", "Class", "<", "E", ">", "eventClass", ",", "final", "Listener", "<", "E", ">", "listener", ")", "{", "locator", ".", "inject", "(", "listener", ")", ";", "locator", ".",...
<p>subscribeSystemEvent.</p> @param eventClass a {@link java.lang.Class} object. @param listener a {@link ameba.event.Listener} object. @since 0.1.6e @param <E> a E object.
[ "<p", ">", "subscribeSystemEvent", ".", "<", "/", "p", ">" ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/feature/AmebaFeature.java#L128-L132
mgm-tp/jfunk
jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ScriptExecutor.java
ScriptExecutor.executeScript
public boolean executeScript(final File script, final Properties scriptProperties) { checkState(script.exists(), "Script file does not exist: %s", script); checkState(script.canRead(), "Script file is not readable: %s", script); Reader reader = null; boolean success = false; Throwable throwable = null; scriptScope.enterScope(); ScriptContext ctx = scriptContextProvider.get(); try { reader = Files.newReader(script, charset); ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("groovy"); ctx.setScript(script); ctx.load(JFunkConstants.SCRIPT_PROPERTIES, false); ctx.registerReporter(new SimpleReporter()); initGroovyCommands(scriptEngine, ctx); initScriptProperties(scriptEngine, scriptProperties); ScriptMetaData scriptMetaData = scriptMetaDataProvider.get(); scriptMetaData.setScriptName(script.getPath()); Date startDate = new Date(); scriptMetaData.setStartDate(startDate); ctx.set(JFunkConstants.SCRIPT_START_MILLIS, String.valueOf(startDate.getTime())); eventBus.post(scriptEngine); eventBus.post(new BeforeScriptEvent(script.getAbsolutePath())); scriptEngine.eval(reader); success = true; } catch (IOException ex) { throwable = ex; log.error("Error loading script: " + script, ex); } catch (ScriptException ex) { throwable = ex; // Look up the cause hierarchy if we find a ModuleExecutionException. // We only need to log exceptions other than ModuleExecutionException because they // have already been logged and we don't want to pollute the log file any further. // In fact, other exception cannot normally happen. Throwable th = ex; while (!(th instanceof ModuleExecutionException)) { if (th == null) { // log original exception log.error("Error executing script: " + script, ex); success = false; break; } th = th.getCause(); } } finally { try { ScriptMetaData scriptMetaData = scriptMetaDataProvider.get(); Date endDate = new Date(); scriptMetaData.setEndDate(endDate); ctx.set(JFunkConstants.SCRIPT_END_MILLIS, String.valueOf(endDate.getTime())); scriptMetaData.setThrowable(throwable); eventBus.post(new AfterScriptEvent(script.getAbsolutePath(), success)); } finally { scriptScope.exitScope(); closeQuietly(reader); } } return success; }
java
public boolean executeScript(final File script, final Properties scriptProperties) { checkState(script.exists(), "Script file does not exist: %s", script); checkState(script.canRead(), "Script file is not readable: %s", script); Reader reader = null; boolean success = false; Throwable throwable = null; scriptScope.enterScope(); ScriptContext ctx = scriptContextProvider.get(); try { reader = Files.newReader(script, charset); ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("groovy"); ctx.setScript(script); ctx.load(JFunkConstants.SCRIPT_PROPERTIES, false); ctx.registerReporter(new SimpleReporter()); initGroovyCommands(scriptEngine, ctx); initScriptProperties(scriptEngine, scriptProperties); ScriptMetaData scriptMetaData = scriptMetaDataProvider.get(); scriptMetaData.setScriptName(script.getPath()); Date startDate = new Date(); scriptMetaData.setStartDate(startDate); ctx.set(JFunkConstants.SCRIPT_START_MILLIS, String.valueOf(startDate.getTime())); eventBus.post(scriptEngine); eventBus.post(new BeforeScriptEvent(script.getAbsolutePath())); scriptEngine.eval(reader); success = true; } catch (IOException ex) { throwable = ex; log.error("Error loading script: " + script, ex); } catch (ScriptException ex) { throwable = ex; // Look up the cause hierarchy if we find a ModuleExecutionException. // We only need to log exceptions other than ModuleExecutionException because they // have already been logged and we don't want to pollute the log file any further. // In fact, other exception cannot normally happen. Throwable th = ex; while (!(th instanceof ModuleExecutionException)) { if (th == null) { // log original exception log.error("Error executing script: " + script, ex); success = false; break; } th = th.getCause(); } } finally { try { ScriptMetaData scriptMetaData = scriptMetaDataProvider.get(); Date endDate = new Date(); scriptMetaData.setEndDate(endDate); ctx.set(JFunkConstants.SCRIPT_END_MILLIS, String.valueOf(endDate.getTime())); scriptMetaData.setThrowable(throwable); eventBus.post(new AfterScriptEvent(script.getAbsolutePath(), success)); } finally { scriptScope.exitScope(); closeQuietly(reader); } } return success; }
[ "public", "boolean", "executeScript", "(", "final", "File", "script", ",", "final", "Properties", "scriptProperties", ")", "{", "checkState", "(", "script", ".", "exists", "(", ")", ",", "\"Script file does not exist: %s\"", ",", "script", ")", ";", "checkState", ...
Executes the specified Groovy script. @param script the script file @param scriptProperties properties that are set to the script engine's binding and thus will be available as variables in the Groovy script @return the execution result, {@code true} if successful, {@code false} code
[ "Executes", "the", "specified", "Groovy", "script", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-core/src/main/java/com/mgmtp/jfunk/core/scripting/ScriptExecutor.java#L92-L159
cdk/cdk
descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/AtomPairs2DFingerprinter.java
AtomPairs2DFingerprinter.encodePath
private static String encodePath(int dist, IAtom a, IAtom b) { return dist + "_" + a.getSymbol() + "_" + b.getSymbol(); }
java
private static String encodePath(int dist, IAtom a, IAtom b) { return dist + "_" + a.getSymbol() + "_" + b.getSymbol(); }
[ "private", "static", "String", "encodePath", "(", "int", "dist", ",", "IAtom", "a", ",", "IAtom", "b", ")", "{", "return", "dist", "+", "\"_\"", "+", "a", ".", "getSymbol", "(", ")", "+", "\"_\"", "+", "b", ".", "getSymbol", "(", ")", ";", "}" ]
Creates the fingerprint name which is used as a key in our hashes @param dist @param a @param b @return
[ "Creates", "the", "fingerprint", "name", "which", "is", "used", "as", "a", "key", "in", "our", "hashes" ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/descriptor/fingerprint/src/main/java/org/openscience/cdk/fingerprint/AtomPairs2DFingerprinter.java#L114-L116
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/ModelRegistry.java
ModelRegistry.dateFormat
void dateFormat(DateFormat format, String... attributes) { convertWith(new DateToStringConverter(format), attributes); convertWith(new StringToSqlDateConverter(format), attributes); }
java
void dateFormat(DateFormat format, String... attributes) { convertWith(new DateToStringConverter(format), attributes); convertWith(new StringToSqlDateConverter(format), attributes); }
[ "void", "dateFormat", "(", "DateFormat", "format", ",", "String", "...", "attributes", ")", "{", "convertWith", "(", "new", "DateToStringConverter", "(", "format", ")", ",", "attributes", ")", ";", "convertWith", "(", "new", "StringToSqlDateConverter", "(", "for...
Registers date converters (Date -> String -> java.sql.Date) for specified model attributes.
[ "Registers", "date", "converters", "(", "Date", "-", ">", "String", "-", ">", "java", ".", "sql", ".", "Date", ")", "for", "specified", "model", "attributes", "." ]
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/ModelRegistry.java#L65-L68
datacleaner/AnalyzerBeans
components/date-gap/src/main/java/org/eobjects/analyzer/beans/dategap/TimeLine.java
TimeLine.getTimeGapIntervals
public SortedSet<TimeInterval> getTimeGapIntervals() { SortedSet<TimeInterval> flattenedIntervals = getFlattenedIntervals(); SortedSet<TimeInterval> gaps = new TreeSet<TimeInterval>(); TimeInterval previous = null; for (TimeInterval timeInterval : flattenedIntervals) { if (previous != null) { long from = previous.getTo(); long to = timeInterval.getFrom(); TimeInterval gap = new TimeInterval(from, to); gaps.add(gap); } previous = timeInterval; } return gaps; }
java
public SortedSet<TimeInterval> getTimeGapIntervals() { SortedSet<TimeInterval> flattenedIntervals = getFlattenedIntervals(); SortedSet<TimeInterval> gaps = new TreeSet<TimeInterval>(); TimeInterval previous = null; for (TimeInterval timeInterval : flattenedIntervals) { if (previous != null) { long from = previous.getTo(); long to = timeInterval.getFrom(); TimeInterval gap = new TimeInterval(from, to); gaps.add(gap); } previous = timeInterval; } return gaps; }
[ "public", "SortedSet", "<", "TimeInterval", ">", "getTimeGapIntervals", "(", ")", "{", "SortedSet", "<", "TimeInterval", ">", "flattenedIntervals", "=", "getFlattenedIntervals", "(", ")", ";", "SortedSet", "<", "TimeInterval", ">", "gaps", "=", "new", "TreeSet", ...
Gets a set of intervals representing the times that are NOT represented in this timeline. @return
[ "Gets", "a", "set", "of", "intervals", "representing", "the", "times", "that", "are", "NOT", "represented", "in", "this", "timeline", "." ]
train
https://github.com/datacleaner/AnalyzerBeans/blob/f82dae080d80d2a647b706a5fb22b3ea250613b3/components/date-gap/src/main/java/org/eobjects/analyzer/beans/dategap/TimeLine.java#L127-L143
grpc/grpc-java
okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
OkHttpClientTransport.onError
private void onError(ErrorCode errorCode, String moreDetail) { startGoAway(0, errorCode, toGrpcStatus(errorCode).augmentDescription(moreDetail)); }
java
private void onError(ErrorCode errorCode, String moreDetail) { startGoAway(0, errorCode, toGrpcStatus(errorCode).augmentDescription(moreDetail)); }
[ "private", "void", "onError", "(", "ErrorCode", "errorCode", ",", "String", "moreDetail", ")", "{", "startGoAway", "(", "0", ",", "errorCode", ",", "toGrpcStatus", "(", "errorCode", ")", ".", "augmentDescription", "(", "moreDetail", ")", ")", ";", "}" ]
Send GOAWAY to the server, then finish all active streams and close the transport.
[ "Send", "GOAWAY", "to", "the", "server", "then", "finish", "all", "active", "streams", "and", "close", "the", "transport", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java#L837-L839
joniles/mpxj
src/main/java/net/sf/mpxj/sample/MppDump.java
MppDump.asciidump
private static long asciidump(InputStream is, PrintWriter pw) throws Exception { byte[] buffer = new byte[BUFFER_SIZE]; long byteCount = 0; char c; int loop; int count; StringBuilder sb = new StringBuilder(); while (true) { count = is.read(buffer); if (count == -1) { break; } byteCount += count; sb.setLength(0); for (loop = 0; loop < count; loop++) { c = (char) buffer[loop]; if (c > 200 || c < 27) { c = ' '; } sb.append(c); } pw.print(sb.toString()); } return (byteCount); }
java
private static long asciidump(InputStream is, PrintWriter pw) throws Exception { byte[] buffer = new byte[BUFFER_SIZE]; long byteCount = 0; char c; int loop; int count; StringBuilder sb = new StringBuilder(); while (true) { count = is.read(buffer); if (count == -1) { break; } byteCount += count; sb.setLength(0); for (loop = 0; loop < count; loop++) { c = (char) buffer[loop]; if (c > 200 || c < 27) { c = ' '; } sb.append(c); } pw.print(sb.toString()); } return (byteCount); }
[ "private", "static", "long", "asciidump", "(", "InputStream", "is", ",", "PrintWriter", "pw", ")", "throws", "Exception", "{", "byte", "[", "]", "buffer", "=", "new", "byte", "[", "BUFFER_SIZE", "]", ";", "long", "byteCount", "=", "0", ";", "char", "c", ...
This method dumps the entire contents of a file to an output print writer as ascii data. @param is Input Stream @param pw Output PrintWriter @return number of bytes read @throws Exception Thrown on file read errors
[ "This", "method", "dumps", "the", "entire", "contents", "of", "a", "file", "to", "an", "output", "print", "writer", "as", "ascii", "data", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/sample/MppDump.java#L233-L269
amsa-code/risky
ais/src/main/java/au/gov/amsa/ais/AisExtractor.java
AisExtractor.getValue
public synchronized int getValue(int from, int to) { try { // is synchronized so that values of bitSet and calculated can be // lazily // calculated and safely published (thread safe). SixBit.convertSixBitToBits(message, padBits, bitSet, calculated, from, to); return (int) SixBit.getValue(from, to, bitSet); } catch (SixBitException | ArrayIndexOutOfBoundsException e) { throw new AisParseException(e); } }
java
public synchronized int getValue(int from, int to) { try { // is synchronized so that values of bitSet and calculated can be // lazily // calculated and safely published (thread safe). SixBit.convertSixBitToBits(message, padBits, bitSet, calculated, from, to); return (int) SixBit.getValue(from, to, bitSet); } catch (SixBitException | ArrayIndexOutOfBoundsException e) { throw new AisParseException(e); } }
[ "public", "synchronized", "int", "getValue", "(", "int", "from", ",", "int", "to", ")", "{", "try", "{", "// is synchronized so that values of bitSet and calculated can be", "// lazily", "// calculated and safely published (thread safe).", "SixBit", ".", "convertSixBitToBits", ...
Returns an unsigned integer value using the bits from character position start to position stop in the decoded message. @param from @param to @return
[ "Returns", "an", "unsigned", "integer", "value", "using", "the", "bits", "from", "character", "position", "start", "to", "position", "stop", "in", "the", "decoded", "message", "." ]
train
https://github.com/amsa-code/risky/blob/13649942aeddfdb9210eec072c605bc5d7a6daf3/ais/src/main/java/au/gov/amsa/ais/AisExtractor.java#L62-L72
dadoonet/elasticsearch-beyonder
src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java
TemplateElasticsearchUpdater.createTemplate
@Deprecated public static void createTemplate(Client client, String root, String template, boolean force) throws Exception { String json = TemplateSettingsReader.readTemplate(root, template); createTemplateWithJson(client, template, json, force); }
java
@Deprecated public static void createTemplate(Client client, String root, String template, boolean force) throws Exception { String json = TemplateSettingsReader.readTemplate(root, template); createTemplateWithJson(client, template, json, force); }
[ "@", "Deprecated", "public", "static", "void", "createTemplate", "(", "Client", "client", ",", "String", "root", ",", "String", "template", ",", "boolean", "force", ")", "throws", "Exception", "{", "String", "json", "=", "TemplateSettingsReader", ".", "readTempl...
Create a template in Elasticsearch. @param client Elasticsearch client @param root dir within the classpath @param template Template name @param force set it to true if you want to force cleaning template before adding it @throws Exception if something goes wrong @deprecated Will be removed when we don't support TransportClient anymore
[ "Create", "a", "template", "in", "Elasticsearch", "." ]
train
https://github.com/dadoonet/elasticsearch-beyonder/blob/275bf63432b97169a90a266e983143cca9ad7629/src/main/java/fr/pilato/elasticsearch/tools/template/TemplateElasticsearchUpdater.java#L50-L54
Prototik/HoloEverywhere
library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java
RadialPickerLayout.onMeasure
@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int measuredHeight = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int minDimension = Math.min(measuredWidth, measuredHeight); super.onMeasure(MeasureSpec.makeMeasureSpec(minDimension, widthMode), MeasureSpec.makeMeasureSpec(minDimension, heightMode)); }
java
@Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int measuredWidth = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int measuredHeight = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int minDimension = Math.min(measuredWidth, measuredHeight); super.onMeasure(MeasureSpec.makeMeasureSpec(minDimension, widthMode), MeasureSpec.makeMeasureSpec(minDimension, heightMode)); }
[ "@", "Override", "public", "void", "onMeasure", "(", "int", "widthMeasureSpec", ",", "int", "heightMeasureSpec", ")", "{", "int", "measuredWidth", "=", "MeasureSpec", ".", "getSize", "(", "widthMeasureSpec", ")", ";", "int", "widthMode", "=", "MeasureSpec", ".",...
Measure the view to end up as a square, based on the minimum of the height and width.
[ "Measure", "the", "view", "to", "end", "up", "as", "a", "square", "based", "on", "the", "minimum", "of", "the", "height", "and", "width", "." ]
train
https://github.com/Prototik/HoloEverywhere/blob/b870abb5ab009a5a6dbab3fb855ec2854e35e125/library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java#L142-L152
libgdx/gdx-ai
gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java
BehaviorTreeLibrary.registerArchetypeTree
public void registerArchetypeTree (String treeReference, BehaviorTree<?> archetypeTree) { if (archetypeTree == null) { throw new IllegalArgumentException("The registered archetype must not be null."); } repository.put(treeReference, archetypeTree); }
java
public void registerArchetypeTree (String treeReference, BehaviorTree<?> archetypeTree) { if (archetypeTree == null) { throw new IllegalArgumentException("The registered archetype must not be null."); } repository.put(treeReference, archetypeTree); }
[ "public", "void", "registerArchetypeTree", "(", "String", "treeReference", ",", "BehaviorTree", "<", "?", ">", "archetypeTree", ")", "{", "if", "(", "archetypeTree", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The registered archetype...
Registers the {@link BehaviorTree} archetypeTree with the specified reference. Existing archetypes in the repository with the same treeReference will be replaced. @param treeReference the tree identifier, typically a path. @param archetypeTree the archetype tree. @throws IllegalArgumentException if the archetypeTree is null
[ "Registers", "the", "{" ]
train
https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/btree/utils/BehaviorTreeLibrary.java#L141-L146
overturetool/overture
core/interpreter/src/main/java/org/overture/interpreter/runtime/ClassInterpreter.java
ClassInterpreter.execute
@Override public Value execute(String line, DBGPReader dbgp) throws Exception { PExp expr = parseExpression(line, getDefaultName()); Environment env = getGlobalEnvironment(); Environment created = new FlatCheckedEnvironment(assistantFactory, createdDefinitions.asList(), env, NameScope.NAMESANDSTATE); typeCheck(expr, created); return execute(expr, dbgp); }
java
@Override public Value execute(String line, DBGPReader dbgp) throws Exception { PExp expr = parseExpression(line, getDefaultName()); Environment env = getGlobalEnvironment(); Environment created = new FlatCheckedEnvironment(assistantFactory, createdDefinitions.asList(), env, NameScope.NAMESANDSTATE); typeCheck(expr, created); return execute(expr, dbgp); }
[ "@", "Override", "public", "Value", "execute", "(", "String", "line", ",", "DBGPReader", "dbgp", ")", "throws", "Exception", "{", "PExp", "expr", "=", "parseExpression", "(", "line", ",", "getDefaultName", "(", ")", ")", ";", "Environment", "env", "=", "ge...
Parse the line passed, type check it and evaluate it as an expression in the initial context. @param line A VDM expression. @return The value of the expression. @throws Exception Parser, type checking or runtime errors.
[ "Parse", "the", "line", "passed", "type", "check", "it", "and", "evaluate", "it", "as", "an", "expression", "in", "the", "initial", "context", "." ]
train
https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/org/overture/interpreter/runtime/ClassInterpreter.java#L282-L291
phax/ph-schedule
ph-schedule/src/main/java/com/helger/schedule/quartz/trigger/JDK8TriggerBuilder.java
JDK8TriggerBuilder.usingJobData
@Nonnull public JDK8TriggerBuilder <T> usingJobData (final String dataKey, final int value) { return usingJobData (dataKey, Integer.valueOf (value)); }
java
@Nonnull public JDK8TriggerBuilder <T> usingJobData (final String dataKey, final int value) { return usingJobData (dataKey, Integer.valueOf (value)); }
[ "@", "Nonnull", "public", "JDK8TriggerBuilder", "<", "T", ">", "usingJobData", "(", "final", "String", "dataKey", ",", "final", "int", "value", ")", "{", "return", "usingJobData", "(", "dataKey", ",", "Integer", ".", "valueOf", "(", "value", ")", ")", ";",...
Add the given key-value pair to the Trigger's {@link JobDataMap}. @param dataKey Job data key. @param value Job data value @return the updated JDK8TriggerBuilder @see ITrigger#getJobDataMap()
[ "Add", "the", "given", "key", "-", "value", "pair", "to", "the", "Trigger", "s", "{", "@link", "JobDataMap", "}", "." ]
train
https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-schedule/src/main/java/com/helger/schedule/quartz/trigger/JDK8TriggerBuilder.java#L405-L409
elki-project/elki
elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/datasource/GeneratorXMLDatabaseConnection.java
GeneratorXMLDatabaseConnection.processElementClipping
private void processElementClipping(GeneratorSingleCluster cluster, Node cur) { double[] cmin = null, cmax = null; String minstr = ((Element) cur).getAttribute(ATTR_MIN); if(minstr != null && minstr.length() > 0) { cmin = parseVector(minstr); } String maxstr = ((Element) cur).getAttribute(ATTR_MAX); if(maxstr != null && maxstr.length() > 0) { cmax = parseVector(maxstr); } if(cmin == null || cmax == null) { throw new AbortException("No or incomplete clipping vectors given."); } // *** set clipping cluster.setClipping(cmin, cmax); // TODO: check for unknown attributes. XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild()); while(iter.hasNext()) { Node child = iter.next(); if(child.getNodeType() == Node.ELEMENT_NODE) { LOG.warning("Unknown element in XML specification file: " + child.getNodeName()); } } }
java
private void processElementClipping(GeneratorSingleCluster cluster, Node cur) { double[] cmin = null, cmax = null; String minstr = ((Element) cur).getAttribute(ATTR_MIN); if(minstr != null && minstr.length() > 0) { cmin = parseVector(minstr); } String maxstr = ((Element) cur).getAttribute(ATTR_MAX); if(maxstr != null && maxstr.length() > 0) { cmax = parseVector(maxstr); } if(cmin == null || cmax == null) { throw new AbortException("No or incomplete clipping vectors given."); } // *** set clipping cluster.setClipping(cmin, cmax); // TODO: check for unknown attributes. XMLNodeIterator iter = new XMLNodeIterator(cur.getFirstChild()); while(iter.hasNext()) { Node child = iter.next(); if(child.getNodeType() == Node.ELEMENT_NODE) { LOG.warning("Unknown element in XML specification file: " + child.getNodeName()); } } }
[ "private", "void", "processElementClipping", "(", "GeneratorSingleCluster", "cluster", ",", "Node", "cur", ")", "{", "double", "[", "]", "cmin", "=", "null", ",", "cmax", "=", "null", ";", "String", "minstr", "=", "(", "(", "Element", ")", "cur", ")", "....
Process a 'clipping' Element in the XML stream. @param cluster @param cur Current document nod
[ "Process", "a", "clipping", "Element", "in", "the", "XML", "stream", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-data-generator/src/main/java/de/lmu/ifi/dbs/elki/datasource/GeneratorXMLDatabaseConnection.java#L601-L627
RestComm/sip-servlets
sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java
FacebookRestClient.callMethod
protected T callMethod(IFacebookMethod method, Pair<String, CharSequence>... paramPairs) throws FacebookException, IOException { return callMethod(method, Arrays.asList(paramPairs)); }
java
protected T callMethod(IFacebookMethod method, Pair<String, CharSequence>... paramPairs) throws FacebookException, IOException { return callMethod(method, Arrays.asList(paramPairs)); }
[ "protected", "T", "callMethod", "(", "IFacebookMethod", "method", ",", "Pair", "<", "String", ",", "CharSequence", ">", "...", "paramPairs", ")", "throws", "FacebookException", ",", "IOException", "{", "return", "callMethod", "(", "method", ",", "Arrays", ".", ...
Call the specified method, with the given parameters, and return a DOM tree with the results. @param method the fieldName of the method @param paramPairs a list of arguments to the method @throws Exception with a description of any errors given to us by the server.
[ "Call", "the", "specified", "method", "with", "the", "given", "parameters", "and", "return", "a", "DOM", "tree", "with", "the", "results", "." ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L651-L654
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java
Cursor.setArea
public void setArea(int minX, int minY, int maxX, int maxY) { this.minX = Math.min(minX, maxX); this.minY = Math.min(minY, maxY); this.maxX = Math.max(maxX, minX); this.maxY = Math.max(maxY, minY); }
java
public void setArea(int minX, int minY, int maxX, int maxY) { this.minX = Math.min(minX, maxX); this.minY = Math.min(minY, maxY); this.maxX = Math.max(maxX, minX); this.maxY = Math.max(maxY, minY); }
[ "public", "void", "setArea", "(", "int", "minX", ",", "int", "minY", ",", "int", "maxX", ",", "int", "maxY", ")", "{", "this", ".", "minX", "=", "Math", ".", "min", "(", "minX", ",", "maxX", ")", ";", "this", ".", "minY", "=", "Math", ".", "min...
Allows cursor to move only inside the specified area. The cursor location will not exceed this area. @param minX The minimal x. @param minY The minimal y. @param maxX The maximal x. @param maxY The maximal y.
[ "Allows", "cursor", "to", "move", "only", "inside", "the", "specified", "area", ".", "The", "cursor", "location", "will", "not", "exceed", "this", "area", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Cursor.java#L214-L220
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/fit/SoapCallMapColumnFixture.java
SoapCallMapColumnFixture.callServiceImpl
protected Response callServiceImpl(String urlSymbolKey, String soapAction) { String url = getSymbol(urlSymbolKey).toString(); Response response = getEnvironment().createInstance(getResponseClass()); callSoapService(url, getTemplateName(), soapAction, response); return response; }
java
protected Response callServiceImpl(String urlSymbolKey, String soapAction) { String url = getSymbol(urlSymbolKey).toString(); Response response = getEnvironment().createInstance(getResponseClass()); callSoapService(url, getTemplateName(), soapAction, response); return response; }
[ "protected", "Response", "callServiceImpl", "(", "String", "urlSymbolKey", ",", "String", "soapAction", ")", "{", "String", "url", "=", "getSymbol", "(", "urlSymbolKey", ")", ".", "toString", "(", ")", ";", "Response", "response", "=", "getEnvironment", "(", "...
Creates response, calls service using configured template and current row's values and calls SOAP service. @param urlSymbolKey key of symbol containing service's URL. @param soapAction SOAPAction header value (null if no header is required). @return filled response
[ "Creates", "response", "calls", "service", "using", "configured", "template", "and", "current", "row", "s", "values", "and", "calls", "SOAP", "service", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/fit/SoapCallMapColumnFixture.java#L56-L61
pietermartin/sqlg
sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java
PostgresDialect.sqlTypeToPropertyType
@Override public PropertyType sqlTypeToPropertyType(SqlgGraph sqlgGraph, String schema, String table, String column, int sqlType, String typeName, ListIterator<Triple<String, Integer, String>> metaDataIter) { switch (sqlType) { case Types.BIT: return PropertyType.BOOLEAN; case Types.SMALLINT: return PropertyType.SHORT; case Types.INTEGER: return PropertyType.INTEGER; case Types.BIGINT: return PropertyType.LONG; case Types.REAL: return PropertyType.FLOAT; case Types.DOUBLE: return PropertyType.DOUBLE; case Types.VARCHAR: return PropertyType.STRING; case Types.TIMESTAMP: return PropertyType.LOCALDATETIME; case Types.DATE: return PropertyType.LOCALDATE; case Types.TIME: return PropertyType.LOCALTIME; case Types.OTHER: //this is a f up as only JSON can be used for other. //means all the gis data types which are also OTHER are not supported switch (typeName) { case "jsonb": return PropertyType.JSON; case "geometry": return getPostGisGeometryType(sqlgGraph, schema, table, column); case "geography": return getPostGisGeographyType(sqlgGraph, schema, table, column); default: throw new RuntimeException("Other type not supported " + typeName); } case Types.BINARY: return BYTE_ARRAY; case Types.ARRAY: return sqlArrayTypeNameToPropertyType(typeName, sqlgGraph, schema, table, column, metaDataIter); default: throw new IllegalStateException("Unknown sqlType " + sqlType); } }
java
@Override public PropertyType sqlTypeToPropertyType(SqlgGraph sqlgGraph, String schema, String table, String column, int sqlType, String typeName, ListIterator<Triple<String, Integer, String>> metaDataIter) { switch (sqlType) { case Types.BIT: return PropertyType.BOOLEAN; case Types.SMALLINT: return PropertyType.SHORT; case Types.INTEGER: return PropertyType.INTEGER; case Types.BIGINT: return PropertyType.LONG; case Types.REAL: return PropertyType.FLOAT; case Types.DOUBLE: return PropertyType.DOUBLE; case Types.VARCHAR: return PropertyType.STRING; case Types.TIMESTAMP: return PropertyType.LOCALDATETIME; case Types.DATE: return PropertyType.LOCALDATE; case Types.TIME: return PropertyType.LOCALTIME; case Types.OTHER: //this is a f up as only JSON can be used for other. //means all the gis data types which are also OTHER are not supported switch (typeName) { case "jsonb": return PropertyType.JSON; case "geometry": return getPostGisGeometryType(sqlgGraph, schema, table, column); case "geography": return getPostGisGeographyType(sqlgGraph, schema, table, column); default: throw new RuntimeException("Other type not supported " + typeName); } case Types.BINARY: return BYTE_ARRAY; case Types.ARRAY: return sqlArrayTypeNameToPropertyType(typeName, sqlgGraph, schema, table, column, metaDataIter); default: throw new IllegalStateException("Unknown sqlType " + sqlType); } }
[ "@", "Override", "public", "PropertyType", "sqlTypeToPropertyType", "(", "SqlgGraph", "sqlgGraph", ",", "String", "schema", ",", "String", "table", ",", "String", "column", ",", "int", "sqlType", ",", "String", "typeName", ",", "ListIterator", "<", "Triple", "<"...
This is only used for upgrading from pre sqlg_schema sqlg to a sqlg_schema
[ "This", "is", "only", "used", "for", "upgrading", "from", "pre", "sqlg_schema", "sqlg", "to", "a", "sqlg_schema" ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java#L2108-L2152
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/util/InvocationUtil.java
InvocationUtil.executeLocallyWithRetry
public static LocalRetryableExecution executeLocallyWithRetry(NodeEngine nodeEngine, Operation operation) { if (operation.getOperationResponseHandler() != null) { throw new IllegalArgumentException("Operation must not have a response handler set"); } if (!operation.returnsResponse()) { throw new IllegalArgumentException("Operation must return a response"); } if (operation.validatesTarget()) { throw new IllegalArgumentException("Operation must not validate the target"); } final LocalRetryableExecution execution = new LocalRetryableExecution(nodeEngine, operation); execution.run(); return execution; }
java
public static LocalRetryableExecution executeLocallyWithRetry(NodeEngine nodeEngine, Operation operation) { if (operation.getOperationResponseHandler() != null) { throw new IllegalArgumentException("Operation must not have a response handler set"); } if (!operation.returnsResponse()) { throw new IllegalArgumentException("Operation must return a response"); } if (operation.validatesTarget()) { throw new IllegalArgumentException("Operation must not validate the target"); } final LocalRetryableExecution execution = new LocalRetryableExecution(nodeEngine, operation); execution.run(); return execution; }
[ "public", "static", "LocalRetryableExecution", "executeLocallyWithRetry", "(", "NodeEngine", "nodeEngine", ",", "Operation", "operation", ")", "{", "if", "(", "operation", ".", "getOperationResponseHandler", "(", ")", "!=", "null", ")", "{", "throw", "new", "Illegal...
Constructs a local execution with retry logic. The operation must not have an {@link OperationResponseHandler}, it must return a response and it must not validate the target. @return the local execution @throws IllegalArgumentException if the operation has a response handler set, if it does not return a response or if it validates the operation target @see Operation#returnsResponse() @see Operation#getOperationResponseHandler() @see Operation#validatesTarget()
[ "Constructs", "a", "local", "execution", "with", "retry", "logic", ".", "The", "operation", "must", "not", "have", "an", "{", "@link", "OperationResponseHandler", "}", "it", "must", "return", "a", "response", "and", "it", "must", "not", "validate", "the", "t...
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/util/InvocationUtil.java#L102-L115
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/Scheduler.java
Scheduler.addSession
public void addSession(String id, Session session) { for (SchedulerForType scheduleThread : schedulersForTypes.values()) { scheduleThread.addSession(id, session); } }
java
public void addSession(String id, Session session) { for (SchedulerForType scheduleThread : schedulersForTypes.values()) { scheduleThread.addSession(id, session); } }
[ "public", "void", "addSession", "(", "String", "id", ",", "Session", "session", ")", "{", "for", "(", "SchedulerForType", "scheduleThread", ":", "schedulersForTypes", ".", "values", "(", ")", ")", "{", "scheduleThread", ".", "addSession", "(", "id", ",", "se...
Add a session for scheduling. @param id Identifies the session @param session Actual session to be scheduled
[ "Add", "a", "session", "for", "scheduling", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/Scheduler.java#L124-L128
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyClient.java
RecurlyClient.createPlanAddOn
public AddOn createPlanAddOn(final String planCode, final AddOn addOn) { return doPOST(Plan.PLANS_RESOURCE + "/" + planCode + AddOn.ADDONS_RESOURCE, addOn, AddOn.class); }
java
public AddOn createPlanAddOn(final String planCode, final AddOn addOn) { return doPOST(Plan.PLANS_RESOURCE + "/" + planCode + AddOn.ADDONS_RESOURCE, addOn, AddOn.class); }
[ "public", "AddOn", "createPlanAddOn", "(", "final", "String", "planCode", ",", "final", "AddOn", "addOn", ")", "{", "return", "doPOST", "(", "Plan", ".", "PLANS_RESOURCE", "+", "\"/\"", "+", "planCode", "+", "AddOn", ".", "ADDONS_RESOURCE", ",", "addOn", ","...
Create an AddOn to a Plan <p> @param planCode The planCode of the {@link Plan } to create within recurly @param addOn The {@link AddOn} to create within recurly @return the {@link AddOn} object as identified by the passed in object
[ "Create", "an", "AddOn", "to", "a", "Plan", "<p", ">" ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L1438-L1444
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java
StringUtil.isDigit
public static boolean isDigit(String str, int beginIndex, int endIndex) { char c; for ( int j = beginIndex; j < endIndex; j++ ) { c = str.charAt(j); //make full-width char half-width if ( c > 65280 ) c -= 65248; if ( c < 48 || c > 57 ) { return false; } } return true; }
java
public static boolean isDigit(String str, int beginIndex, int endIndex) { char c; for ( int j = beginIndex; j < endIndex; j++ ) { c = str.charAt(j); //make full-width char half-width if ( c > 65280 ) c -= 65248; if ( c < 48 || c > 57 ) { return false; } } return true; }
[ "public", "static", "boolean", "isDigit", "(", "String", "str", ",", "int", "beginIndex", ",", "int", "endIndex", ")", "{", "char", "c", ";", "for", "(", "int", "j", "=", "beginIndex", ";", "j", "<", "endIndex", ";", "j", "++", ")", "{", "c", "=", ...
check the specified char is a digit or not true will return if it is or return false this method can recognize full-with char @param str @param beginIndex @param endIndex @return boolean
[ "check", "the", "specified", "char", "is", "a", "digit", "or", "not", "true", "will", "return", "if", "it", "is", "or", "return", "false", "this", "method", "can", "recognize", "full", "-", "with", "char" ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java#L272-L285
xerial/snappy-java
src/main/java/org/xerial/snappy/Snappy.java
Snappy.rawUncompress
public static long rawUncompress(long inputAddr, long inputSize, long destAddr) throws IOException { return impl.rawUncompress(inputAddr, inputSize, destAddr); }
java
public static long rawUncompress(long inputAddr, long inputSize, long destAddr) throws IOException { return impl.rawUncompress(inputAddr, inputSize, destAddr); }
[ "public", "static", "long", "rawUncompress", "(", "long", "inputAddr", ",", "long", "inputSize", ",", "long", "destAddr", ")", "throws", "IOException", "{", "return", "impl", ".", "rawUncompress", "(", "inputAddr", ",", "inputSize", ",", "destAddr", ")", ";", ...
Zero-copy decompress using memory addresses. @param inputAddr input memory address @param inputSize input byte size @param destAddr destination address of the uncompressed data @return the uncompressed data size @throws IOException
[ "Zero", "-", "copy", "decompress", "using", "memory", "addresses", "." ]
train
https://github.com/xerial/snappy-java/blob/9df6ed7bbce88186c82f2e7cdcb7b974421b3340/src/main/java/org/xerial/snappy/Snappy.java#L403-L407
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.xdsl_setting_GET
public OvhSetting xdsl_setting_GET() throws IOException { String qPath = "/me/xdsl/setting"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSetting.class); }
java
public OvhSetting xdsl_setting_GET() throws IOException { String qPath = "/me/xdsl/setting"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSetting.class); }
[ "public", "OvhSetting", "xdsl_setting_GET", "(", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/xdsl/setting\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ...
Get xdsl settings linked to the nichandle REST: GET /me/xdsl/setting
[ "Get", "xdsl", "settings", "linked", "to", "the", "nichandle" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L2167-L2172
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/pool/WrapperInvocationHandler.java
WrapperInvocationHandler.getDatabaseMetaDataSurrogate
protected Object getDatabaseMetaDataSurrogate(final Method method, final Object[] args) throws Throwable { if (this.dbmdHandler == null) { Object dbmd = method.invoke(this.delegate, args); this.dbmdHandler = new WrapperInvocationHandler(dbmd, this); } return this.dbmdHandler.surrogate; }
java
protected Object getDatabaseMetaDataSurrogate(final Method method, final Object[] args) throws Throwable { if (this.dbmdHandler == null) { Object dbmd = method.invoke(this.delegate, args); this.dbmdHandler = new WrapperInvocationHandler(dbmd, this); } return this.dbmdHandler.surrogate; }
[ "protected", "Object", "getDatabaseMetaDataSurrogate", "(", "final", "Method", "method", ",", "final", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "if", "(", "this", ".", "dbmdHandler", "==", "null", ")", "{", "Object", "dbmd", "=", "method"...
Surrogate for any method of the delegate that returns an instance of <tt>DatabaseMetaData</tt> object. <p> @param method returning <tt>DatabaseMetaData</tt> @param args to the method @throws java.lang.Throwable the exception, if any, thrown by invoking the given method with the given arguments upon the delegate @return surrogate for the underlying DatabaseMetaData object
[ "Surrogate", "for", "any", "method", "of", "the", "delegate", "that", "returns", "an", "instance", "of", "<tt", ">", "DatabaseMetaData<", "/", "tt", ">", "object", ".", "<p", ">" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/pool/WrapperInvocationHandler.java#L874-L884
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/RepositoryApi.java
RepositoryApi.deleteBranch
public void deleteBranch(Object projectIdOrPath, String branchName) throws GitLabApiException { Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName)); }
java
public void deleteBranch(Object projectIdOrPath, String branchName) throws GitLabApiException { Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName)); }
[ "public", "void", "deleteBranch", "(", "Object", "projectIdOrPath", ",", "String", "branchName", ")", "throws", "GitLabApiException", "{", "Response", ".", "Status", "expectedStatus", "=", "(", "isApiVersion", "(", "ApiVersion", ".", "V3", ")", "?", "Response", ...
Delete a single project repository branch. <pre><code>GitLab Endpoint: DELETE /projects/:id/repository/branches/:branch</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param branchName the name of the branch to delete @throws GitLabApiException if any exception occurs
[ "Delete", "a", "single", "project", "repository", "branch", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryApi.java#L158-L162
jhunters/jprotobuf
v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapEntryLite.java
MapEntryLite.parseEntry
static <K, V> Map.Entry<K, V> parseEntry(CodedInputStream input, Metadata<K, V> metadata, ExtensionRegistryLite extensionRegistry) throws IOException { K key = metadata.defaultKey; V value = metadata.defaultValue; while (true) { int tag = input.readTag(); if (tag == 0) { break; } if (tag == CodedConstant.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) { key = parseField(input, extensionRegistry, metadata.keyType, key); } else if (tag == CodedConstant.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) { value = parseField(input, extensionRegistry, metadata.valueType, value); } else { if (!input.skipField(tag)) { break; } } } return new AbstractMap.SimpleImmutableEntry<K, V>(key, value); }
java
static <K, V> Map.Entry<K, V> parseEntry(CodedInputStream input, Metadata<K, V> metadata, ExtensionRegistryLite extensionRegistry) throws IOException { K key = metadata.defaultKey; V value = metadata.defaultValue; while (true) { int tag = input.readTag(); if (tag == 0) { break; } if (tag == CodedConstant.makeTag(KEY_FIELD_NUMBER, metadata.keyType.getWireType())) { key = parseField(input, extensionRegistry, metadata.keyType, key); } else if (tag == CodedConstant.makeTag(VALUE_FIELD_NUMBER, metadata.valueType.getWireType())) { value = parseField(input, extensionRegistry, metadata.valueType, value); } else { if (!input.skipField(tag)) { break; } } } return new AbstractMap.SimpleImmutableEntry<K, V>(key, value); }
[ "static", "<", "K", ",", "V", ">", "Map", ".", "Entry", "<", "K", ",", "V", ">", "parseEntry", "(", "CodedInputStream", "input", ",", "Metadata", "<", "K", ",", "V", ">", "metadata", ",", "ExtensionRegistryLite", "extensionRegistry", ")", "throws", "IOEx...
Parses the entry. @param <K> the key type @param <V> the value type @param input the input @param metadata the metadata @param extensionRegistry the extension registry @return the map. entry @throws IOException Signals that an I/O exception has occurred.
[ "Parses", "the", "entry", "." ]
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/v3/src/main/java/com/baidu/bjf/remoting/protobuf/MapEntryLite.java#L277-L297
lamydev/Android-Notification
core/src/zemin/notification/NotificationViewCallback.java
NotificationViewCallback.onShowNotification
public void onShowNotification(NotificationView view, View contentView, NotificationEntry entry, int layoutId) { if (DBG) Log.v(TAG, "onShowNotification - " + entry.ID); final Drawable icon = entry.iconDrawable; final CharSequence title = entry.title; final CharSequence text = entry.text; final CharSequence when = entry.showWhen ? entry.whenFormatted : null; ChildViewManager mgr = view.getChildViewManager(); if (layoutId == R.layout.notification_simple || layoutId == R.layout.notification_large_icon || layoutId == R.layout.notification_full) { boolean titleChanged = true; boolean contentChanged = view.isContentLayoutChanged(); NotificationEntry lastEntry = view.getLastNotification(); if (!contentChanged && title != null && lastEntry != null && title.equals(lastEntry.title)) { titleChanged = false; } mgr.setImageDrawable(ICON, icon, titleChanged); mgr.setText(TITLE, title, titleChanged); mgr.setText(TEXT, text); mgr.setText(WHEN, when); } else if (layoutId == R.layout.notification_simple_2) { mgr.setImageDrawable(ICON, icon); mgr.setText(TITLE, title); mgr.setText(TEXT, text); mgr.setText(WHEN, when); } }
java
public void onShowNotification(NotificationView view, View contentView, NotificationEntry entry, int layoutId) { if (DBG) Log.v(TAG, "onShowNotification - " + entry.ID); final Drawable icon = entry.iconDrawable; final CharSequence title = entry.title; final CharSequence text = entry.text; final CharSequence when = entry.showWhen ? entry.whenFormatted : null; ChildViewManager mgr = view.getChildViewManager(); if (layoutId == R.layout.notification_simple || layoutId == R.layout.notification_large_icon || layoutId == R.layout.notification_full) { boolean titleChanged = true; boolean contentChanged = view.isContentLayoutChanged(); NotificationEntry lastEntry = view.getLastNotification(); if (!contentChanged && title != null && lastEntry != null && title.equals(lastEntry.title)) { titleChanged = false; } mgr.setImageDrawable(ICON, icon, titleChanged); mgr.setText(TITLE, title, titleChanged); mgr.setText(TEXT, text); mgr.setText(WHEN, when); } else if (layoutId == R.layout.notification_simple_2) { mgr.setImageDrawable(ICON, icon); mgr.setText(TITLE, title); mgr.setText(TEXT, text); mgr.setText(WHEN, when); } }
[ "public", "void", "onShowNotification", "(", "NotificationView", "view", ",", "View", "contentView", ",", "NotificationEntry", "entry", ",", "int", "layoutId", ")", "{", "if", "(", "DBG", ")", "Log", ".", "v", "(", "TAG", ",", "\"onShowNotification - \"", "+",...
Called when a notification is being displayed. This is the place to update the user interface of child-views for the new notification. @param view @param contentView @param entry @param layoutId
[ "Called", "when", "a", "notification", "is", "being", "displayed", ".", "This", "is", "the", "place", "to", "update", "the", "user", "interface", "of", "child", "-", "views", "for", "the", "new", "notification", "." ]
train
https://github.com/lamydev/Android-Notification/blob/6d6571d2862cb6edbacf9a78125418f7d621c3f8/core/src/zemin/notification/NotificationViewCallback.java#L108-L143
google/jimfs
jimfs/src/main/java/com/google/common/jimfs/PathService.java
PathService.createPathInternal
protected final JimfsPath createPathInternal(@Nullable Name root, Iterable<Name> names) { return new JimfsPath(this, root, names); }
java
protected final JimfsPath createPathInternal(@Nullable Name root, Iterable<Name> names) { return new JimfsPath(this, root, names); }
[ "protected", "final", "JimfsPath", "createPathInternal", "(", "@", "Nullable", "Name", "root", ",", "Iterable", "<", "Name", ">", "names", ")", "{", "return", "new", "JimfsPath", "(", "this", ",", "root", ",", "names", ")", ";", "}" ]
Returns a path with the given root (or no root, if null) and the given names.
[ "Returns", "a", "path", "with", "the", "given", "root", "(", "or", "no", "root", "if", "null", ")", "and", "the", "given", "names", "." ]
train
https://github.com/google/jimfs/blob/3eadff747a3afa7b498030f420d2d04ce700534a/jimfs/src/main/java/com/google/common/jimfs/PathService.java#L176-L178
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/RedisClient.java
RedisClient.connectSentinel
public <K, V> StatefulRedisSentinelConnection<K, V> connectSentinel(RedisCodec<K, V> codec) { checkForRedisURI(); return getConnection(connectSentinelAsync(codec, redisURI, timeout)); }
java
public <K, V> StatefulRedisSentinelConnection<K, V> connectSentinel(RedisCodec<K, V> codec) { checkForRedisURI(); return getConnection(connectSentinelAsync(codec, redisURI, timeout)); }
[ "public", "<", "K", ",", "V", ">", "StatefulRedisSentinelConnection", "<", "K", ",", "V", ">", "connectSentinel", "(", "RedisCodec", "<", "K", ",", "V", ">", "codec", ")", "{", "checkForRedisURI", "(", ")", ";", "return", "getConnection", "(", "connectSent...
Open a connection to a Redis Sentinel that treats keys and use the supplied {@link RedisCodec codec} to encode/decode keys and values. The client {@link RedisURI} must contain one or more sentinels. @param codec Use this codec to encode/decode keys and values, must not be {@literal null} @param <K> Key type @param <V> Value type @return A new stateful Redis Sentinel connection
[ "Open", "a", "connection", "to", "a", "Redis", "Sentinel", "that", "treats", "keys", "and", "use", "the", "supplied", "{", "@link", "RedisCodec", "codec", "}", "to", "encode", "/", "decode", "keys", "and", "values", ".", "The", "client", "{", "@link", "R...
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/RedisClient.java#L464-L467
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java
MethodDelegation.toField
public static MethodDelegation toField(String name, MethodGraph.Compiler methodGraphCompiler) { return withDefaultConfiguration().toField(name, methodGraphCompiler); }
java
public static MethodDelegation toField(String name, MethodGraph.Compiler methodGraphCompiler) { return withDefaultConfiguration().toField(name, methodGraphCompiler); }
[ "public", "static", "MethodDelegation", "toField", "(", "String", "name", ",", "MethodGraph", ".", "Compiler", "methodGraphCompiler", ")", "{", "return", "withDefaultConfiguration", "(", ")", ".", "toField", "(", "name", ",", "methodGraphCompiler", ")", ";", "}" ]
Delegates any intercepted method to invoke a non-{@code static} method on the instance of the supplied field. To be considered a valid delegation target, a method must be visible and accessible to the instrumented type. This is the case if the method's declaring type is either public or in the same package as the instrumented type and if the method is either public or non-private and in the same package as the instrumented type. Private methods can only be used as a delegation target if the delegation is targeting the instrumented type. @param name The field's name. @param methodGraphCompiler The method graph compiler to use. @return A delegation that redirects invocations to a method of the specified field's instance.
[ "Delegates", "any", "intercepted", "method", "to", "invoke", "a", "non", "-", "{", "@code", "static", "}", "method", "on", "the", "instance", "of", "the", "supplied", "field", ".", "To", "be", "considered", "a", "valid", "delegation", "target", "a", "metho...
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/implementation/MethodDelegation.java#L480-L482
pressgang-ccms/PressGangCCMSCommonUtilities
src/main/java/org/jboss/pressgang/ccms/utils/common/HTTPUtilities.java
HTTPUtilities.writeOutContent
public static void writeOutContent(final byte[] data, final String filename, final String mime) { writeOutContent(data, filename, mime, true); }
java
public static void writeOutContent(final byte[] data, final String filename, final String mime) { writeOutContent(data, filename, mime, true); }
[ "public", "static", "void", "writeOutContent", "(", "final", "byte", "[", "]", "data", ",", "final", "String", "filename", ",", "final", "String", "mime", ")", "{", "writeOutContent", "(", "data", ",", "filename", ",", "mime", ",", "true", ")", ";", "}" ...
Used to send arbitrary data to the user (i.e. to download files) @param data The contents of the file @param filename The name of the file to send to the browser @param mime The MIME type of the file
[ "Used", "to", "send", "arbitrary", "data", "to", "the", "user", "(", "i", ".", "e", ".", "to", "download", "files", ")" ]
train
https://github.com/pressgang-ccms/PressGangCCMSCommonUtilities/blob/5ebf5ed30a94c34c33f4708caa04a8da99cbb15c/src/main/java/org/jboss/pressgang/ccms/utils/common/HTTPUtilities.java#L50-L52
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/slim/web/SeleniumDriverSetup.java
SeleniumDriverSetup.connectToDriverForVersionOnAt
public boolean connectToDriverForVersionOnAt(String browser, String version, String platformName, String url) throws MalformedURLException { Platform platform = Platform.valueOf(platformName); DesiredCapabilities desiredCapabilities = new DesiredCapabilities(browser, version, platform); desiredCapabilities.setVersion(version); return createAndSetRemoteDriver(url, desiredCapabilities); }
java
public boolean connectToDriverForVersionOnAt(String browser, String version, String platformName, String url) throws MalformedURLException { Platform platform = Platform.valueOf(platformName); DesiredCapabilities desiredCapabilities = new DesiredCapabilities(browser, version, platform); desiredCapabilities.setVersion(version); return createAndSetRemoteDriver(url, desiredCapabilities); }
[ "public", "boolean", "connectToDriverForVersionOnAt", "(", "String", "browser", ",", "String", "version", ",", "String", "platformName", ",", "String", "url", ")", "throws", "MalformedURLException", "{", "Platform", "platform", "=", "Platform", ".", "valueOf", "(", ...
Connects SeleniumHelper to a remote web driver. @param browser name of browser to connect to. @param version version of browser. @param platformName platform browser must run on. @param url url to connect to browser. @return true. @throws MalformedURLException if supplied url can not be transformed to URL.
[ "Connects", "SeleniumHelper", "to", "a", "remote", "web", "driver", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/web/SeleniumDriverSetup.java#L138-L144
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/http/HttpMessage.java
HttpMessage.setIntField
public void setIntField(String name, int value) { if (_state!=__MSG_EDITABLE) return; _header.put(name, TypeUtil.toString(value)); }
java
public void setIntField(String name, int value) { if (_state!=__MSG_EDITABLE) return; _header.put(name, TypeUtil.toString(value)); }
[ "public", "void", "setIntField", "(", "String", "name", ",", "int", "value", ")", "{", "if", "(", "_state", "!=", "__MSG_EDITABLE", ")", "return", ";", "_header", ".", "put", "(", "name", ",", "TypeUtil", ".", "toString", "(", "value", ")", ")", ";", ...
Sets the value of an integer field. Header or Trailer fields are set depending on message state. @param name the field name @param value the field integer value
[ "Sets", "the", "value", "of", "an", "integer", "field", ".", "Header", "or", "Trailer", "fields", "are", "set", "depending", "on", "message", "state", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/http/HttpMessage.java#L333-L338
brunocvcunha/inutils4j
src/main/java/org/brunocvcunha/inutils4j/thirdparty/DateUtils.java
DateUtils.dateTimeEquals
@SuppressWarnings("deprecation") public static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getDate() == d2.getDate() && d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear() && d1.getHours() == d2.getHours() && d1.getMinutes() == d2.getMinutes() && d1.getSeconds() == d2.getSeconds(); }
java
@SuppressWarnings("deprecation") public static boolean dateTimeEquals(java.util.Date d1, java.util.Date d2) { if (d1 == null || d2 == null) { return false; } return d1.getDate() == d2.getDate() && d1.getMonth() == d2.getMonth() && d1.getYear() == d2.getYear() && d1.getHours() == d2.getHours() && d1.getMinutes() == d2.getMinutes() && d1.getSeconds() == d2.getSeconds(); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "static", "boolean", "dateTimeEquals", "(", "java", ".", "util", ".", "Date", "d1", ",", "java", ".", "util", ".", "Date", "d2", ")", "{", "if", "(", "d1", "==", "null", "||", "d2", "==", ...
Checks the second, hour, month, day, month and year are equal.
[ "Checks", "the", "second", "hour", "month", "day", "month", "and", "year", "are", "equal", "." ]
train
https://github.com/brunocvcunha/inutils4j/blob/223c4443c2cee662576ce644e552588fa114aa94/src/main/java/org/brunocvcunha/inutils4j/thirdparty/DateUtils.java#L237-L249
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/GlobalAddressClient.java
GlobalAddressClient.insertGlobalAddress
@BetaApi public final Operation insertGlobalAddress(ProjectName project, Address addressResource) { InsertGlobalAddressHttpRequest request = InsertGlobalAddressHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .setAddressResource(addressResource) .build(); return insertGlobalAddress(request); }
java
@BetaApi public final Operation insertGlobalAddress(ProjectName project, Address addressResource) { InsertGlobalAddressHttpRequest request = InsertGlobalAddressHttpRequest.newBuilder() .setProject(project == null ? null : project.toString()) .setAddressResource(addressResource) .build(); return insertGlobalAddress(request); }
[ "@", "BetaApi", "public", "final", "Operation", "insertGlobalAddress", "(", "ProjectName", "project", ",", "Address", "addressResource", ")", "{", "InsertGlobalAddressHttpRequest", "request", "=", "InsertGlobalAddressHttpRequest", ".", "newBuilder", "(", ")", ".", "setP...
Creates an address resource in the specified project using the data included in the request. <p>Sample code: <pre><code> try (GlobalAddressClient globalAddressClient = GlobalAddressClient.create()) { ProjectName project = ProjectName.of("[PROJECT]"); Address addressResource = Address.newBuilder().build(); Operation response = globalAddressClient.insertGlobalAddress(project, addressResource); } </code></pre> @param project Project ID for this request. @param addressResource A reserved address resource. (== resource_for beta.addresses ==) (== resource_for v1.addresses ==) (== resource_for beta.globalAddresses ==) (== resource_for v1.globalAddresses ==) @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "an", "address", "resource", "in", "the", "specified", "project", "using", "the", "data", "included", "in", "the", "request", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/GlobalAddressClient.java#L375-L384