code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public void forward(HttpServerRequest request,final Buffer requestBody){
if (httpHook.getMethods().isEmpty()) {
forwarder.handle(request,requestBody);
}
else {
if (httpHook.getMethods().contains(request.method().name())) {
forwarder.handle(request,requestBody);
}
}
}
| Handles the request (consumed) and forwards it to the hook specific destination. |
private ModuleSpecifierContentProposalProvider(IPath rootFolder){
this.rootFolder=rootFolder;
}
| Creates a new module specifier content proposal for the given root folder |
public boolean[] toBooleanArray(){
boolean[] array=new boolean[length];
for (int i=0; i < length; i++) {
array[i]=get(i) != 0.0 ? true : false;
}
return array;
}
| Convert the matrix to a one-dimensional array of boolean values. |
public void simulateMethod(SootMethod method,ReferenceVariable thisVar,ReferenceVariable returnVar,ReferenceVariable params[]){
String subSignature=method.getSubSignature();
if (subSignature.equals("java.lang.String getSystemPackage0(java.lang.String)")) {
java_lang_Package_getSystemPackage0(method,thisVar,returnVar,params);
return;
}
else if (subSignature.equals("java.lang.String[] getSystemPackages0()")) {
java_lang_Package_getSystemPackages0(method,thisVar,returnVar,params);
return;
}
else {
defaultMethod(method,thisVar,returnVar,params);
return;
}
}
| Implements the abstract method simulateMethod. It distributes the request to the corresponding methods by signatures. |
public Charset charset(){
return charset != null ? Charset.forName(charset) : null;
}
| Returns the charset of this media type, or null if this media type doesn't specify a charset. |
public static RegionStatisticsResponse create(DistributionManager dm,InternalDistributedMember recipient,Region r){
RegionStatisticsResponse m=new RegionStatisticsResponse();
m.setRecipient(recipient);
m.regionStatistics=new RemoteCacheStatistics(r.getStatistics());
return m;
}
| Returns a <code>RegionStatisticsResponse</code> that will be returned to the specified recipient. The message will contains a copy of the local manager's system config. |
public void animateText(){
animateText(getStartValue(),getEndValue());
}
| Animates from startValue to endValue |
public boolean isParseComments(){
return parseComments;
}
| Checks if the spider should parse the comments. |
public void addAnimation(BaseAnim anim){
animList.add(anim);
}
| add anim to list |
@Override protected void handleConnect(Connector start,Connector end){
TaskFigure sf=(TaskFigure)start.getOwner();
TaskFigure ef=(TaskFigure)end.getOwner();
sf.addDependency(this);
ef.addDependency(this);
}
| Handles the connection of a connection. Override this method to handle this event. |
public static DeleteServiceSessionsForSubscription parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception {
DeleteServiceSessionsForSubscription object=new DeleteServiceSessionsForSubscription();
int event;
java.lang.String nillableValue=null;
java.lang.String prefix="";
java.lang.String namespaceuri="";
try {
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type") != null) {
java.lang.String fullTypeName=reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type");
if (fullTypeName != null) {
java.lang.String nsPrefix=null;
if (fullTypeName.indexOf(":") > -1) {
nsPrefix=fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix=nsPrefix == null ? "" : nsPrefix;
java.lang.String type=fullTypeName.substring(fullTypeName.indexOf(":") + 1);
if (!"deleteServiceSessionsForSubscription".equals(type)) {
java.lang.String nsUri=reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (DeleteServiceSessionsForSubscription)ExtensionMapper.getTypeObject(nsUri,type,reader);
}
}
}
java.util.Vector handledAttributes=new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("","subscriptionKey").equals(reader.getName())) {
java.lang.String content=reader.getElementText();
object.setSubscriptionKey(org.apache.axis2.databinding.utils.ConverterUtil.convertToLong(content));
reader.next();
}
else {
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement()) throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getLocalName());
}
catch ( javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
| static method to create the object Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable If this object is not an element, it is a complex type and the reader is at the event just after the outer start element Postcondition: If this object is an element, the reader is positioned at its end element If this object is a complex type, the reader is positioned at the end element of its outer element |
static public void assertEquals(int expected,int actual){
assertEquals(null,expected,actual);
}
| Asserts that two ints are equal. |
public void closeResultSet(ResultSet rs){
try {
if (rs != null) {
Statement stmt=rs.getStatement();
rs.close();
if (stmt != null) stmt.close();
}
}
catch ( SQLException e) {
logger.error("Error al cerrar el ResultSet",e);
}
}
| Cierra el conjunto de resultados de una consulta realizada. |
public RMSProp(double rho){
setRho(rho);
}
| Creates a new RMSProp updater |
public boolean isTaxExempt(){
Object oo=get_Value(COLUMNNAME_IsTaxExempt);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get SO Tax exempt. |
public static AtomContent forEntry(XmlNamespaceDictionary namespaceDictionary,Object entry){
return new AtomContent(namespaceDictionary,entry,true);
}
| Returns a new instance of HTTP content for an Atom entry. |
private void createCSVvalue(StringBuffer sb,char delimiter,String content){
if (content == null || content.length() == 0) return;
boolean needMask=false;
StringBuffer buff=new StringBuffer();
char chars[]=content.toCharArray();
for (int i=0; i < chars.length; i++) {
char c=chars[i];
if (c == '"') {
needMask=true;
buff.append(c);
}
else if (!needMask && (c == delimiter || !Character.isLetterOrDigit(c))) needMask=true;
buff.append(c);
}
if (needMask) sb.append('"').append(buff).append('"');
else sb.append(buff);
}
| Add Content to CSV string. Encapsulate/mask content in " if required |
public boolean deleteRows(Map<String,?> fromRow) throws IOException {
return deleteRowsImpl(findRows(fromRow).setColumnNames(Collections.<String>emptySet()).iterator());
}
| Deletes any rows in the "to" table based on the given columns in the "from" table. |
private void check(final int n){
if (n < 0) throw new ArithmeticException("Factorial: expected n >= 0");
}
| Checks if <code>n</code> is >= 0. |
static void testIntFloorMod(int x,int y,Object expected){
Object result=doFloorMod(x,y);
if (!resultEquals(result,expected)) {
fail("FAIL: Math.floorMod(%d, %d) = %s; expected %s%n",x,y,result,expected);
}
Object strict_result=doStrictFloorMod(x,y);
if (!resultEquals(strict_result,expected)) {
fail("FAIL: StrictMath.floorMod(%d, %d) = %s; expected %s%n",x,y,strict_result,expected);
}
try {
int tmp=x / y;
double ff=x - Math.floor((double)x / (double)y) * y;
int fr=(int)ff;
boolean t=(fr == ((Integer)result));
if (!result.equals(fr)) {
fail("FAIL: Math.floorMod(%d, %d) = %s differs from Math.floor(x, y): %d%n",x,y,result,fr);
}
}
catch ( ArithmeticException ae) {
if (y != 0) {
fail("FAIL: Math.floorMod(%d, %d); unexpected %s%n",x,y,ae);
}
}
}
| Test FloorMod with int data. |
public boolean compareNotifyContext(Object object){
return context == object;
}
| Compare an object to the notification context. |
public int compare(final T o1,final T o2){
String sig1=StringUtility.constructMethodSignature(o1.getMethod().getMethod(),o1.getParameters());
String sig2=StringUtility.constructMethodSignature(o2.getMethod().getMethod(),o2.getParameters());
return sig1.compareTo(sig2);
}
| Arrange methods by class and method name. |
public Object run(Class scriptClass,GroovyClassLoader loader){
try {
Class testNGClass=loader.loadClass("org.testng.TestNG");
Object testng=InvokerHelper.invokeConstructorOf(testNGClass,new Object[]{});
InvokerHelper.invokeMethod(testng,"setTestClasses",new Object[]{scriptClass});
Class listenerClass=loader.loadClass("org.testng.TestListenerAdapter");
Object listener=InvokerHelper.invokeConstructorOf(listenerClass,new Object[]{});
InvokerHelper.invokeMethod(testng,"addListener",new Object[]{listener});
return InvokerHelper.invokeMethod(testng,"run",new Object[]{});
}
catch ( ClassNotFoundException e) {
throw new GroovyRuntimeException("Error running TestNG test.",e);
}
}
| Utility method to run a TestNG test. |
private static boolean checkForTarget(BeanInstance candidate,Vector<Object> listToCheck,Integer... tab){
int tabIndex=0;
if (tab.length > 0) {
tabIndex=tab[0].intValue();
}
Vector<BeanConnection> connections=TABBED_CONNECTIONS.get(tabIndex);
for (int i=0; i < connections.size(); i++) {
BeanConnection bc=connections.elementAt(i);
if (bc.getTarget() != candidate) {
continue;
}
for (int j=0; j < listToCheck.size(); j++) {
BeanInstance tempSource=(BeanInstance)listToCheck.elementAt(j);
if (bc.getSource() == tempSource) {
return true;
}
}
}
return false;
}
| A candidate BeanInstance can be an output if it is in the listToCheck and it is the target of a connection from a source that is in the listToCheck |
public void testLong() throws IOException {
Directory dir=newDirectory();
RandomIndexWriter writer=new RandomIndexWriter(random(),dir);
Document doc=new Document();
doc.add(new NumericDocValuesField("value",3000000000L));
doc.add(newStringField("value","3000000000",Field.Store.YES));
writer.addDocument(doc);
doc=new Document();
doc.add(new NumericDocValuesField("value",-1));
doc.add(newStringField("value","-1",Field.Store.YES));
writer.addDocument(doc);
doc=new Document();
doc.add(new NumericDocValuesField("value",4));
doc.add(newStringField("value","4",Field.Store.YES));
writer.addDocument(doc);
IndexReader ir=writer.getReader();
writer.close();
IndexSearcher searcher=newSearcher(ir);
Sort sort=new Sort(new SortField("value",SortField.Type.LONG));
TopDocs td=searcher.search(new MatchAllDocsQuery(),10,sort);
assertEquals(3,td.totalHits);
assertEquals("-1",searcher.doc(td.scoreDocs[0].doc).get("value"));
assertEquals("4",searcher.doc(td.scoreDocs[1].doc).get("value"));
assertEquals("3000000000",searcher.doc(td.scoreDocs[2].doc).get("value"));
ir.close();
dir.close();
}
| Tests sorting on type long |
public boolean isWaitingRequest(Request request){
return exchangeMap.containsKey(request);
}
| Checks if a thread is waiting for the arrive of a specific response. |
private void installSubcomponents(){
int decorationStyle=getWindowDecorationStyle();
if (decorationStyle == JRootPane.FRAME || decorationStyle == JRootPane.PLAIN_DIALOG) {
createActions();
menuBar=createMenuBar();
add(menuBar);
createButtons();
add(closeButton);
Object isSetupButtonVisibleObj=UIManager.get("RootPane.setupButtonVisible");
boolean isSetupButtonVisible=(isSetupButtonVisibleObj == null ? true : (Boolean)isSetupButtonVisibleObj);
if (isSetupButtonVisible) add(setupButton);
if (decorationStyle != JRootPane.PLAIN_DIALOG) {
add(iconifyButton);
add(toggleButton);
menuBar.setEnabled(false);
}
}
else if (decorationStyle == JRootPane.INFORMATION_DIALOG || decorationStyle == JRootPane.ERROR_DIALOG || decorationStyle == JRootPane.COLOR_CHOOSER_DIALOG || decorationStyle == JRootPane.FILE_CHOOSER_DIALOG || decorationStyle == JRootPane.QUESTION_DIALOG || decorationStyle == JRootPane.WARNING_DIALOG) {
createActions();
createButtons();
add(closeButton);
}
}
| Adds any sub-Components contained in the <code>MetalTitlePane</code>. |
public AttributeSet copyAttributes(){
return (AttributeSet)clone();
}
| Makes a copy of the attributes. |
private Object writeReplace(){
return new Ser(Ser.YEAR_MONTH_TYPE,this);
}
| Writes the object using a <a href="../../serialized-form.html#java.time.Ser">dedicated serialized form</a>. |
private int assertPivotCountsAreCorrect(String pivotName,SolrParams baseParams,PivotField constraint) throws SolrServerException {
SolrParams p=SolrParams.wrapAppended(baseParams,params("fq",buildFilter(constraint)));
List<PivotField> subPivots=null;
try {
assertNumFound(pivotName,constraint.getCount(),p);
subPivots=constraint.getPivot();
}
catch ( Exception e) {
throw new RuntimeException(pivotName + ": count query failed: " + p+ ": "+ e.getMessage(),e);
}
int depth=0;
if (null != subPivots) {
assertTraceOk(pivotName,baseParams,subPivots);
for ( PivotField subPivot : subPivots) {
depth=assertPivotCountsAreCorrect(pivotName,p,subPivot);
}
}
return depth + 1;
}
| Recursive Helper method for asserting that pivot constraint counds match results when filtering on those constraints. Returns the recursive depth reached (for sanity checking) |
public List<RelatedResourceRep> listByHost(URI hostId){
UnManagedVolumeList response=client.get(UnManagedVolumeList.class,PathConstants.UNMANAGED_VOLUME_BY_HOST_URL,hostId);
return ResourceUtils.defaultList(response.getUnManagedVolumes());
}
| Gets the list of unmanaged volumes for the given host by ID. <p> API Call: <tt>GET /compute/hosts/{hostId}/unmanaged-volumes</tt> |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case EipPackage.SERVICE_REF__NAME:
return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name);
case EipPackage.SERVICE_REF__REFERENCE:
return REFERENCE_EDEFAULT == null ? reference != null : !REFERENCE_EDEFAULT.equals(reference);
case EipPackage.SERVICE_REF__OPERATIONS:
return operations != null && !operations.isEmpty();
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public final byte[] encode() throws IOException {
DerOutputStream out=new DerOutputStream();
derEncode(out);
return out.toByteArray();
}
| Returns the DER-encoded X.509 AlgorithmId as a byte array. |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:22.391 -0500",hash_original_method="6CF19E73C026523F689130FF9C39751C",hash_generated_method="1598F5EB9AD023A3CBF17A833242949C") public CancellationException(String message){
super(message);
}
| Constructs a <tt>CancellationException</tt> with the specified detail message. |
public DeviceIterator(Iterator<Device> subIterator,IEntityClass[] entityClasses,Long macAddress,Short vlan,Integer ipv4Address,Long switchDPID,Integer switchPort){
super(subIterator);
this.entityClasses=entityClasses;
this.subIterator=subIterator;
this.macAddress=macAddress;
this.vlan=vlan;
this.ipv4Address=ipv4Address;
this.switchDPID=switchDPID;
this.switchPort=switchPort;
}
| Construct a new device iterator over the key fields |
public static void binaryToKOML(String binary,String koml) throws Exception {
Object o;
checkKOML();
o=readBinary(binary);
if (o == null) throw new Exception("Failed to deserialize object from binary file '" + binary + "'!");
KOML.write(koml,o);
}
| converts a binary file into a KOML XML file |
protected void onPrepareRequest(HttpUriRequest request) throws IOException {
}
| Called before the request is executed using the underlying HttpClient. <p>Overwrite in subclasses to augment the request.</p> |
public static TrapCodeOperand StackOverflow(){
return new TrapCodeOperand((byte)RuntimeEntrypoints.TRAP_STACK_OVERFLOW);
}
| Create a trap code operand for a stack overflow |
protected void fireActionPerformed(MouseEvent event){
ActionListener[] listeners=getActionListeners();
ActionEvent e=null;
for (int i=0; i < listeners.length; i++) {
if (e == null) e=new ActionEvent(this,ActionEvent.ACTION_PERFORMED,"pi",event.getWhen(),event.getModifiers());
listeners[i].actionPerformed(e);
}
}
| Notifies all listeners that have registered interest for notification on this event type. The event instance is lazily created using the <code>event</code> parameter. |
public FastAdapterDialog<Item> withNegativeButton(String text,OnClickListener listener){
return withButton(BUTTON_NEGATIVE,text,listener);
}
| Set a listener to be invoked when the negative button of the dialog is pressed. |
public CallableStatement prepareCall(String sql) throws SQLException {
return prepareCall(sql,ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_READ_ONLY);
}
| Creates a <code>CallableStatement</code> object for calling database stored procedures. The <code>CallableStatement</code> object provides methods for setting up its IN and OUT parameters, and methods for executing the call to a stored procedure. <P><B>Note:</B> This method is optimized for handling stored procedure call statements. Some drivers may send the call statement to the database when the method <code>prepareCall</code> is done; others may wait until the <code>CallableStatement</code> object is executed. This has no direct effect on users; however, it does affect which method throws certain SQLExceptions. Result sets created using the returned CallableStatement will have forward-only type and read-only concurrency, by default. |
public boolean test(char ch){
if (ch <= MAX_ASCII_CHAR) {
return asciiSet.get(ch);
}
return testRanges(ch);
}
| Tests to see if a single character matches the character set. |
public boolean drawEdgeFeatures(){
return drawEdgeFeatures;
}
| Return true if we may draw some edge features. |
public Select<Model> sortDesc(String... columns){
for ( String column : columns) {
sortingOrderList.add(column + " DESC");
}
return this;
}
| Sorts the specified columns in DESC order. The order here is important, as the sorting will be done in the same order the columns are added. |
@Override public Object clone() throws CloneNotSupportedException {
return super.clone();
}
| Returns a clone of this needle. |
public static ThrottleFrameManager instance(){
if (instance == null) {
instance=new ThrottleFrameManager();
}
return instance;
}
| Get the singleton instance of this class. |
public long write(final byte[] bits,final long len) throws IOException {
return writeByteOffset(bits,0,len);
}
| Writes a sequence of bits. Bits will be written in the natural way: the first bit is bit 7 of the first byte, the eightth bit is bit 0 of the first byte, the ninth bit is bit 7 of the second byte and so on. |
public TemplateProposal(Template template,TemplateContext context,Region region,Images image){
Assert.isNotNull(template);
Assert.isNotNull(context);
Assert.isNotNull(region);
fTemplate=template;
fContext=context;
fImage=image;
fRegion=region;
fDisplayString=null;
fRelevance=computeRelevance();
}
| Creates a template proposal with a template and its context. |
public static Set<JavaClassAndMethod> resolveMethodCallTargets(InvokeInstruction invokeInstruction,TypeFrame typeFrame,ConstantPoolGen cpg) throws DataflowAnalysisException, ClassNotFoundException {
short opcode=invokeInstruction.getOpcode();
if (opcode == Constants.INVOKESTATIC) {
HashSet<JavaClassAndMethod> result=new HashSet<JavaClassAndMethod>();
JavaClassAndMethod targetMethod=findInvocationLeastUpperBound(invokeInstruction,cpg,CONCRETE_METHOD);
if (targetMethod != null) {
result.add(targetMethod);
}
return result;
}
if (!typeFrame.isValid()) {
return new HashSet<JavaClassAndMethod>();
}
Type receiverType;
boolean receiverTypeIsExact;
if (opcode == Constants.INVOKESPECIAL) {
receiverType=ObjectTypeFactory.getInstance(invokeInstruction.getClassName(cpg));
receiverTypeIsExact=false;
}
else {
int instanceStackLocation=typeFrame.getInstanceStackLocation(invokeInstruction,cpg);
receiverType=typeFrame.getStackValue(instanceStackLocation);
if (!(receiverType instanceof ReferenceType)) {
return new HashSet<JavaClassAndMethod>();
}
receiverTypeIsExact=typeFrame.isExact(instanceStackLocation);
}
if (DEBUG_METHOD_LOOKUP) {
System.out.println("[receiver type is " + receiverType + ", "+ (receiverTypeIsExact ? "exact]" : " not exact]"));
}
return resolveMethodCallTargets((ReferenceType)receiverType,invokeInstruction,cpg,receiverTypeIsExact);
}
| Resolve possible method call targets. This works for both static and instance method calls. |
public void reset(){
final long now=System.currentTimeMillis();
while (m_currentRotation + TIME_24_HOURS < now) {
m_currentRotation+=TIME_24_HOURS;
}
}
| reset interval history counters. |
protected <A extends Annotation>A findAnnotation(Class<A> annotationClass,Annotated annotated,boolean includePackage,boolean includeClass,boolean includeSuperclasses){
A annotation=annotated.getAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
Class<?> memberClass=null;
if (annotated instanceof AnnotatedParameter) {
memberClass=((AnnotatedParameter)annotated).getDeclaringClass();
}
else {
AnnotatedElement annType=annotated.getAnnotated();
if (annType instanceof Member) {
memberClass=((Member)annType).getDeclaringClass();
if (includeClass) {
annotation=(A)memberClass.getAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
}
}
else if (annType instanceof Class<?>) {
memberClass=(Class<?>)annType;
}
else {
throw new IllegalStateException("Unsupported annotated member: " + annotated.getClass().getName());
}
}
if (memberClass != null) {
if (includeSuperclasses) {
Class<?> superclass=memberClass.getSuperclass();
while (superclass != null && superclass != Object.class) {
annotation=(A)superclass.getAnnotation(annotationClass);
if (annotation != null) {
return annotation;
}
superclass=superclass.getSuperclass();
}
}
if (includePackage) {
Package pkg=memberClass.getPackage();
if (pkg != null) {
return memberClass.getPackage().getAnnotation(annotationClass);
}
}
}
return null;
}
| Finds an annotation associated with given annotatable thing; or if not found, a default annotation it may have (from super class, package and so on) |
private void migrateToStack(){
removeFromQueue();
if (!inStack()) {
moveToStackBottom();
}
hot();
}
| Moves this entry from the queue to the stack, marking it hot (as cold resident entries must remain in the queue). |
static void executeRemoteCommand(InetSocketAddress adbSockAddr,AdbService adbService,String command,Device device,IShellOutputReceiver rcvr,long maxTimeToOutputResponse,TimeUnit maxTimeUnits,@Nullable InputStream is) throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException, IOException {
long maxTimeToOutputMs=0;
if (maxTimeToOutputResponse > 0) {
if (maxTimeUnits == null) {
throw new NullPointerException("Time unit must not be null for non-zero max.");
}
maxTimeToOutputMs=maxTimeUnits.toMillis(maxTimeToOutputResponse);
}
Log.v("ddms","execute: running " + command);
try (SocketChannel adbChan=SocketChannel.open(adbSockAddr)){
adbChan.configureBlocking(false);
setDevice(adbChan,device);
byte[] request=formAdbRequest(adbService.name().toLowerCase() + ":" + command);
write(adbChan,request);
AdbResponse resp=readAdbResponse(adbChan,false);
if (!resp.okay) {
if (device.logError) Log.e("ddms","ADB rejected shell command (" + command + "): "+ resp.message);
throw new AdbCommandRejectedException(resp.message);
}
byte[] data=new byte[16384];
if (is != null) {
int read;
while ((read=is.read(data)) != -1) {
ByteBuffer buf=ByteBuffer.wrap(data,0,read);
int written=0;
while (buf.hasRemaining()) {
written+=adbChan.write(buf);
}
if (written != read) {
Log.e("ddms","ADB write inconsistency, wrote " + written + "expected "+ read);
throw new AdbCommandRejectedException("write failed");
}
}
}
ByteBuffer buf=ByteBuffer.wrap(data);
buf.clear();
long timeToResponseCount=0;
while (true) {
int count;
if (rcvr != null && rcvr.isCancelled()) {
Log.v("ddms","execute: cancelled");
break;
}
count=adbChan.read(buf);
if (count < 0) {
if (rcvr != null) {
rcvr.flush();
}
Log.v("ddms","execute '" + command + "' on '"+ device+ "' : EOF hit. Read: "+ count);
break;
}
else if (count == 0) {
try {
int wait=WAIT_TIME * 5;
timeToResponseCount+=wait;
if (maxTimeToOutputMs > 0 && timeToResponseCount > maxTimeToOutputMs) {
throw new ShellCommandUnresponsiveException();
}
Thread.sleep(wait);
}
catch ( InterruptedException ie) {
Thread.currentThread().interrupt();
throw new TimeoutException("executeRemoteCommand interrupted with immediate timeout via interruption.");
}
}
else {
timeToResponseCount=0;
if (rcvr != null) {
rcvr.addOutput(buf.array(),buf.arrayOffset(),buf.position());
}
buf.rewind();
}
}
}
finally {
Log.v("ddms","execute: returning");
}
}
| Executes a remote command on the device and retrieve the output. The output is handed to <var>rcvr</var> as it arrives. The command is execute by the remote service identified by the adbService parameter. |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-25 14:54:54.321 -0400",hash_original_method="1610CA05F41C29253E59D62C2A59995F",hash_generated_method="7FD8BC39B742BD433F67325F94E96443") public boolean equals(Object object){
boolean result=false;
if (object instanceof DrmSupportInfo) {
result=mFileSuffixList.equals(((DrmSupportInfo)object).mFileSuffixList) && mMimeTypeList.equals(((DrmSupportInfo)object).mMimeTypeList) && mDescription.equals(((DrmSupportInfo)object).mDescription);
}
return result;
}
| Overridden <code>equals</code> implementation. |
void showLicenseWindow(){
}
| Shows the license window. |
public JdkConfig(Project project){
String javaHome;
if (project.hasProperty(KEY_JAVA)) {
javaHome=(String)project.property(KEY_JAVA);
}
else {
javaHome=StandardSystemProperty.JAVA_HOME.value();
}
Objects.requireNonNull(javaHome,"Could not find JRE dir, set 'org.gradle.java.home' to fix.");
this.rootFolder=new File(javaHome);
}
| Creates a JDK using the project's `org.gradle.java.home` property. |
public boolean isAdPosition(int position){
int result=(position - getOffsetValue()) % (getNoOfDataBetweenAds() + 1);
return result == 0;
}
| Checks if adapter position is an ad position. |
protected void sequence_Group_Term(ISerializationContext context,Group semanticObject){
genericSequencer.createSequence(context,semanticObject);
}
| Contexts: Disjunction returns Group Disjunction.Disjunction_0_1_0 returns Group Alternative returns Group Alternative.Sequence_1_0 returns Group Term returns Group Constraint: (nonCapturing?='?'? pattern=Disjunction quantifier=Quantifier?) |
public void findAndInit(Object someObj){
if (someObj instanceof LayerHandler) {
Debug.message("bc","LayersMenu found a LayerHandler");
setLayerHandler((LayerHandler)someObj);
}
else if (someObj instanceof LayersPanel) {
setupEditLayersButton((LayersPanel)someObj);
}
else if (someObj instanceof LayerAddPanel) {
setupLayerAddButton((LayerAddPanel)someObj);
}
}
| Called when the BeanContext membership changes with object from the BeanContext. This lets this object hook up with what it needs. It expects to find only one LayerHandler and LayersPanel in the BeanContext. If another LayerHandler/LayersPanel is somehow added to the BeanContext, however, it will drop the connection to the component it is set up to listen to, and rewire itself to reflect the status of the last version of the LayerHandler/LayersPanel found. |
private static void usage(){
System.out.println("Syntax: ProjectHostingReadDemo --project <project> " + "[--username <username> --password <password>]\n" + "\t<project>\tProject on which the demo will run.\n"+ "\t<username>\tGoogle Account username\n"+ "\t<password>\tGoogle Account password\n");
}
| Prints usage of this application. |
public boolean contains(byte[] bytes){
int[] hashes=createHashes(bytes,k,getNewDigestFunction());
for ( int hash : hashes) {
if (!bitset.get(Math.abs(hash % bitSetSize))) {
return false;
}
}
return true;
}
| Returns true if the array of bytes could have been inserted into the Bloom filter. Use getFalsePositiveProbability() to calculate the probability of this being correct. |
static void lnprint(String key){
System.out.println();
System.out.print(textResources.getString(key));
}
| Print a newline, followed by the string. |
private void showFeedback(String feedback){
if (myHost != null) {
myHost.showFeedback(feedback);
}
else {
System.out.println(feedback);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public void finishActivity(){
finishActivity(currentActivity());
}
| Finish the current activity. |
public Color24(){
this.r=this.g=this.b=0;
}
| Creates a 24 bit 888 RGB color with all values set to 0. |
public RealLiteralItemProvider(AdapterFactory adapterFactory){
super(adapterFactory);
}
| This constructs an instance from a factory and a notifier. <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public void afterLoad(TermsEnum termsEnum,long actualUsed){
if (termsEnum instanceof RamAccountingTermsEnum) {
estimatedBytes=((RamAccountingTermsEnum)termsEnum).getTotalBytes();
}
breaker.addWithoutBreaking(-(estimatedBytes - actualUsed));
}
| Adjust the circuit breaker now that terms have been loaded, getting the actual used either from the parameter (if estimation worked for the entire set), or from the TermsEnum if it has been wrapped in a RamAccountingTermsEnum. |
public void notifyChange(ChangeType changeType,T t,String id,Rectangle2D.Double previous,Rectangle2D.Double current){
listeners.changed(changeType,t,id,previous,current);
}
| Notifies this Surface that changes to its underlying layout have occurred. |
public final int yylength(){
return zzMarkedPos - zzStartRead;
}
| Returns the length of the matched text region. |
@Override public void protect(Address start,int pages){
int startChunk=addressToMmapChunksDown(start);
int chunks=pagesToMmapChunksUp(pages);
int endChunk=startChunk + chunks;
lock.acquire();
for (int chunk=startChunk; chunk < endChunk; chunk++) {
if (mapped[chunk] == MAPPED) {
Address mmapStart=mmapChunksToAddress(chunk);
if (!VM.memory.mprotect(mmapStart,MMAP_CHUNK_BYTES)) {
lock.release();
VM.assertions.fail("Mmapper.mprotect failed");
}
else {
if (verbose) {
Log.write("mprotect succeeded at chunk ");
Log.write(chunk);
Log.write(" ");
Log.write(mmapStart);
Log.write(" with len = ");
Log.writeln(MMAP_CHUNK_BYTES);
}
}
mapped[chunk]=PROTECTED;
}
else {
if (VM.VERIFY_ASSERTIONS) VM.assertions._assert(mapped[chunk] == PROTECTED);
}
}
lock.release();
}
| Memory protect a range of pages (using mprotect or equivalent). Note that protection occurs at chunk granularity, not page granularity. |
public boolean updateOnAny(int bits){
return (updatemask & bits) != 0;
}
| Update if any oft these bits is set. |
public UnsignedInteger add(UnsignedInteger increment){
return valueOf(getValue() + increment.getValue());
}
| Add a value. Note that this object is not changed, but a new one is created. |
@RequestMapping(value="/activate",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE) @Timed public ResponseEntity<String> activateAccount(@RequestParam(value="key") String key){
return Optional.ofNullable(userService.activateRegistration(key)).map(null).orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
}
| GET /activate -> activate the registered user. |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:59:14.133 -0500",hash_original_method="276911B1F31C12ADE55317E1DBA28A10",hash_generated_method="CB85081F1CD1198E5F33E7DDF76DB880") private static int readRilMessage(InputStream is,byte[] buffer) throws IOException {
int countRead;
int offset;
int remaining;
int messageLength;
offset=0;
remaining=4;
do {
countRead=is.read(buffer,offset,remaining);
if (countRead < 0) {
Log.e(LOG_TAG,"Hit EOS reading message length");
return -1;
}
offset+=countRead;
remaining-=countRead;
}
while (remaining > 0);
messageLength=((buffer[0] & 0xff) << 24) | ((buffer[1] & 0xff) << 16) | ((buffer[2] & 0xff) << 8)| (buffer[3] & 0xff);
offset=0;
remaining=messageLength;
do {
countRead=is.read(buffer,offset,remaining);
if (countRead < 0) {
Log.e(LOG_TAG,"Hit EOS reading message. messageLength=" + messageLength + " remaining="+ remaining);
return -1;
}
offset+=countRead;
remaining-=countRead;
}
while (remaining > 0);
return messageLength;
}
| Reads in a single RIL message off the wire. A RIL message consists of a 4-byte little-endian length and a subsequent series of bytes. The final message (length header omitted) is read into <code>buffer</code> and the length of the final message (less header) is returned. A return value of -1 indicates end-of-stream. |
@Deprecated public List<ExportGroupRestRep> findByHostOrCluster(URI hostId,URI projectId,URI virtualArrayId){
HostRestRep host=parent.hosts().get(hostId);
URI clusterId=(host != null) ? id(host.getCluster()) : null;
ResourceFilter<ExportGroupRestRep> filter;
if (virtualArrayId == null) {
filter=new ExportHostOrClusterFilter(hostId,clusterId);
}
else {
filter=new ExportHostOrClusterFilter(hostId,clusterId).and(new ExportVirtualArrayFilter(virtualArrayId));
}
return findByProject(projectId,filter);
}
| Finds the exports associated with a host (or that host's cluster) that are for the given project. If a virtual array ID is specified, only exports associated with that virtual array are returned. |
public void runTest() throws Throwable {
String namespaceURI="http://www.w3.org/XML/1998/namespaces";
String qualifiedName="xml:attr1";
Document doc;
Attr newAttr;
doc=(Document)load("staffNS",false);
{
boolean success=false;
try {
newAttr=doc.createAttributeNS(namespaceURI,qualifiedName);
}
catch ( DOMException ex) {
success=(ex.code == DOMException.NAMESPACE_ERR);
}
assertTrue("throw_NAMESPACE_ERR",success);
}
}
| Runs the test case. |
protected void runTests(boolean weighted,boolean multiInstance,boolean updateable){
boolean PNom=canPredict(true,false,false,false,false,multiInstance)[0];
boolean PNum=canPredict(false,true,false,false,false,multiInstance)[0];
boolean PStr=canPredict(false,false,true,false,false,multiInstance)[0];
boolean PDat=canPredict(false,false,false,true,false,multiInstance)[0];
boolean PRel;
if (!multiInstance) {
PRel=canPredict(false,false,false,false,true,multiInstance)[0];
}
else {
PRel=false;
}
if (PNom || PNum || PStr|| PDat|| PRel) {
if (weighted) {
instanceWeights(PNom,PNum,PStr,PDat,PRel,multiInstance);
}
canHandleZeroTraining(PNom,PNum,PStr,PDat,PRel,multiInstance);
boolean handleMissingPredictors=canHandleMissing(PNom,PNum,PStr,PDat,PRel,multiInstance,true,20)[0];
if (handleMissingPredictors) {
canHandleMissing(PNom,PNum,PStr,PDat,PRel,multiInstance,true,100);
}
correctBuildInitialisation(PNom,PNum,PStr,PDat,PRel,multiInstance);
datasetIntegrity(PNom,PNum,PStr,PDat,PRel,multiInstance,handleMissingPredictors);
if (updateable) {
updatingEquality(PNom,PNum,PStr,PDat,PRel,multiInstance);
}
}
}
| Run a battery of tests |
public static Integer valueOf(String string) throws NumberFormatException {
return valueOf(parseInt(string));
}
| Parses the specified string as a signed decimal integer value. |
public boolean hasQuery(){
return (_query != null);
}
| Tell whether or not this URI has query. |
public void testSequenceLinearizableOperations() throws Throwable {
testSequenceOperations(5,Query.ConsistencyLevel.LINEARIZABLE);
}
| Tests that operations are properly sequenced on the client. |
public StringConverter(final Object defaultValue){
super(defaultValue);
}
| Construct a <b>java.lang.String</b> <i>Converter</i> that returns a default value if an error occurs. |
private boolean isLabelTypeExistsInStorage(AbstractStorageLabelType<?> labelType,Set<AbstractStorageLabel<?>> labelsInStorages){
for ( AbstractStorageLabel<?> label : labelsInStorages) {
if (ObjectUtils.equals(label.getStorageLabelType(),labelType)) {
return true;
}
}
return false;
}
| Returns if any storage in collection of storages does contain at least one label that is of the given label type. |
public void addChangeListener(ChangeListener l){
changeSupport.addChangeListener(l);
}
| Adds a <code>ChangeListener</code>. |
public void keyPressed(KeyEvent e){
switch (e.getKeyCode()) {
case KeyEvent.VK_BACK_SPACE:
case KeyEvent.VK_ENTER:
case KeyEvent.VK_DELETE:
case KeyEvent.VK_TAB:
e.consume();
break;
}
}
| Called when a key is pressed. |
public void writeNext(String[] nextLine){
writeNext(nextLine,true);
}
| Writes the next line to the file. |
public void run(){
if (Thread.currentThread().isInterrupted()) return;
if (this.elem.loadImage()) this.elem.notifyImageLoaded();
}
| Retrieves and loads the image source from this request task's texture atlas element, and notifies the element when the load completes. This does nothing if the current thread has been interrupted. |
protected byte[] engineUpdate(byte[] input,int inputOffset,int inputLen){
return core.update(input,inputOffset,inputLen);
}
| Continues a multiple-part encryption or decryption operation (depending on how this cipher was initialized), processing another data part. <p>The first <code>inputLen</code> bytes in the <code>input</code> buffer, starting at <code>inputOffset</code>, are processed, and the result is stored in a new buffer. |
protected void createPanel(){
JPanel panel;
JPanel panel2;
setLayout(new BorderLayout());
m_ConnectionPanel=new ConnectionPanel(m_Parent);
panel=new JPanel(new BorderLayout());
add(panel,BorderLayout.NORTH);
panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Connection"),BorderFactory.createEmptyBorder(0,5,5,5)));
panel.add(m_ConnectionPanel,BorderLayout.CENTER);
m_QueryPanel=new QueryPanel(m_Parent);
panel=new JPanel(new BorderLayout());
add(panel,BorderLayout.CENTER);
panel2=new JPanel(new BorderLayout());
panel2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Query"),BorderFactory.createEmptyBorder(0,5,5,5)));
panel2.add(m_QueryPanel,BorderLayout.NORTH);
panel.add(panel2,BorderLayout.NORTH);
m_ResultPanel=new ResultPanel(m_Parent);
m_ResultPanel.setQueryPanel(m_QueryPanel);
panel2=new JPanel(new BorderLayout());
panel2.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Result"),BorderFactory.createEmptyBorder(0,5,5,5)));
panel2.add(m_ResultPanel,BorderLayout.CENTER);
panel.add(panel2,BorderLayout.CENTER);
m_InfoPanel=new InfoPanel(m_Parent);
panel=new JPanel(new BorderLayout());
add(panel,BorderLayout.SOUTH);
panel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Info"),BorderFactory.createEmptyBorder(0,5,5,5)));
panel.add(m_InfoPanel,BorderLayout.CENTER);
addConnectionListener(this);
addConnectionListener(m_QueryPanel);
addQueryExecuteListener(this);
addQueryExecuteListener(m_ResultPanel);
addResultChangedListener(this);
addHistoryChangedListener(this);
loadHistory(true);
}
| builds the interface. |
protected PlayerPositionListener(final Player admin){
this.admin=admin;
}
| creates a new PlayerPositionListener. |
public void unlinkAtCommitStop(Value v){
if (unlinkLobMap != null) {
unlinkLobMap.remove(v.toString());
}
}
| Do not unlink this LOB value at commit any longer. |
public int hashCode(){
return parent.hashEntry(getKey(),getValue());
}
| Gets the hashcode of the entry using temporary hard references. <p/> This implementation uses <code>hashEntry</code> on the main map. |
private static boolean overlapsOrTouches(Position gap,int offset,int length){
return gap.getOffset() <= offset + length && offset <= gap.getOffset() + gap.getLength();
}
| Returns <code>true</code> if the given ranges overlap with or touch each other. |
protected Label createDayTitle(int day){
String value=getUIManager().localize("Calendar." + DAYS[day],LABELS[day]);
Label dayh=new Label(value,"CalendarTitle");
dayh.setEndsWith3Points(false);
dayh.setTickerEnabled(false);
return dayh;
}
| This method creates the Day title Component for the Month View |
public static short toShort(ByteString bs){
return bs.asReadOnlyByteBuffer().getShort();
}
| Interpret the bytestring as a short |
private boolean[] extractBits(BitMatrix matrix) throws FormatException {
boolean[] rawbits;
if (ddata.isCompact()) {
if (ddata.getNbLayers() > NB_BITS_COMPACT.length) {
throw FormatException.getFormatInstance();
}
rawbits=new boolean[NB_BITS_COMPACT[ddata.getNbLayers()]];
numCodewords=NB_DATABLOCK_COMPACT[ddata.getNbLayers()];
}
else {
if (ddata.getNbLayers() > NB_BITS.length) {
throw FormatException.getFormatInstance();
}
rawbits=new boolean[NB_BITS[ddata.getNbLayers()]];
numCodewords=NB_DATABLOCK[ddata.getNbLayers()];
}
int layer=ddata.getNbLayers();
int size=matrix.getHeight();
int rawbitsOffset=0;
int matrixOffset=0;
while (layer != 0) {
int flip=0;
for (int i=0; i < 2 * size - 4; i++) {
rawbits[rawbitsOffset + i]=matrix.get(matrixOffset + flip,matrixOffset + i / 2);
rawbits[rawbitsOffset + 2 * size - 4 + i]=matrix.get(matrixOffset + i / 2,matrixOffset + size - 1 - flip);
flip=(flip + 1) % 2;
}
flip=0;
for (int i=2 * size + 1; i > 5; i--) {
rawbits[rawbitsOffset + 4 * size - 8 + (2 * size - i) + 1]=matrix.get(matrixOffset + size - 1 - flip,matrixOffset + i / 2 - 1);
rawbits[rawbitsOffset + 6 * size - 12 + (2 * size - i) + 1]=matrix.get(matrixOffset + i / 2 - 1,matrixOffset + flip);
flip=(flip + 1) % 2;
}
matrixOffset+=2;
rawbitsOffset+=8 * size - 16;
layer--;
size-=4;
}
return rawbits;
}
| Gets the array of bits from an Aztec Code matrix |
public FastBufferedReader(final String bufferSize,final String wordConstituents){
this(Integer.parseInt(bufferSize),new CharOpenHashSet(wordConstituents.toCharArray(),Hash.VERY_FAST_LOAD_FACTOR));
}
| Creates a new fast buffered reader with a given buffer size and a set of additional word constituents, both specified by strings. |
public final void addSuccess(Position pos,Move m,int depth){
int p=pos.getPiece(m.from);
int cnt=depth;
int val=countSuccess[p][m.to] + cnt;
if (val > 1000) {
val/=2;
countFail[p][m.to]/=2;
}
countSuccess[p][m.to]=val;
score[p][m.to]=-1;
}
| Record move as a success. |
protected void test(String problemName){
Problem problem=ProblemFactory.getInstance().getProblem(problemName);
NondominatedPopulation referenceSet=ProblemFactory.getInstance().getReferenceSet(problemName);
NondominatedPopulation approximationSet=generateApproximationSet(problemName,100);
InvertedGenerationalDistance myIndicator=new InvertedGenerationalDistance(problem,referenceSet,2.0);
jmetal.qualityIndicator.InvertedGenerationalDistance theirIndicator=new jmetal.qualityIndicator.InvertedGenerationalDistance();
double actual=myIndicator.evaluate(approximationSet);
double expected=theirIndicator.invertedGenerationalDistance(toArray(approximationSet),toArray(referenceSet),problem.getNumberOfObjectives());
Assert.assertEquals(expected,actual,Settings.EPS);
actual=myIndicator.evaluate(referenceSet);
Assert.assertEquals(0.0,actual,Settings.EPS);
}
| Generates a random approximation set and tests if the inverted generational distance is computed correctly. |
public void backgroundTasks(){
PeerManager peerManager=PeerManager.getInstance(getApplicationContext());
peerManager.tasks();
mBluetoothSpeaker.tasks();
mWifiDirectSpeaker.tasks();
List<Peer> peers=peerManager.getPeers();
if (peers.size() > 0 && readyToConnect()) {
Peer peer=peers.get(mRandom.nextInt(peers.size()));
try {
if (peerManager.thisDeviceSpeaksTo(peer)) {
connectTo(peer);
}
}
catch ( NoSuchAlgorithmException e) {
Log.e(TAG,"No such algorithm for hashing in thisDeviceSpeaksTo!? " + e);
return;
}
catch ( UnsupportedEncodingException e) {
Log.e(TAG,"Unsupported encoding exception in thisDeviceSpeaksTo!?" + e);
return;
}
}
else {
Log.v(TAG,String.format("Not connecting (%d peers, ready to connect is %s)",peers.size(),readyToConnect()));
}
mBackgroundTaskRunCount++;
}
| Method called periodically on a background thread to perform Rangzen's background tasks. |
public void addRole(Role role){
getRoles().add(role);
}
| Adds a role for the user |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.