code
stringlengths
10
174k
nl
stringlengths
3
129k
public static String clientMessagesRegion(GemFireCacheImpl cache,String ePolicy,int capacity,int port,String overFlowDir,boolean isDiskStore){ AttributesFactory factory=getAttribFactoryForClientMessagesRegion(cache,ePolicy,capacity,overFlowDir,isDiskStore); RegionAttributes attr=factory.create(); return createClientMessagesRegion(attr,cache,capacity,port); }
create client subscription
public static Map<URI,String> mapNames(Collection<? extends NamedRelatedResourceRep> references){ Map<URI,String> map=new LinkedHashMap<URI,String>(); for ( NamedRelatedResourceRep ref : references) { map.put(ref.getId(),ref.getName()); } return map; }
Maps a collection of references by their ID to their name.
protected int calculateTouchCommandGridColumns(Container grid){ int count=grid.getComponentCount(); int maxWidth=10; for (int iter=0; iter < count; iter++) { Component c=grid.getComponentAt(iter); Style s=c.getUnselectedStyle(); maxWidth=Math.max(maxWidth,c.getPreferredW() + s.getMargin(false,LEFT) + s.getMargin(false,RIGHT)); } return Math.max(2,Display.getInstance().getDisplayWidth() / maxWidth); }
Calculates the amount of columns to give to the touch commands within the grid
public char nextClean() throws JSONException { for (; ; ) { char c=this.next(); if (c == 0 || c > ' ') { return c; } } }
Get the next char in the string, skipping whitespace.
public void onDestroy(){ destroyed=true; inactivityTimer.cancel(); }
Call from Activity#onDestroy().
@Override public void accept(T model){ requireNonNull(model); if (!hasMethod(model,EQUALS,1)) { acceptEquals(model); } if (!hasMethod(model,HASHCODE,0)) { acceptHashcode(model); } }
Adds an <code>equals()</code> and a <code>hashCode()</code> method to the specified model. <p> If one of the methods already exists, it will not be overwritten.
@Override public String toString(){ final SentenceBuilder builder=new SentenceBuilder(); for ( final Expression w : expressions) { if (w.getType() != null) { if (!isIgnorable(w)) { builder.append(w.getNormalizedWithTypeString()); } } else { builder.append(w.getOriginal()); } if (w.getBreakFlag()) { builder.append(','); } } appendPunctation(builder); String ret=builder.toString(); ExpressionMatcher matcher=getMatcher(); if (matcher != null) { ret=matcher.toString() + ExpressionMatcher.PM_SEPARATOR + ret; } return ret; }
Return the full sentence as lower case string including type specifiers.
public boolean disconnectClient() throws MqttException { synchronized (connLock) { connLockNotified=true; connLock.notify(); } try { wmqttClient.disconnect(); } catch ( MqttPersistenceException mqpe) { } connected=false; return true; }
disconnectClient stops any connectionLost processing that is happening and disconnects the TCP/IP socket connection.
private Object invokeOperationOnTargetMBean(final ObjectName namePattern,final String pidAttribute,final String methodName,final String[] attributes,final Object[] values) throws ConnectionFailedException, IOException, MBeanInvocationFailedException { ObjectName objectName=namePattern; connect(); try { final QueryExp constraint=buildQueryExp(pidAttribute,attributes,values); final Set<ObjectName> mbeanNames=this.server.queryNames(namePattern,constraint); if (mbeanNames.isEmpty()) { throw new MBeanInvocationFailedException("Failed to find mbean matching '" + namePattern + "' with attribute '"+ pidAttribute+ "' of value '"+ this.pid+ "'"); } if (mbeanNames.size() > 1) { throw new MBeanInvocationFailedException("Found more than one mbean matching '" + namePattern + "' with attribute '"+ pidAttribute+ "' of value '"+ this.pid+ "'"); } objectName=mbeanNames.iterator().next(); return invoke(objectName,methodName); } catch ( InstanceNotFoundException e) { throw new MBeanInvocationFailedException("Failed to invoke " + methodName + " on "+ objectName,e); } catch ( MBeanException e) { throw new MBeanInvocationFailedException("Failed to invoke " + methodName + " on "+ objectName,e); } catch ( ReflectionException e) { throw new MBeanInvocationFailedException("Failed to invoke " + methodName + " on "+ objectName,e); } finally { disconnect(); } }
Connects to the process and use its MBean to stop it.
public static boolean isLowercaseAlpha(char c){ return (c >= 'a') && (c <= 'z'); }
Returns <code>true</code> if specified character is lowercase ASCII. If user uses only ASCIIs, it is much much faster.
private int countMark(TicTacToeBoard board,int c,int r,int dc,int dr,int sz,char m){ int ct=0; for (int i=0; i < sz; i++, c+=dc, r+=dr) { if (board.isClear(c,r)) { continue; } if (board.get(c,r) != m) { return -1; } ct++; } return ct; }
Starting from (c,r) count three in direction (dc,dr) and return the number of cells that contain mark 'm' without containing opponent marks (empty cells are skipped). If, however, a non-empty cell is discovered whose mark is not 'm', then -1 is returned -1.
@Override public String toString(){ return "[" + xmin + ", "+ xmax+ "] x ["+ ymin+ ", "+ ymax+ "]"; }
Returns a string representation of this rectangle.
private void parserParameters(List<MySqlParameter> parameters){ for (; ; ) { MySqlParameter parameter=new MySqlParameter(); if (lexer.token() == Token.CURSOR) { lexer.nextToken(); parameter.setName(this.exprParser.name()); accept(Token.IS); SQLSelect select=this.createSQLSelectParser().select(); SQLDataTypeImpl dataType=new SQLDataTypeImpl(); dataType.setName("CURSOR"); parameter.setDataType(dataType); parameter.setDefaultValue(new SQLQueryExpr(select)); } else if (lexer.token() == Token.IN || lexer.token() == Token.OUT || lexer.token() == Token.INOUT) { if (lexer.token() == Token.IN) { parameter.setParamType(ParameterType.IN); } else if (lexer.token() == Token.OUT) { parameter.setParamType(ParameterType.OUT); } else if (lexer.token() == Token.INOUT) { parameter.setParamType(ParameterType.INOUT); } lexer.nextToken(); parameter.setName(this.exprParser.name()); parameter.setDataType(this.exprParser.parseDataType()); } else { parameter.setParamType(ParameterType.DEFAULT); parameter.setName(this.exprParser.name()); parameter.setDataType(this.exprParser.parseDataType()); if (lexer.token() == Token.COLONEQ) { lexer.nextToken(); parameter.setDefaultValue(this.exprParser.expr()); } } parameters.add(parameter); if (lexer.token() == Token.COMMA || lexer.token() == Token.SEMI) { lexer.nextToken(); } if (lexer.token() != Token.BEGIN && lexer.token() != Token.RPAREN) { continue; } break; } }
parse create procedure parameters
public static final double parseTime(final String time,final char separator){ if (time == null || time.length() == 0 || time.equals("undefined")) { return Time.UNDEFINED_TIME; } boolean isNegative=(time.charAt(0) == '-'); String[] strings=(isNegative ? StringUtils.explode(time.substring(1),separator) : StringUtils.explode(time,separator)); double seconds=0; if (strings.length == 1) { seconds=Math.abs(Double.parseDouble(strings[0])); } else if (strings.length == 2) { int h=Integer.parseInt(strings[0]); int m=Integer.parseInt(strings[1]); if ((m < 0) || (m > 59)) { throw new IllegalArgumentException("minutes are out of range in " + time); } seconds=Math.abs(h) * 3600 + m * 60; } else if (strings.length == 3) { int h=Integer.parseInt(strings[0]); int m=Integer.parseInt(strings[1]); double s=Double.parseDouble(strings[2]); if ((m < 0) || (m > 59)) { throw new IllegalArgumentException("minutes are out of range in " + time); } if ((s < 0) || (s >= 60)) { throw new IllegalArgumentException("seconds are out of range in " + time); } seconds=Math.abs(h) * 3600 + m * 60 + s; } else { throw new IllegalArgumentException("time format is not valid in " + time); } if (isNegative) { seconds=-seconds; } return seconds; }
Parses the given string for a textual representation for time and returns the time value in seconds past midnight. The following formats are recognized: HH:mm:ss, HH:mm, ssss.
public void disposeTimer(){ started=false; if (timer == null) return; if (actionListeners != null) { actionListeners.clear(); } if (stopListeners != null) { stopListeners.clear(); } timer.stop(); timer=null; }
Remove all listeners and stop timer
@Override public Enumeration<String> enumerateMeasures(){ Vector<String> newVector=new Vector<String>(1); newVector.addElement("measureOutOfBagError"); return newVector.elements(); }
Returns an enumeration of the additional measure names.
public static double calculateTestStatistic(MeanVariance mv1,MeanVariance mv2){ final double delta=mv1.getMean() - mv2.getMean(); final double relvar1=mv1.getSampleVariance() / mv1.getCount(); final double relvar2=mv2.getSampleVariance() / mv2.getCount(); return delta / Math.sqrt(relvar1 + relvar2); }
Calculate the statistic of Welch's t test using statistical moments of the provided data samples
public void replaceAndWait(final Component current,final Component next,final Transition t,boolean dropEvents){ replaceComponents(current,next,t,true,dropEvents,null,0,0,true); }
This method replaces the current Component with the next Component. Current Component must be contained in this Container. This method returns when transition has finished.
public Object jjtAccept(SyntaxTreeBuilderVisitor visitor,Object data) throws VisitorException { return visitor.visit(this,data); }
Accept the visitor.
public PanHandlerFX(String id){ this(id,false,false,false,false); }
Creates a new instance that requires no modifier keys.
@Override public String toString(){ MoreObjects.ToStringHelper s=MoreObjects.toStringHelper(this); if (initialCapacity != UNSET_INT) { s.add("initialCapacity",initialCapacity); } if (concurrencyLevel != UNSET_INT) { s.add("concurrencyLevel",concurrencyLevel); } if (maximumSize != UNSET_INT) { s.add("maximumSize",maximumSize); } if (maximumWeight != UNSET_INT) { s.add("maximumWeight",maximumWeight); } if (expireAfterWriteNanos != UNSET_INT) { s.add("expireAfterWrite",expireAfterWriteNanos + "ns"); } if (expireAfterAccessNanos != UNSET_INT) { s.add("expireAfterAccess",expireAfterAccessNanos + "ns"); } if (keyStrength != null) { s.add("keyStrength",Ascii.toLowerCase(keyStrength.toString())); } if (valueStrength != null) { s.add("valueStrength",Ascii.toLowerCase(valueStrength.toString())); } if (keyEquivalence != null) { s.addValue("keyEquivalence"); } if (valueEquivalence != null) { s.addValue("valueEquivalence"); } if (removalListener != null) { s.addValue("removalListener"); } return s.toString(); }
Returns a string representation for this CacheBuilder instance. The exact form of the returned string is not specified.
@Override public Namespace createNamespace(Namespace namespace){ requireNotDisposed(); requireArgument(namespace != null,"null namespace cannot be created."); if (!_validateQualifier(namespace.getQualifier())) { throw new SystemException(new IllegalArgumentException("Illegal characters found while generating namespace. Cannot generate a namespace with this qualifier.")); } if (Namespace.findByQualifier(emf.get(),namespace.getQualifier()) != null) { throw new SystemException(new IllegalArgumentException("Namespace already exists. Please try a different namespace.")); } namespace=updateNamespace(namespace); _logger.debug("Generated namespace {}.",namespace); return namespace; }
Creates a new namespace.
@SuppressWarnings({"unchecked"}) private void inheritValues(Values fromParent){ Object[] table=this.table; for (int i=table.length - 2; i >= 0; i-=2) { Object k=table[i]; if (k == null || k == TOMBSTONE) { continue; } Reference<InheritableThreadLocal<?>> reference=(Reference<InheritableThreadLocal<?>>)k; InheritableThreadLocal key=reference.get(); if (key != null) { table[i + 1]=key.childValue(fromParent.table[i + 1]); } else { table[i]=TOMBSTONE; table[i + 1]=null; fromParent.table[i]=TOMBSTONE; fromParent.table[i + 1]=null; tombstones++; fromParent.tombstones++; size--; fromParent.size--; } } }
Inherits values from a parent thread.
public void writeAll(Iterable<String[]> allLines,boolean applyQuotesToAll){ StringBuilder sb=new StringBuilder(INITIAL_STRING_SIZE); try { for ( String[] line : allLines) { writeNext(line,applyQuotesToAll,sb); sb.setLength(0); } } catch ( IOException e) { exception=e; } }
Writes iterable to a CSV file. The list is assumed to be a String[]
public boolean isMatch(SearchQuery.Criterion criterion,MailboxMessage message,final Collection<MessageUid> recentMessageUids) throws MailboxException { final boolean result; if (criterion instanceof SearchQuery.InternalDateCriterion) { result=matches((SearchQuery.InternalDateCriterion)criterion,message); } else if (criterion instanceof SearchQuery.SizeCriterion) { result=matches((SearchQuery.SizeCriterion)criterion,message); } else if (criterion instanceof SearchQuery.HeaderCriterion) { try { result=matches((SearchQuery.HeaderCriterion)criterion,message); } catch ( IOException e) { throw new MailboxException("Unable to search header",e); } } else if (criterion instanceof SearchQuery.UidCriterion) { result=matches((SearchQuery.UidCriterion)criterion,message); } else if (criterion instanceof SearchQuery.FlagCriterion) { result=matches((SearchQuery.FlagCriterion)criterion,message,recentMessageUids); } else if (criterion instanceof SearchQuery.CustomFlagCriterion) { result=matches((SearchQuery.CustomFlagCriterion)criterion,message,recentMessageUids); } else if (criterion instanceof SearchQuery.TextCriterion) { result=matches((SearchQuery.TextCriterion)criterion,message); } else if (criterion instanceof SearchQuery.AllCriterion) { result=true; } else if (criterion instanceof SearchQuery.ConjunctionCriterion) { result=matches((SearchQuery.ConjunctionCriterion)criterion,message,recentMessageUids); } else if (criterion instanceof SearchQuery.ModSeqCriterion) { result=matches((SearchQuery.ModSeqCriterion)criterion,message); } else { throw new UnsupportedSearchException(); } return result; }
Does the row match the given criterion?
public ConcurrentIndexMap(Object[] array){ this.array=array; }
Creates a new IndexMap with the given underlying array. Any change to this array is reflected in the map and vice-versa.
public int size(){ return size; }
Returns the number of key-value mappings in this map.
public boolean contains(long key){ if (key == FREE_KEY) { return true; } int ptr=(int)((Tools.phiMix(key) & m_mask)); long e=m_data[ptr]; if (e == FREE_KEY) { return false; } if (e == key) { return true; } while (true) { ptr=(int)((ptr + 1) & m_mask); e=m_data[ptr]; if (e == FREE_KEY) { return false; } if (e == key) { return true; } } }
Return true if the map contains an object with the specified key
private void buildTableHelper(String fileName) throws Exception { PennTreebankPOSReader reader=new PennTreebankPOSReader(this.corpusName); reader.readFile(fileName); List<TextAnnotation> tas=reader.getTextAnnotations(); for ( TextAnnotation ta : tas) { for (int tokenId=0; tokenId < ta.size(); tokenId++) { String form=ta.getToken(tokenId); String tag=((SpanLabelView)ta.getView(ViewNames.POS)).getLabel(tokenId); if (form.length() >= 5) { boolean allLetters=true; for (int i=form.length() - 3; i < form.length() && allLetters; ++i) allLetters=Character.isLetter(form.charAt(i)); if (allLetters) { HashMap<String,TreeMap<String,Integer>> t=null; if (WordHelpers.isCapitalized(ta,tokenId)) { int headOfSentence=ta.getSentence(ta.getSentenceId(tokenId)).getStartSpan(); if (tokenId == headOfSentence) t=firstCapitalized; else t=notFirstCapitalized; } else { if (form.contains("-")) return; t=table; } form=form.toLowerCase(); count(t,form.substring(form.length() - 3),tag); if (form.length() >= 6 && Character.isLetter(form.charAt(form.length() - 4))) count(t,form.substring(form.length() - 4),tag); } } } } }
A table is built from a given source corpus file by counting the number of times that each suffix-POS association in a source corpus.
public static void apply(int gravity,int w,int h,Rect container,int xAdj,int yAdj,Rect outRect){ switch (gravity & ((AXIS_PULL_BEFORE | AXIS_PULL_AFTER) << AXIS_X_SHIFT)) { case 0: outRect.left=container.left + ((container.right - container.left - w) / 2) + xAdj; outRect.right=outRect.left + w; if ((gravity & (AXIS_CLIP << AXIS_X_SHIFT)) == (AXIS_CLIP << AXIS_X_SHIFT)) { if (outRect.left < container.left) { outRect.left=container.left; } if (outRect.right > container.right) { outRect.right=container.right; } } break; case AXIS_PULL_BEFORE << AXIS_X_SHIFT: outRect.left=container.left + xAdj; outRect.right=outRect.left + w; if ((gravity & (AXIS_CLIP << AXIS_X_SHIFT)) == (AXIS_CLIP << AXIS_X_SHIFT)) { if (outRect.right > container.right) { outRect.right=container.right; } } break; case AXIS_PULL_AFTER << AXIS_X_SHIFT: outRect.right=container.right - xAdj; outRect.left=outRect.right - w; if ((gravity & (AXIS_CLIP << AXIS_X_SHIFT)) == (AXIS_CLIP << AXIS_X_SHIFT)) { if (outRect.left < container.left) { outRect.left=container.left; } } break; default : outRect.left=container.left + xAdj; outRect.right=container.right + xAdj; break; } switch (gravity & ((AXIS_PULL_BEFORE | AXIS_PULL_AFTER) << AXIS_Y_SHIFT)) { case 0: outRect.top=container.top + ((container.bottom - container.top - h) / 2) + yAdj; outRect.bottom=outRect.top + h; if ((gravity & (AXIS_CLIP << AXIS_Y_SHIFT)) == (AXIS_CLIP << AXIS_Y_SHIFT)) { if (outRect.top < container.top) { outRect.top=container.top; } if (outRect.bottom > container.bottom) { outRect.bottom=container.bottom; } } break; case AXIS_PULL_BEFORE << AXIS_Y_SHIFT: outRect.top=container.top + yAdj; outRect.bottom=outRect.top + h; if ((gravity & (AXIS_CLIP << AXIS_Y_SHIFT)) == (AXIS_CLIP << AXIS_Y_SHIFT)) { if (outRect.bottom > container.bottom) { outRect.bottom=container.bottom; } } break; case AXIS_PULL_AFTER << AXIS_Y_SHIFT: outRect.bottom=container.bottom - yAdj; outRect.top=outRect.bottom - h; if ((gravity & (AXIS_CLIP << AXIS_Y_SHIFT)) == (AXIS_CLIP << AXIS_Y_SHIFT)) { if (outRect.top < container.top) { outRect.top=container.top; } } break; default : outRect.top=container.top + yAdj; outRect.bottom=container.bottom + yAdj; break; } }
Apply a gravity constant to an object.
public byte[] loadContent(final Request request,final CacheStrategy cacheStrategy,BlacklistType blacklistType,final ClientIdentification.Agent agent) throws IOException { final Response entry=load(request,cacheStrategy,blacklistType,agent); if (entry == null) return null; return entry.getContent(); }
load the url as byte[] content from the web or the cache
public CreateSnapshotRequest repository(String repository){ this.repository=repository; return this; }
Sets repository name
public QueryBuilder where(String sqlCondition,String... args){ if (sqlCondition != null && !sqlCondition.isEmpty()) { mCondition+=" and (" + sqlCondition + ")"; mArgs=args == null ? mArgs : ObjectArrays.concat(mArgs,args,String.class); } return this; }
Adds a SQL condition to the WHERE clause (joined using AND).
public IXMLElement createElement(String fullName,String namespace){ return new XMLElement(fullName,namespace); }
Creates an empty element.
public Transform match(Class type) throws Exception { return null; }
This method is used to return a null value for the transform. Returning a null value allows the normal resolution of the stock transforms to be used when no matcher is specified.
protected StringLiteralImpl(){ super(); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public Builder addMatch3Method(Match3MethodSpec match3MethodSpec){ match3Methods.addAll(new Match3MethodPermutationBuilder(matchType,match3MethodSpec,MAX_ARITY).build()); return this; }
Adds a 3-arity match method.
public static void main(String[] args) throws Exception { if (5 != args.length) { System.err.println(ThrottlingConfigGenerator.class.getCanonicalName() + " PARSE_URL WARP_ENDPOINT TOKEN CELL DDP_SPIKE"); } genConfiguration(args[0],args[1],args[2],args[3],args[4]); }
ThrottlingConfigGenerator PARSE_URL WARP_ENDPOINT TOKEN CELL DDP_SPIKE DDP_SPIKE indicates on which time interval we allow the DDP to be pushed. It is expressed in seconds.
private void initCardPanel(){ if (dictionaryType.getSelectedItem().equals("Vector")) { cardPanel.removeAll(); cardPanel.add(vectorPanel); } else { cardPanel.removeAll(); cardPanel.add(scalarPanel); } cardPanel.revalidate(); cardPanel.repaint(); pack(); }
Set the current "card".
boolean hasHistory(){ return false; }
Has History (false) To be overwritten by concrete classes
public static void w(String tag,String s,Object... args){ if (LDJSLOG.WARN >= LOGLEVEL) Log.w(tag,String.format(s,args)); }
Warning log message with printf formatting.
public static void render(GetDocumentResponse aResponse,BratAnnotatorModel aBModel,JCas aJCas,AnnotationService aAnnotationService){ aResponse.setRtlMode(ScriptDirection.RTL.equals(aBModel.getScriptDirection())); SpanAdapter.renderTokenAndSentence(aJCas,aResponse,aBModel); Map<String[],Queue<String>> colorQueues=new HashMap<>(); for ( AnnotationLayer layer : aBModel.getAnnotationLayers()) { if (layer.getName().equals(Token.class.getName()) || layer.getName().equals(Sentence.class.getName()) || (layer.getType().equals(CHAIN_TYPE) && (aBModel.getMode().equals(Mode.AUTOMATION) || aBModel.getMode().equals(Mode.CORRECTION) || aBModel.getMode().equals(Mode.CURATION)))|| !layer.isEnabled()) { continue; } ColoringStrategy coloringStrategy=ColoringStrategy.getBestStrategy(aAnnotationService,layer,aBModel.getPreferences(),colorQueues); List<AnnotationFeature> features=aAnnotationService.listAnnotationFeature(layer); List<AnnotationFeature> invisibleFeatures=new ArrayList<AnnotationFeature>(); for ( AnnotationFeature feature : features) { if (!feature.isVisible()) { invisibleFeatures.add(feature); } } features.removeAll(invisibleFeatures); TypeAdapter adapter=getAdapter(aAnnotationService,layer); adapter.render(aJCas,features,aResponse,aBModel,coloringStrategy); } }
wrap JSON responses to BRAT visualizer
public void incrementRow(Assignment head,double prob){ addRow(head,table.getOrDefault(head,0.0) + prob); }
Increments the probability specified in the table for the given head assignment. If none exists, simply assign the probability.
public double measureTreeSize(){ return m_NumNodes; }
Returns the size of the tree. (number of internal nodes + number of leaves)
public Map<Integer,Integer> buildCharStringTable(){ final Map<Integer,Integer> glyfValues=new HashMap<Integer,Integer>(); if (hasFormat4) { final ArrayList<Integer> list4=new ArrayList<Integer>(); for (int z=0; z < segCount; z++) { final int total=endCode[z] - startCode[z] + 1; for (int q=0; q < total; q++) { list4.add(startCode[z] + q); } } for ( final Integer i : list4) { glyfValues.put(i,getFormat4Value(i,0)); } } else if (hasFormat6) { for (int z=0; z < entryCount; z++) { glyfValues.put(firstCode + z,f6glyphIdArray[firstCode + z]); } } else { for (int z=0; z < glyphToIndex.length; z++) { if (glyphToIndex[z] > 0) { glyfValues.put(glyphToIndex[z],z); } } } return glyfValues; }
turn type 0 table into a list of glyph
void trackMotionScroll(float deltaAngle){ if (getChildCount() == 0) { return; } for (int i=0; i < getAdapter().getCount(); i++) { CarouselItemImage child=(CarouselItemImage)getAdapter().getView(i,null,null); float angle=child.getCurrentAngle(); angle+=deltaAngle; while (angle > 360.0f) angle-=360.0f; while (angle < 0.0f) angle+=360.0f; child.setCurrentAngle(angle); Calculate3DPosition(child,getWidth(),angle); } mRecycler.clear(); invalidate(); }
Tracks a motion scroll. In reality, this is used to do just about any movement to items (touch scroll, arrow-key scroll, set an item as selected).
public static void out(final String _debug_msg,final Throwable _exception){ if ((_exception instanceof ConnectException) && _exception.getMessage().startsWith("No route to host")) { diagLoggerLog(_exception.toString()); return; } if ((_exception instanceof UnknownHostException)) { diagLoggerLog(_exception.toString()); return; } String header="DEBUG::"; header=header + new Date(SystemTime.getCurrentTime()).toString() + "::"; String className; String methodName; int lineNumber; String trace_trace_tail=null; try { throw new Exception(); } catch ( Exception e) { StackTraceElement[] st=e.getStackTrace(); StackTraceElement first_line=st[2]; className=first_line.getClassName() + "::"; methodName=first_line.getMethodName() + "::"; lineNumber=first_line.getLineNumber(); trace_trace_tail=getCompressedStackTrace(e,3,200,false); } diagLoggerLogAndOut(header + className + (methodName)+ lineNumber+ ":",true); if (_debug_msg.length() > 0) { diagLoggerLogAndOut(" " + _debug_msg,true); } if (trace_trace_tail != null) { diagLoggerLogAndOut(" " + trace_trace_tail,true); } if (_exception != null) { diagLoggerLogAndOut(_exception); } }
Prints out the given debug message to System.out, prefixed by the calling class name, method and line number, appending the stacktrace of the given exception.
public boolean addAllUnique(Collection<Playlist> ps){ boolean didChange=false; for ( Playlist p : ps) { if (p != null && !mPlaylists.contains(p)) { mPlaylists.add(p); didChange=true; } } if (didChange) { notifyDataSetChanged(); } return didChange; }
Add all the elements into the adapter if they're not already there
@Override public void eUnset(int featureID){ switch (featureID) { case UmplePackage.KEY___KEY_ID_1: setKeyId_1(KEY_ID_1_EDEFAULT); return; case UmplePackage.KEY___ANONYMOUS_KEY_11: getAnonymous_key_1_1().clear(); return; } super.eUnset(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public Matrix4d scaleAround(double factor,double ox,double oy,double oz){ return scaleAround(factor,factor,factor,ox,oy,oz,this); }
Apply scaling to this matrix by scaling all three base axes by the given <code>factor</code> while using <tt>(ox, oy, oz)</tt> as the scaling origin. <p> If <code>M</code> is <code>this</code> matrix and <code>S</code> the scaling matrix, then the new matrix will be <code>M * S</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * S * v</code>, the scaling will be applied first! <p> This method is equivalent to calling: <tt>translate(ox, oy, oz).scale(factor).translate(-ox, -oy, -oz)</tt>
@Override public void eUnset(int featureID){ switch (featureID) { case TypesPackage.TSTRUCT_METHOD__DEFINED_MEMBER: setDefinedMember((TStructMember)null); return; } super.eUnset(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public static void dropAllTables(SQLiteDatabase db,boolean ifExists){ GroupAudioDao.dropTable(db,ifExists); }
Drops underlying database table using DAOs.
public void startButtonChange(ActionEvent e){ firePropertyChangeEvent(new PropertyChangeEvent(this,"start",engine_started,start_button.isSelected())); engine_started=start_button.isSelected(); }
Respond to a start button press
public Shape apply(E e){ Shape edgeShape=getLoopOrNull(e); if (edgeShape != null) { return edgeShape; } int index=getIndex(e,edgeIndexFunction); float controlY=control_offset_increment + control_offset_increment * index; BENT_LINE.reset(); BENT_LINE.moveTo(0.0f,0.0f); BENT_LINE.lineTo(0.5f,controlY); BENT_LINE.lineTo(1.0f,1.0f); return BENT_LINE; }
Get the shape for this edge, returning either the shared instance or, in the case of self-loop edges, the Loop shared instance.
public void testSetF16(){ boolean f16=false; AbstractThrottle instance=new AbstractThrottleImpl(); instance.setF16(f16); jmri.util.JUnitAppender.assertErrorMessage("Can't send F13-F20 since no command station defined"); }
Test of setF16 method, of class AbstractThrottle.
public void translateRegionInWindowToScreen(Region transparentRegion){ transparentRegion.scale(applicationScale); }
Translate the region in window to screen.
public String distanceWeightingTipText(){ return "Gets the distance weighting method used."; }
Returns the tip text for this property.
public synchronized void clearSession(Context context,MXSession session,Boolean clearCredentials){ if (clearCredentials) { mLoginStorage.removeCredentials(session.getHomeserverConfig()); } session.getDataHandler().removeListener(mLiveEventListener); session.mCallsManager.removeListener(mCallsManagerListener); session.clear(context); synchronized (LOG_TAG) { mMXSessions.remove(session); } }
Clear a session.
public void testDuplexStaticRemoteBrokerHasNoConsumer() throws Exception { boolean dynamicOnly=true; int networkTTL=2; boolean conduit=true; bridgeBrokers("BrokerA","BrokerB",dynamicOnly,networkTTL,conduit); bridgeBrokers("BrokerB","BrokerA",dynamicOnly,networkTTL,conduit); startAllBrokers(); Destination dest=createDestination("TEST.FOO",false); MessageConsumer clientA=createConsumer("BrokerA",dest); Thread.sleep(2 * 1000); int messageCount=2000; sendMessages("BrokerA",dest,messageCount); MessageIdList msgsA=getConsumerMessages("BrokerA",clientA); msgsA.waitForMessagesToArrive(messageCount); assertEquals(messageCount,msgsA.getMessageCount()); }
BrokerA -> BrokerB && BrokerB -> BrokerA
public int count(){ return m_docs.count(); }
Devuelve el numero de documentos de la lista
private boolean shouldScanFile(){ return (mediaScanned == 0) && (getDestination() == DownloadsDestination.DESTINATION_EXTERNAL || getDestination() == DownloadsDestination.DESTINATION_FILE_URI || getDestination() == DownloadsDestination.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD) && DownloadStatus.isSuccess(getStatus())&& scannable; }
Returns whether a file should be scanned
public long tryConvertToWriteLock(long stamp){ long a=stamp & ABITS, m, s, next; while (((s=state) & SBITS) == (stamp & SBITS)) { if ((m=s & ABITS) == 0L) { if (a != 0L) break; if (U.compareAndSwapLong(this,STATE,s,next=s + WBIT)) return next; } else if (m == WBIT) { if (a != m) break; return stamp; } else if (m == RUNIT && a != 0L) { if (U.compareAndSwapLong(this,STATE,s,next=s - RUNIT + WBIT)) return next; } else break; } return 0L; }
If the lock state matches the given stamp, atomically performs one of the following actions. If the stamp represents holding a write lock, returns it. Or, if a read lock, if the write lock is available, releases the read lock and returns a write stamp. Or, if an optimistic read, returns a write stamp only if immediately available. This method returns zero in all other cases.
public UniformFilterEditor(){ super(); initComponents(); layoutComponents(); }
Create a new uniform filter editor.
public FXMessageDialog(final Stage parent,final Parent group){ this(parent); content.setCenter(group); }
MessageDialog with custom center node
public CallableParameterMetaData(MariaDbConnection con,String database,String name,boolean isFunction){ this.params=null; this.con=con; if (database != null) { this.database=database.replace("`",""); } else { this.database=null; } this.name=name.replace("`",""); this.isFunction=isFunction; }
Retrieve Callable metaData.
@Override public OutputStream openOutputStream() throws IOException { return bos; }
Will provide the compiler with an output stream that leads to our byte array. This way the compiler will write everything into the byte array that we will instantiate later
public boolean showOverflowMenu(){ if (mReserveOverflow && !isOverflowMenuShowing() && mMenu != null && mMenuView != null && mPostedOpenRunnable == null && !mMenu.getNonActionItems().isEmpty()) { OverflowPopup popup=new OverflowPopup(mContext,mMenu,mOverflowButton,true); mPostedOpenRunnable=new OpenOverflowRunnable(popup); ((View)mMenuView).post(mPostedOpenRunnable); super.onSubMenuSelected(null); return true; } return false; }
Display the overflow menu if one is present.
public EntityView(Node graphics){ addNode(graphics); }
Constructs a view with given graphics content.
public static void restoreHardwareExceptionState(AbstractRegisters registers){ if (VM.VerifyAssertions) VM._assert(VM.NOT_REACHED); }
Resume execution with specified thread exception state. <p> Restores virtually all registers (details vary by architecture). But, the following are _NOT_ restored <ul> <li>JTOC_POINTER <li>THREAD_REGISTER </ul> does not return (execution resumes at new IP)
public static double pointToAngle(Rectangle2D.Double r,Point2D.Double p){ double px=p.x - (r.x + r.width / 2); double py=p.y - (r.y + r.height / 2); return atan2(py * r.width,px * r.height); }
Gets the angle of a point relative to a rectangle.
public Builder withErrorCode(String errorCode){ this.errorCode=errorCode; return this; }
Add an error code.
public boolean matches(Sign sign){ return sign.getLine(0).equals("Door [" + id + "]"); }
Checks if a given sign corresponds to this door
private static final boolean nowAllSet(int before,int after,int mask){ return ((before & mask) != mask) && ((after & mask) == mask); }
Returns whether or not the bits in the mask have changed to all set.
@SuppressLint("NewApi") private void loadGifUsingTempFile(Subscriber<? super GifDrawableLoader.DownloadStatus> subscriber,Response response) throws IOException { File temporary=new File(fileCache,"tmp" + identityHashCode(subscriber) + ".gif"); logger.info("storing data into temporary file"); try (RandomAccessFile storage=new RandomAccessFile(temporary,"rw")){ temporary.delete(); long lastStatusTime=System.currentTimeMillis(); float contentLength=(float)response.body().contentLength(); try (InputStream stream=response.body().byteStream()){ int length, count=0; byte[] buffer=new byte[16 * 1024]; while ((length=stream.read(buffer)) >= 0) { storage.write(buffer,0,length); count+=length; if (subscriber.isUnsubscribed()) { logger.info("Stopped because the subscriber unsubscribed"); return; } long now=System.currentTimeMillis(); if (now - lastStatusTime > 250) { subscriber.onNext(new DownloadStatus(count / contentLength)); lastStatusTime=now; } } } if (subscriber.isUnsubscribed()) return; try { GifDrawable drawable=new GifDrawable(storage.getFD()); subscriber.onNext(new DownloadStatus(drawable)); subscriber.onCompleted(); } catch ( Throwable error) { subscriber.onError(error); } } }
Loads the data of the gif into a temporary file. The method then loads the gif from this temporary file. The temporary file is removed after loading the gif (or on failure).
@Deprecated public AbstractXmlDriver(final XmlFriendlyReplacer replacer){ this((NameCoder)replacer); }
Creates a AbstractXmlFriendlyDriver with custom XmlFriendlyReplacer
private static void compute(StoredIntervalsNode<?> node,int q,Set<IInterval> F){ int left, right; if (node == null || q < (left=node.getLeft()) || q > (right=node.getRight())) { return; } F.addAll(node.intervals()); int mid=(left + right) / 2; if (q < mid) { compute((StoredIntervalsNode<?>)node.getLeftSon(),q,F); } else if (q >= mid) { compute((StoredIntervalsNode<?>)node.getRightSon(),q,F); } }
Helper method for compute. <p> Naturally divides the tree even though ranges of the interior nodes may overlap. We rely on the 'midpoint' of the node to determine whether to search left or right.
private void markClosed(boolean connBroken){ if (!closed) { closed=true; this.connBroken=connBroken; delegate.hadoop().removeEventListener(delegate); } }
Marks stream as closed.
public static final boolean anyNull(IonValue value){ return (value == null || value.isNullValue()); }
Determines whether a value is Java null, or any Ion null.
public static String date(){ return year() + ""; }
Method date
@Override public boolean shouldNotBeLogged(){ return true; }
Api for the subclasses to decide if this exception should be treated as a bug and hence to be get logged or not in the service layer just before AIDL connection to client.
public final void loadStream(final InputStream ins,String strStreamName) throws IOException { try { Load1.load(ins,strStreamName,this); } catch ( ClassNotFoundException ex) { throw new JIPTypeException(JIPTypeException.LIBRARY,Atom.createAtom(strStreamName)); } }
Loads a stream. The stream must contain a valid JIProlog compiled code If in the stream there are some no multifile predicates already consulted/loaded in another file the interpreter raises an exception.<br>
public void print(String text){ String[] lines=text.split("\n"); for ( String line : lines) { view.print(line.isEmpty() ? " " : line); } performPostOutputActions(); }
Print text on console.
public void delete() throws IOException { close(); Util.deleteContents(directory); }
Closes the cache and deletes all of its stored values. This will delete all files in the cache directory including files that weren't created by the cache.
private void removeListeners(AccessibleContext ac){ if (ac != null) { AccessibleStateSet states=ac.getAccessibleStateSet(); if (!states.contains(AccessibleState.TRANSIENT)) { ac.removePropertyChangeListener(this); if (states.contains(_AccessibleState.MANAGES_DESCENDANTS)) { return; } AccessibleRole role=ac.getAccessibleRole(); if (role == AccessibleRole.LIST || role == AccessibleRole.TABLE || role == AccessibleRole.TREE) { return; } int count=ac.getAccessibleChildrenCount(); for (int i=0; i < count; i++) { Accessible child=ac.getAccessibleChild(i); if (child != null) { removeListeners(child); } } } } }
Removes PropertyChange listeners for the given AccessibleContext object, it's children (so long as the object isn't of TRANSIENT state).
public Editor edit() throws IOException { return DiskLruCache.this.edit(key,sequenceNumber); }
Returns an editor for this snapshot's entry, or null if either the entry has changed since this snapshot was created or if another edit is in progress.
public int size(){ if (mGarbage) { gc(); } return mSize; }
Returns the number of key-value mappings that this SparseArray currently stores.
public void endVisit(MethodRef node){ }
End of visit the given type-specific AST node. <p> The default implementation does nothing. Subclasses may reimplement. </p>
public void reconnectFailedConnection(SearchFilter searchFilter) throws QueryException { if (!searchFilter.isInitialConnection() && (isExplicitClosed() || (searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail())) { return; } if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); if ((searchFilter.isFineIfFoundOnlyMaster() && !isMasterHostFail()) || searchFilter.isFineIfFoundOnlySlave() && !isSecondaryHostFail()) { return; } } catch ( ReconnectDuringTransactionException e) { return; } } currentConnectionAttempts.incrementAndGet(); resetOldsBlackListHosts(); List<HostAddress> loopAddress=new LinkedList<>(urlParser.getHostAddresses()); loopAddress.removeAll(getBlacklistKeys()); Collections.shuffle(loopAddress); List<HostAddress> blacklistShuffle=new LinkedList<>(getBlacklistKeys()); Collections.shuffle(blacklistShuffle); loopAddress.addAll(blacklistShuffle); if (masterProtocol != null && !isMasterHostFail()) { loopAddress.remove(masterProtocol.getHostAddress()); loopAddress.add(masterProtocol.getHostAddress()); } if (secondaryProtocol != null && !isSecondaryHostFail()) { loopAddress.remove(secondaryProtocol.getHostAddress()); loopAddress.add(secondaryProtocol.getHostAddress()); } if ((isMasterHostFail() || isSecondaryHostFail()) || searchFilter.isInitialConnection()) { do { MastersSlavesProtocol.loop(this,loopAddress,searchFilter); if (!searchFilter.isFailoverLoop()) { try { checkWaitingConnection(); } catch ( ReconnectDuringTransactionException e) { } } } while (searchFilter.isInitialConnection() && masterProtocol == null); } }
Loop to connect.
public IconRenderer(String tooltip){ this.tooltip=tooltip; }
Instantiates a new icon renderer.
private void internalResolve(Scope scope){ if (this.completionNode != null) { if (this.completionNode instanceof CompletionOnJavadocTag) { ((CompletionOnJavadocTag)this.completionNode).filterPossibleTags(scope); } else { boolean resolve=true; if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { resolve=((CompletionOnJavadocParamNameReference)this.completionNode).token != null; } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { resolve=((CompletionOnJavadocTypeParamReference)this.completionNode).token != null; } if (resolve) { switch (scope.kind) { case Scope.CLASS_SCOPE: this.completionNode.resolveType((ClassScope)scope); break; case Scope.METHOD_SCOPE: this.completionNode.resolveType((MethodScope)scope); break; } } if (this.completionNode instanceof CompletionOnJavadocParamNameReference) { CompletionOnJavadocParamNameReference paramNameReference=(CompletionOnJavadocParamNameReference)this.completionNode; if (scope.kind == Scope.METHOD_SCOPE) { paramNameReference.missingParams=missingParamTags(paramNameReference.binding,(MethodScope)scope); } if (paramNameReference.token == null || paramNameReference.token.length == 0) { paramNameReference.missingTypeParams=missingTypeParameterTags(paramNameReference.binding,scope); } } else if (this.completionNode instanceof CompletionOnJavadocTypeParamReference) { CompletionOnJavadocTypeParamReference typeParamReference=(CompletionOnJavadocTypeParamReference)this.completionNode; typeParamReference.missingParams=missingTypeParameterTags(typeParamReference.resolvedType,scope); } } Binding qualifiedBinding=null; if (this.completionNode instanceof CompletionOnJavadocQualifiedTypeReference) { CompletionOnJavadocQualifiedTypeReference typeRef=(CompletionOnJavadocQualifiedTypeReference)this.completionNode; if (typeRef.packageBinding == null) { qualifiedBinding=typeRef.resolvedType; } else { qualifiedBinding=typeRef.packageBinding; } } else if (this.completionNode instanceof CompletionOnJavadocMessageSend) { CompletionOnJavadocMessageSend msg=(CompletionOnJavadocMessageSend)this.completionNode; if (!msg.receiver.isThis()) qualifiedBinding=msg.receiver.resolvedType; } else if (this.completionNode instanceof CompletionOnJavadocAllocationExpression) { CompletionOnJavadocAllocationExpression alloc=(CompletionOnJavadocAllocationExpression)this.completionNode; qualifiedBinding=alloc.type.resolvedType; } throw new CompletionNodeFound(this.completionNode,qualifiedBinding,scope); } }
Resolve selected node if not null and throw exception to let clients know that it has been found.
public void openDirectory(boolean addDir){ showWaitFrame(); File dir=getDirectory("openDirMenu",false); if (dir != null) { if (addDir) { doPreviewDialog(dir,new AActionListener(dir),new MActionListener(dir,true),null,new CActionListener(),0); } else { doPreviewDialog(dir,null,new MActionListener(dir,true),null,new CActionListener(),0); } } else { JOptionPane.showMessageDialog(null,Bundle.getMessage("NoImagesInDir"),Bundle.getMessage("searchFSMenu"),JOptionPane.INFORMATION_MESSAGE); } closeWaitFrame(); }
Open one directory.
private static boolean hasProtocol(String systemId){ return systemId != null && HAS_PROTOCOL.matcher(systemId).find(); }
Check for protocol on a systemId. eg, file://blah, http://blah, jndi://blah have protocols /blah does not
protected void updateLeadIndex(){ if (leadPath != null) { if (selection == null) { leadPath=null; leadIndex=leadRow=-1; } else { leadRow=leadIndex=-1; for (int counter=selection.length - 1; counter >= 0; counter--) { if (selection[counter] == leadPath) { leadIndex=counter; break; } } } } else { leadIndex=-1; } }
Updates the leadIndex instance variable.
public GenwizardVisualPanel1(){ initComponents(); }
Creates new form GenwizardVisualPanel1
private static void runTest(String main,boolean clearGcOpts,String... testOpts) throws Throwable { List<String> opts=new ArrayList<>(); opts.add(JDKToolFinder.getJDKTool("java")); opts.addAll(Arrays.asList(Utils.getTestJavaOpts())); opts.add("-cp"); opts.add(System.getProperty("test.class.path","test.class.path")); opts.add("-XX:+PrintGCDetails"); if (clearGcOpts) { opts=Utils.removeGcOpts(opts); } opts.addAll(Arrays.asList(testOpts)); opts.add(main); OutputAnalyzer output=ProcessTools.executeProcess(opts.toArray(new String[0])); output.shouldHaveExitValue(0); if (output.getStdout().indexOf(successMessage) < 0) { throw new Exception("output missing '" + successMessage + "'"); } }
Runs a test in a separate JVM. command line like: {test_jdk}/bin/java {defaultopts} -cp {test.class.path} {testopts} main {defaultopts} are the default java options set by the framework. Default GC options in {defaultopts} may be removed. This is used when the test specifies its own GC options.
public static SVGPoint elementCoordinatesFromEvent(Document doc,Element tag,Event evt){ try { DOMMouseEvent gnme=(DOMMouseEvent)evt; SVGMatrix mat=((SVGLocatable)tag).getScreenCTM(); SVGMatrix imat=mat.inverse(); SVGPoint cPt=((SVGDocument)doc).getRootElement().createSVGPoint(); cPt.setX(gnme.getClientX()); cPt.setY(gnme.getClientY()); return cPt.matrixTransform(imat); } catch ( Exception e) { LoggingUtil.warning("Error getting coordinates from SVG event.",e); return null; } }
Convert the coordinates of an DOM Event from screen into element coordinates.
private void reflectParametersInView(){ removeAllViews(); dots.clear(); for (int i=0; i < numberOfDots; i++) { final Dot dot=new Dot(getContext()); dot.setInactiveDiameterPx(unselectedDotDiameterPx).setActiveDiameterPx(selectedDotDiameterPx).setActiveColor(selectedDotColor).setInactiveColor(unselectedDotColor).setTransitionDuration(dotTransitionDuration); if (i == selectedDotIndex) { dot.setActive(false); } else { dot.setInactive(false); } final int maxDiameterDim=Math.max(selectedDotDiameterPx,unselectedDotDiameterPx); final int startMargin=i * (spacingBetweenDotsPx + unselectedDotDiameterPx); LayoutParams params=new LayoutParams(maxDiameterDim,maxDiameterDim); params.setMargins(startMargin,0,0,0); if (Build.VERSION.SDK_INT >= 17) { params.setMarginStart(startMargin); } dot.setLayoutParams(params); addView(dot); dots.add(i,dot); } }
Constructs and displays dots based on current member variables.
public static byte[] decode(byte[] data){ ByteArrayOutputStream bOut=new ByteArrayOutputStream(); try { encoder.decode(data,0,data.length,bOut); } catch ( IOException e) { throw new RuntimeException("exception decoding base64 string: " + e); } return bOut.toByteArray(); }
decode the base 64 encoded input data. It is assumed the input data is valid.
@Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); if (savedInstanceState != null) { Log.d(TAG,"onCreate(): activity re-created"); } else { Log.d(TAG,"onCreate(): activity created anew"); } }
Hook method called when a new instance of Activity is created. One time initialization code should go here e.g. UI layout, some class scope variable initialization. if finish() is called from onCreate no other lifecycle callbacks are called except for onDestroy().
@Override public boolean allowPaypalDonations(){ return false; }
Paypal donations aren't approved by Google, usually.