code
stringlengths
10
174k
nl
stringlengths
3
129k
@Override public int hashCode(){ if (m_RecalcHashCode) { m_HashCode=toString().hashCode(); m_RecalcHashCode=false; } return m_HashCode; }
Returns the hash code value for this collection.
@Override public int intValue(){ return value; }
Returns the value of this MutableInt as an int.
public DefaultDeployableFactory(ClassLoader classLoader){ registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.WAR,WAR.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.EJB,EJB.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.EAR,EAR.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.SAR,SAR.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.RAR,RAR.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.FILE,File.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.BUNDLE,Bundle.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.HAR,HAR.class); registerDeployable(DEFAULT_CONTAINER_ID,DeployableType.AOP,AOP.class); AbstractFactoryRegistry.register(classLoader,this); }
Register deployable classes mappings.
public VarInt(long value){ this.value=value; originallyEncodedSize=getSizeInBytes(); }
Constructs a new VarInt with the given unsigned long value.
public void makeClass(Vector v,boolean caseless){ makeClass(new IntCharSet(v),caseless); }
Updates the current partition, so that the specified set of characters gets a new character class. Characters that are elements of the set <code>v</code> are not in the same equivalence class with characters that are not elements of the set <code>v</code>.
@POST @Produces({MediaType.APPLICATION_XML,MediaType.APPLICATION_JSON}) @Path("/{id}/deactivate") @CheckPermission(roles={Role.TENANT_ADMIN},acls={ACL.ANY}) public TaskList deactivateSnapshot(@PathParam("id") URI id,@DefaultValue("FULL") @QueryParam("type") String type){ _log.info("Executing {} snapshot delete for snapshot {}",type,id); String opStage=null; boolean successStatus=true; String taskId=UUID.randomUUID().toString(); TaskList response=new TaskList(); BlockSnapshot snap=(BlockSnapshot)queryResource(id); List<Class<? extends DataObject>> excludeTypes=new ArrayList<Class<? extends DataObject>>(); excludeTypes.add(BlockSnapshotSession.class); if (VolumeDeleteTypeEnum.VIPR_ONLY.name().equals(type)) { excludeTypes.add(ExportGroup.class); excludeTypes.add(ExportMask.class); } ArgValidator.checkReference(BlockSnapshot.class,id,checkForDelete(snap,excludeTypes)); if (!VolumeDeleteTypeEnum.VIPR_ONLY.name().equals(type)) { opStage=AuditLogManager.AUDITOP_BEGIN; URIQueryResultList snapSessionURIs=new URIQueryResultList(); _dbClient.queryByConstraint(ContainmentConstraint.Factory.getLinkedTargetSnapshotSessionConstraint(id),snapSessionURIs); Iterator<URI> snapSessionURIsIter=snapSessionURIs.iterator(); if (snapSessionURIsIter.hasNext()) { _log.info("Snapshot is linked target for a snapshot session"); SnapshotSessionUnlinkTargetsParam param=new SnapshotSessionUnlinkTargetsParam(); List<SnapshotSessionUnlinkTargetParam> targetInfoList=new ArrayList<SnapshotSessionUnlinkTargetParam>(); SnapshotSessionUnlinkTargetParam targetInfo=new SnapshotSessionUnlinkTargetParam(id,Boolean.TRUE); targetInfoList.add(targetInfo); param.setLinkedTargets(targetInfoList); response.getTaskList().add(getSnapshotSessionManager().unlinkTargetVolumesFromSnapshotSession(snapSessionURIsIter.next(),param,OperationTypeEnum.DELETE_VOLUME_SNAPSHOT)); return response; } if (snap.getInactive()) { _log.info("Snapshot is already inactive"); Operation op=new Operation(); op.ready("The snapshot has already been deleted"); op.setResourceType(ResourceOperationTypeEnum.DELETE_VOLUME_SNAPSHOT); _dbClient.createTaskOpStatus(BlockSnapshot.class,snap.getId(),taskId,op); response.getTaskList().add(toTask(snap,taskId,op)); return response; } } StorageSystem device=_dbClient.queryObject(StorageSystem.class,snap.getStorageController()); List<BlockSnapshot> snapshots=new ArrayList<BlockSnapshot>(); final URI cgId=snap.getConsistencyGroup(); if (!NullColumnValueGetter.isNullURI(cgId) && !NullColumnValueGetter.isNullValue(snap.getReplicationGroupInstance())) { snapshots=ControllerUtils.getSnapshotsPartOfReplicationGroup(snap,_dbClient); } else { snapshots.add(snap); } Volume parentVolume=_permissionsHelper.getObjectById(snap.getParent(),Volume.class); checkForPendingTasks(Arrays.asList(parentVolume.getTenant().getURI()),snapshots); for ( BlockSnapshot snapshot : snapshots) { Operation snapOp=_dbClient.createTaskOpStatus(BlockSnapshot.class,snapshot.getId(),taskId,ResourceOperationTypeEnum.DELETE_VOLUME_SNAPSHOT); response.getTaskList().add(toTask(snapshot,taskId,snapOp)); } try { BlockServiceApi blockServiceApiImpl=BlockService.getBlockServiceImpl(parentVolume,_dbClient); blockServiceApiImpl.deleteSnapshot(snap,snapshots,taskId,type); } catch ( APIException|InternalException e) { successStatus=false; String errorMsg=String.format("Exception attempting to delete snapshot %s: %s",snap.getId(),e.getMessage()); _log.error(errorMsg); for ( TaskResourceRep taskResourceRep : response.getTaskList()) { taskResourceRep.setState(Operation.Status.error.name()); taskResourceRep.setMessage(errorMsg); _dbClient.error(BlockSnapshot.class,taskResourceRep.getResource().getId(),taskId,e); } } catch ( Exception e) { successStatus=false; String errorMsg=String.format("Exception attempting to delete snapshot %s: %s",snap.getId(),e.getMessage()); _log.error(errorMsg); ServiceCoded sc=APIException.internalServerErrors.genericApisvcError(errorMsg,e); for ( TaskResourceRep taskResourceRep : response.getTaskList()) { taskResourceRep.setState(Operation.Status.error.name()); taskResourceRep.setMessage(sc.getMessage()); _dbClient.error(BlockSnapshot.class,taskResourceRep.getResource().getId(),taskId,sc); } } auditOp(OperationTypeEnum.DELETE_VOLUME_SNAPSHOT,successStatus,opStage,id.toString(),snap.getLabel(),snap.getParent().getName(),device.getId().toString()); return response; }
Deactivate volume snapshot, this will move the snapshot to a "marked-for-delete" state. It will be deleted by the garbage collector on a subsequent iteration If this snapshot was created from a volume that is part of a consistency group, then all the related snapshots will be deactivated, as well.
public static List propertyDescriptors(int apiLevel){ return PROPERTY_DESCRIPTORS; }
Returns a list of structural property descriptors for this node type. Clients must not modify the result.
public CataclysmicDemographicModel(Parameter N0Parameter,Parameter N1Parameter,Parameter growthRateParameter,Parameter timeParameter,Type units,boolean useSpike){ this(CataclysmicDemographicModelParser.CATACLYSM_MODEL,N0Parameter,N1Parameter,growthRateParameter,timeParameter,units,useSpike); }
Construct demographic model with default settings
public <T extends SuperModel>boolean insert(T model){ Object[] objects=model.getInsertSql(); return execSQL(objects[0].toString(),Arrays.copyOfRange(objects,1,objects.length)); }
Insert a model.
public void update(byte[] in,int off,int len){ contentDigest.update(in,off,len); }
update the internal digest with the byte array in
PostscriptGraphics(PostscriptGraphics copy){ m_extent=new Rectangle(copy.m_extent); m_printstream=copy.m_printstream; m_localGraphicsState=new GraphicsState(copy.m_localGraphicsState); m_psGraphicsState=copy.m_psGraphicsState; }
Creates a new cloned PostscriptGraphics object.
public boolean isParameterized(){ EList<TypeRef> _typeArgs=this.getTypeArgs(); boolean _isEmpty=_typeArgs.isEmpty(); return (!_isEmpty); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public ConstraintIntervalType createConstraintIntervalTypeFromString(EDataType eDataType,String initialValue){ ConstraintIntervalType result=ConstraintIntervalType.get(initialValue); if (result == null) throw new IllegalArgumentException("The value '" + initialValue + "' is not a valid enumerator of '"+ eDataType.getName()+ "'"); return result; }
<!-- begin-user-doc --> <!-- end-user-doc -->
private Optional<FeedItem> findLastVisibleFeedItem(Set<ContentType> contentType){ List<FeedItem> items=feedAdapter.getFeed().getItems(); return getRecyclerViewLayoutManager().<Optional<FeedItem>>transform(null).get(); }
Finds the first item in the proxy, that is visible and of one of the given content type.
public TaskBuilder single(){ this.type=TaskType.SINGLE; return this; }
<b>This is default value/state of builder.</b> <br> Change task type to single, so it will be only executed once.
public static double mean(Iterator tuples,String field){ try { int count=0; double sum=0; while (tuples.hasNext()) { sum+=((Tuple)tuples.next()).getDouble(field); ++count; } return sum / count; } catch ( Exception e) { return Double.NaN; } }
Get the mean value of a tuple data value. If any tuple does not have the named field or the field is not a numeric data type, NaN will be returned.
@Override public void onPageScrollStateChanged(int page){ }
On scroll state of page changed.
public static boolean exitableTerrain(int terrType){ boolean exitableTerrainType=false; for (int i=0; i < Terrains.exitableTerrains.length; i++) { exitableTerrainType|=terrType == Terrains.exitableTerrains[i]; } return exitableTerrainType; }
Checks to see if the given terrain type can have exits.
private static CTutorial loadTutorial(final File file) throws ParserConfigurationException, SAXException, IOException { String name=""; String description=""; final List<CTutorialStep> steps=new ArrayList<CTutorialStep>(); final DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); final DocumentBuilder builder=factory.newDocumentBuilder(); final Document document=builder.parse(file); final NodeList nodes=document.getFirstChild().getChildNodes(); for (int i=0; i < nodes.getLength(); ++i) { final Node node=nodes.item(i); final String nodeName=node.getNodeName(); if ("name".equals(nodeName)) { name=node.getTextContent(); } else if ("description".equals(nodeName)) { description=node.getTextContent(); } else if ("steps".equals(nodeName)) { steps.addAll(readSteps(node)); } } return new CTutorial(name,description,steps); }
Loads a single tutorial from a file.
public void readFromNBT(NBTTagCompound nbt){ this.cheese=EnumCheeseType.loadFromNBT(nbt); this.cheeseStage=EnumCheeseStage.loadFromNBT(nbt); if (nbt.hasKey("age")) { this.age=nbt.getInteger("age"); } if (nbt.hasKey("slices")) { this.slices=nbt.getInteger("slices"); } if (nbt.hasKey("slices_max")) { this.slicesMax=nbt.getInteger("slices_max"); } }
When the tileentity is reloaded from an ItemStack
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:32:00.390 -0500",hash_original_method="344907C67A02819CC7A230367AD45761",hash_generated_method="4B06F00DE2D9425181B65C93B3228913") @Override protected int computeHorizontalScrollRange(){ final int count=getChildCount(); final int contentWidth=getWidth() - mPaddingLeft - mPaddingRight; if (count == 0) { return contentWidth; } int scrollRange=getChildAt(0).getRight(); final int scrollX=mScrollX; final int overscrollRight=Math.max(0,scrollRange - contentWidth); if (scrollX < 0) { scrollRange-=scrollX; } else if (scrollX > overscrollRight) { scrollRange+=scrollX - overscrollRight; } return scrollRange; }
<p>The scroll range of a scroll view is the overall width of all of its children.</p>
public DateBuilder inLocale(Locale locale){ this.lc=locale; return this; }
Set the Locale for the Date that will be built by this builder (if "null", system default will be used)
public IgniteThread(GridWorker worker){ this(DFLT_GRP,worker.gridName(),worker.name(),worker,GRP_IDX_UNASSIGNED); }
Creates thread with given worker.
void convertRequireToImportStatements(Node n,String fullLocalName,String requiredNamespace){ if (!namespaceToModule.containsKey(requiredNamespace)) { compiler.report(JSError.make(n,GentsErrorManager.GENTS_MODULE_PASS_ERROR,String.format("Module %s does not exist.",requiredNamespace))); return; } String localName=nameUtil.lastStepOfName(fullLocalName); FileModule module=namespaceToModule.get(requiredNamespace); String moduleSuffix=nameUtil.lastStepOfName(requiredNamespace); String backupName=moduleSuffix.equals(localName) ? moduleSuffix + "Exports" : moduleSuffix; if (module.shouldUseOldSyntax()) { Node importNode=new Node(Token.IMPORT,IR.empty(),Node.newString(Token.NAME,localName),Node.newString("goog:" + requiredNamespace)); nodeComments.replaceWithComment(n,importNode); compiler.reportCodeChange(); registerLocalSymbol(n.getSourceFileName(),fullLocalName,requiredNamespace,localName); return; } String referencedFile=pathUtil.getImportPath(n.getSourceFileName(),module.file); boolean imported=false; if (module.importedNamespacesToSymbols.containsKey(requiredNamespace)) { Node importSpec=new Node(Token.IMPORT_SPEC,IR.name(moduleSuffix)); if (!moduleSuffix.equals(localName)) { importSpec.addChildToBack(IR.name(localName)); } Node importNode=new Node(Token.IMPORT,IR.empty(),new Node(Token.IMPORT_SPECS,importSpec),Node.newString(referencedFile)); n.getParent().addChildBefore(importNode,n); nodeComments.moveComment(n,importNode); imported=true; registerLocalSymbol(n.getSourceFileName(),fullLocalName,requiredNamespace,localName); localName=backupName; } if (module.providesObjectChildren.get(requiredNamespace).size() > 0) { Node importNode=new Node(Token.IMPORT,IR.empty(),Node.newString(Token.IMPORT_STAR,localName),Node.newString(referencedFile)); n.getParent().addChildBefore(importNode,n); nodeComments.moveComment(n,importNode); imported=true; for ( String child : module.providesObjectChildren.get(requiredNamespace)) { if (!valueRewrite.contains(n.getSourceFileName(),child)) { String fileName=n.getSourceFileName(); registerLocalSymbol(fileName,fullLocalName + '.' + child,requiredNamespace + '.' + child,localName + '.' + child); } } } if (!imported) { Node importNode=new Node(Token.IMPORT,IR.empty(),IR.empty(),Node.newString(referencedFile)); n.getParent().addChildBefore(importNode,n); nodeComments.moveComment(n,importNode); } n.getParent().removeChild(n); compiler.reportCodeChange(); }
Converts a Closure goog.require call into a TypeScript import statement. The resulting node is dependent on the exports by the module being imported: import localName from "goog:old.namespace.syntax"; import {A as localName} from "./valueExports"; import * as localName from "./objectExports"; import "./sideEffectsOnly"
@VisibleForTesting public void clearPendingInvalidations(Context context){ SharedPreferences.Editor editor=PreferenceManager.getDefaultSharedPreferences(context).edit(); editor.putString(DELAYED_ACCOUNT_NAME,null); editor.putStringSet(DELAYED_INVALIDATIONS,null); editor.apply(); }
If there are any pending invalidations, they will be cleared.
public static int parseCodePoint(String s) throws NumberFormatException { return Integer.parseInt(s,16); }
Parse the codePoint attribute for a Unicode character. If the parse succeeds, the codePoint field of this UnicodeSpec object is updated and false is returned. The codePoint attribute should be a four to six digit hexadecimal integer.
public final boolean hasIndex(){ return (index >= 0); }
Gets whether or not this instance has been assigned an index.
public static String encodeLines(byte[] in,int iOff,int iLen,int lineLen,String lineSeparator){ final int blockLen=lineLen * 3 / 4; if (blockLen <= 0) { throw new IllegalArgumentException(); } final int lines=(iLen + blockLen - 1) / blockLen; final int bufLen=(iLen + 2) / 3 * 4 + lines * lineSeparator.length(); final StringBuilder buf=new StringBuilder(bufLen); int ip=0; while (ip < iLen) { final int l=Math.min(iLen - ip,blockLen); buf.append(encode(in,iOff + ip,l)); buf.append(lineSeparator); ip+=l; } return buf.toString(); }
Encodes a byte array into Base 64 format and breaks the output into lines.
@SuppressWarnings("unchecked") @Override public void eSet(int featureID,Object newValue){ switch (featureID) { case EipPackage.ROUTE__OWNED_ENDPOINTS: getOwnedEndpoints().clear(); getOwnedEndpoints().addAll((Collection<? extends Endpoint>)newValue); return; case EipPackage.ROUTE__OWNED_CHANNELS: getOwnedChannels().clear(); getOwnedChannels().addAll((Collection<? extends Channel>)newValue); return; case EipPackage.ROUTE__NAME: setName((String)newValue); return; case EipPackage.ROUTE__EXCHANGE_TYPE: setExchangeType((ExchangeType)newValue); return; } super.eSet(featureID,newValue); }
<!-- begin-user-doc --> <!-- end-user-doc -->
public void write(int c){ buf.append((char)c); }
Write a single character.
public void initialize(EngineStatusCallback engineStatusCallback){ this.statusEventHandler.initialize(engineStatusCallback); this.outputEventHandler.initialize(engineStatusCallback); }
Initialize some callbacks
public String encode(String pString) throws EncoderException { if (pString == null) { return null; } try { return encode(pString,getDefaultCharset()); } catch ( UnsupportedEncodingException e) { throw new EncoderException(e.getMessage()); } }
Encodes a string into its quoted-printable form using the default string charset. Unsafe characters are escaped. <p> This function implements a subset of quoted-printable encoding specification (rule #1 and rule #2) as defined in RFC 1521 and is suitable for encoding binary data. </p>
public DiskBasedCache(File rootDirectory){ this(rootDirectory,DEFAULT_DISK_USAGE_BYTES); }
Constructs an instance of the DiskBasedCache at the specified directory using the default maximum cache size of 5MB.
public static OutputLimitClause create(OutputLimitSelector selector,double frequency){ return new OutputLimitClause(selector,frequency); }
Creates an output limit clause.
public static boolean isHeadMissing(final VcsException e){ @NonNls final String errorText="fatal: bad revision 'HEAD'\n"; return e.getMessage().equals(errorText); }
Check if the exception means that HEAD is missing for the current repository.
private String compute(String left,Boolean right){ if (left == null && right == null) { return null; } return (left == null ? "" : left) + (right == null ? "" : right); }
Adds a String and a Boolean. If both are missing, then the result is missing; if one is missing, it is ignored.
public boolean isNamespaceAware(){ return _isNamespaceAware; }
Gets Namespace aware flag.
public void remove(int fieldNumber){ int i=binarySearch(fieldNumber); if (i >= 0 && mData[i] != DELETED) { mData[i]=DELETED; mGarbage=true; } }
Removes the data from the specified fieldNumber, if there was any.
protected void sequence_IntersectionTypeExpressionOLD_TypeRef_TypeRefWithModifiers(ISerializationContext context,IntersectionTypeExpression semanticObject){ genericSequencer.createSequence(context,semanticObject); }
Contexts: IntersectionTypeExpression.IntersectionTypeExpression_1_0 returns IntersectionTypeExpression PrimaryTypeExpression returns IntersectionTypeExpression Constraint: ( typeRefs+=TypeRefWithoutModifiers typeRefs+=TypeRefWithoutModifiers* ((undefModifier=UndefModifierToken? nullModifier=NullModifierToken?) | undefModifier=UndefModifierToken)? )
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:28:44.149 -0500",hash_original_method="A22563797EE8B98D8D2C96F4FC0F2C77",hash_generated_method="EB9D53584F352AD6AC60DCC4EDA82399") public Cursor query(SQLiteDatabase db,String[] projectionIn,String selection,String[] selectionArgs,String groupBy,String having,String sortOrder,String limit){ Cursor ret=new DSCursor(DSOnlyType.NOT_USED); ret.addTaint(db.getTaint()); ret.addTaint(projectionIn.getTaint()); ret.addTaint(projectionIn[0].getTaint()); ret.addTaint(selection.getTaint()); ret.addTaint(selectionArgs.getTaint()); ret.addTaint(selectionArgs[0].getTaint()); ret.addTaint(groupBy.getTaint()); ret.addTaint(having.getTaint()); ret.addTaint(sortOrder.getTaint()); ret.addTaint(limit.getTaint()); return ret; }
Perform a query by combining all current settings and the information passed into this method.
public PayloadItem(E payloadExt){ super(); if (payloadExt == null) throw new IllegalArgumentException("payload cannot be 'null'"); payload=payloadExt; }
Create an <tt>Item</tt> with no id and a payload The id will be set by the server.
public void testNegPos(){ String numA="-27384627835298756289327365"; String numB="0"; String res="-27384627835298756289327365"; BigInteger aNumber=new BigInteger(numA); BigInteger bNumber=new BigInteger(numB); BigInteger result=aNumber.xor(bNumber); assertTrue(res.equals(result.toString())); }
Xor for a negative number and zero
public void initializeTrie(Context context,int fileResource){ TrieNode startInsertionNode=mRoot; InputStream stream=context.getResources().openRawResource(fileResource); BufferedReader reader=null; try { reader=new BufferedReader(new InputStreamReader(stream,"UTF-8")); String input; while ((input=reader.readLine()) != null) { for (int i=0; i < input.length(); i++) { startInsertionNode=insertSymbol(startInsertionNode,input.charAt(i)); } } } catch ( IOException e) { LogUtils.log(this,Log.ERROR,"Unable to read PPMTrie input file: %1$s",e.toString()); } finally { try { if (reader != null) { reader.close(); } } catch ( IOException e) { LogUtils.log(this,Log.ERROR,"Unable to close input file: %1$s",e.toString()); } } }
Uses the text in a training file to form a ppm model and store it in a trie. The file is a .txt file that contains plain unicode text.
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:56:50.891 -0500",hash_original_method="7045B1DBF21073AA43E994CE221E4094",hash_generated_method="7045B1DBF21073AA43E994CE221E4094") ObjectStreamField(String signature,String name){ if (name == null) { throw new NullPointerException(); } this.name=name; this.typeString=signature.replace('.','/').intern(); defaultResolve(); this.isDeserialized=true; }
Constructs an ObjectStreamField with the given name and the given type. The type may be null.
@Override protected final int nextIndex(){ if (_expectedSize != _hash.size()) { throw new ConcurrentModificationException(); } Object[] set=_map._set; int i=_index; while (i-- > 0 && (set[i] == null || set[i] == TObjectHash.REMOVED)) ; return i; }
Returns the index of the next value in the data structure or a negative value if the iterator is exhausted.
public static ArrayList<BaseQuestion> returnChatList(String jsonFile){ ArrayList<BaseQuestion> questions=new ArrayList<BaseQuestion>(); RestAPI api=RestAPI.getAPI(); questions=api.getChatQuestions(jsonFile); return questions; }
Get list of chat questions
public int numElements() throws Exception { if (m_Classifier instanceof PartitionGenerator) return ((PartitionGenerator)m_Classifier).numElements(); else throw new Exception("Classifier: " + getClassifierSpec() + " cannot generate a partition"); }
Returns the number of elements in the partition. (If the base classifier supports this.)
@Override protected Instance process(Instance instance) throws Exception { m_Remove.input(instance); return m_Remove.output(); }
processes the given instance (may change the provided instance) and returns the modified version.
public static void main(String[] args) throws Exception { if (args.length > 1) { BufferedImage firstImage=ImageIO.read(new File(args[0])); ImageOutputStream output=new FileImageOutputStream(new File(args[args.length - 1])); GifSequenceWriter writer=new GifSequenceWriter(output,firstImage.getType(),1,false); writer.writeToSequence(firstImage); for (int i=1; i < args.length - 1; i++) { BufferedImage nextImage=ImageIO.read(new File(args[i])); writer.writeToSequence(nextImage); } writer.close(); output.close(); } else { System.out.println("Usage: java GifSequenceWriter [list of gif files] [output file]"); } }
public GifSequenceWriter( BufferedOutputStream outputStream, int imageType, int timeBetweenFramesMS, boolean loopContinuously) {
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if (index < 0) { throw new IllegalStateException(); } if (lag < 0) { throw new IllegalStateException(); } }
Adds semantic checks to the default deserialization method. This method must have the standard signature for a readObject method, and the body of the method must begin with "s.defaultReadObject();". Other than that, any semantic checks can be specified and do not need to stay the same from version to version. A readObject method of this form may be added to any class, even if Tetrad sessions were previously saved out using a version of the class that didn't include it. (That's what the "s.defaultReadObject();" is for. See J. Bloch, Effective Java, for help.
public boolean markAsRead(String smsNumber){ try { ContentResolver cr=_context.getContentResolver(); ContentValues values=new ContentValues(); values.put("read","1"); cr.update(SMS_INBOX_CONTENT_URI,values," address='" + smsNumber + "'",null); return true; } catch ( Exception e) { Log.w("markAsRead() exception:",e); return false; } }
Not supported in Android 5 Marks all SMS from a given phone number as read
public CategoryAxis3D(String label){ super(label); }
Creates a new axis using default attribute values.
@Override public int compare(Triplet<byte[],UserLeafNode,Operation> p1,Triplet<byte[],UserLeafNode,Operation> p2){ byte[] buf1=p1.getValue0(); byte[] buf2=p2.getValue0(); if (buf1.length < 3 || buf2.length < 3) { throw new RuntimeException("bad byte array length"); } for (int i=0; i < 3; i++) { if (buf1[i] > buf2[i]) { return 1; } else if (buf1[i] < buf2[i]) { return -1; } } Operation op1=p1.getValue2(); Operation op2=p2.getValue2(); if (op1 instanceof Register) { return 1; } if (op2 instanceof Register) { return -1; } if (op1 instanceof KeyChange && op2 instanceof KeyChange) { return (((KeyChange)op1).getCounter() > ((KeyChange)op2).getCounter()) ? 1 : -1; } return 0; }
Compares the first 24 bits of two data binding lookup indeces.
private void parsePublicUserIdentity(Node node){ String publicUserIdentity=null; if (node == null) { return; } Node childnode=node.getFirstChild(); if (childnode != null) { do { if (publicUserIdentity == null) { if ((publicUserIdentity=getValueByParamName("Public_User_Identity",childnode,TYPE_TXT)) != null) { String username=extractUserNamePart(publicUserIdentity.trim()); PhoneNumber number=ContactUtil.getValidPhoneNumberFromUri(username); if (number == null) { if (sLogger.isActivated()) { sLogger.error("Invalid public user identity '" + username + "'"); } mRcsSettings.setUserProfileImsUserName(null); } else { ContactId contact=ContactUtil.createContactIdFromValidatedData(number); mRcsSettings.setUserProfileImsUserName(contact); } } } } while ((childnode=childnode.getNextSibling()) != null); } }
Parse public user identity
@Override public void clearUndo(){ ((DataSortedTableModel)m_TableData.getModel()).clearUndo(); }
removes the undo history
public static List<org.oscm.internal.vo.VOParameterOption> convertToUpVOParameterOption(List<org.oscm.vo.VOParameterOption> oldVO){ if (oldVO == null) { return null; } List<org.oscm.internal.vo.VOParameterOption> newVO=new ArrayList<org.oscm.internal.vo.VOParameterOption>(); for ( org.oscm.vo.VOParameterOption tmp : oldVO) { newVO.add(convertToUp(tmp)); } return newVO; }
Convert list of VOParameterOption.
public void traceFieldNotStaticInHostJdk(){ traceNulledWord(": field not static in host jdk"); }
Report a field that is an instance field in the host JDK but a static field in ours.
public SwitchPreference(Context context){ super(context,null); }
Construct a new SwitchPreference with default style options.
private void publishTextRecord(final LogRecord record){ try { logpane.publish(record); } catch ( Exception e) { throw new RuntimeException("Error writing a log-like message.",e); } }
Publish a text record to the pane
public static final List<String> combine(Collection<String> list,String... args){ List<String> ret=new ArrayList<String>(list); for ( String s : args) { ret.add(s); } return ret; }
Combine a string collection (list) with additional strings.
public void clear(){ try { skip(size); } catch ( EOFException e) { throw new AssertionError(e); } }
Discards all bytes in this buffer. Calling this method when you're done with a buffer will return its segments to the pool.
public static String fromUTF8(byte[] bytes){ try { return new String(bytes,ENCODING_UTF8); } catch ( UnsupportedEncodingException e) { throw new AssertionError(e); } }
Decodes the given binary data with UTF-8.
private void analyzeFiles(Set<String> fileNames) throws CLIArgumentParserException, IOException { ColorSettings colorSettings=new ColorSettings(configuration.shouldColorOutput(),configuration.shouldInvertColorOutput()); Formatter formatter=configuration.getFormatter(colorSettings); Severity maxSeverity=configuration.getMaxSeverity(); ConstructLengths constructLengths=configuration.parseConstructLengths(); Set<Rules> enabledRules=configuration.getEnabledRules(); numberOfFilesBeforePurge=configuration.numberOfFilesBeforePurge(); List<File> files=fileNames.parallelStream().map(null).collect(Collectors.toList()); formatter.printProgressInfo(String.format("Analyzing %s:%n",Formatter.pluralize(fileNames.size(),"file","files"))); files.parallelStream().forEach(null); formatter.printProgressInfo(String.format("%n")); printersForAllFiles.forEach(null); formatter.displaySummary(fileNames.size(),numSkippedFiles.get(),numErrors.get(),numWarnings.get()); handleErrorViolations(formatter,numErrors.get()); }
Analyze files with SwiftLexer, SwiftParser and Listeners.
@Override public void eUnset(int featureID){ switch (featureID) { case UmplePackage.ENUM___NAME_1: setName_1(NAME_1_EDEFAULT); return; case UmplePackage.ENUM___STATE_NAME_1: setStateName_1(STATE_NAME_1_EDEFAULT); return; case UmplePackage.ENUM___ANONYMOUS_ENUM_11: getAnonymous_enum_1_1().clear(); return; } super.eUnset(featureID); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private synchronized boolean isSelectedTrackRecording(){ return trackDataHub != null && trackDataHub.isSelectedTrackRecording(); }
Returns true if the selected track is recording. Needs to be synchronized because the trackDataHub can be accessed by multiple threads.
public byte[] filter(byte[] buffer,int offset,int len){ byte[] slices=getSlices(buffer,offset,len); if (null == slices) { return null; } int insertionPoint=findInsertionPoint(slices); if (insertionPoint >= 0) { return buffer; } if (-1 == insertionPoint) { if (hasHinting) { return Arrays.copyOf(this.rangekeys,this.bounds[1]); } else { return null; } } if (-nranges - 1 == insertionPoint) { if (hasHinting) { return EMPTY_BYTE_ARRAY; } else { return null; } } if (-(insertionPoint + 1) % 2 == 0) { if (hasHinting) { int hintOffset=this.slicesLength * (-(insertionPoint + 1)); return Arrays.copyOfRange(this.rangekeys,hintOffset,this.bounds[1]); } else { return null; } } return buffer; }
Determine if a key should be filtered or not. This method returns a byte array which indicates how the key should be dealt with. If the return value is 'buffer', the key should be include. If the return value is null, the key should be skipped and no next key hint is available If the return value is a non empty byte array (different from 'buffer'), the key should be skipped and the return value used as the next key hint. If the return value is an empty byte array, the key is passed the last range and scanning should end
private JPanel createPhotoframe(){ JPanel pf=NPComponentUtils.createPanel_root(NPIconFactory.getInstance().getPhotoframeBg(),new Insets(13,15,15,15)); pf.setLayout(new BorderLayout()); pf.setOpaque(false); return pf; }
Create and return a new photo frame pane object. Its background is NinePatch pictrue.
@SuppressWarnings("deprecation") void insertIntoHoveringConnection(final Operator operator){ OutputPort hoveringConnectionSource=model.getHoveringConnectionSource(); if (hoveringConnectionSource == null) { return; } InputPort oldDest=hoveringConnectionSource.getDestination(); oldDest.lock(); hoveringConnectionSource.lock(); try { InputPort bestInputPort=null; MetaData md=hoveringConnectionSource.getMetaData(); if (md != null) { for ( InputPort inCandidate : operator.getInputPorts().getAllPorts()) { if (!inCandidate.isConnected() && inCandidate.isInputCompatible(md,CompatibilityLevel.PRE_VERSION_5)) { bestInputPort=inCandidate; break; } } } else { for ( InputPort inCandidate : operator.getInputPorts().getAllPorts()) { if (!inCandidate.isConnected()) { bestInputPort=inCandidate; break; } } } if (bestInputPort != null) { hoveringConnectionSource.disconnect(); connect(hoveringConnectionSource,bestInputPort); if (RapidMinerGUI.getMainFrame().VALIDATE_AUTOMATICALLY_ACTION.isSelected()) { hoveringConnectionSource.getPorts().getOwner().getOperator().transformMetaData(); operator.transformMetaData(); } OutputPort bestOutput=null; for ( OutputPort outCandidate : operator.getOutputPorts().getAllPorts()) { if (!outCandidate.isConnected()) { md=outCandidate.getMetaData(); if (md != null && oldDest.isInputCompatible(md,CompatibilityLevel.PRE_VERSION_5)) { bestOutput=outCandidate; break; } } } if (bestOutput == null) { for ( OutputPort outCandidate : operator.getOutputPorts().getAllPorts()) { if (!outCandidate.isConnected()) { bestOutput=outCandidate; break; } } } if (bestOutput != null) { connect(bestOutput,oldDest); } } } finally { oldDest.unlock(); hoveringConnectionSource.unlock(); model.setHoveringConnectionSource(null); } }
Insert the specified operator into the currently hovered connection.
protected void unhandledMessageReceived(OFMessage m){ switchManagerCounters.unhandledMessage.increment(); if (log.isDebugEnabled()) { String msg=getSwitchStateMessage(m,"Ignoring unexpected message"); log.debug(msg); } }
We have an OFMessage we didn't expect given the current state and we want to ignore the message
public static int sanitizeInt(int flags){ if (((flags & OFMatch.OFPFW_NW_SRC_MASK) >> OFMatch.OFPFW_NW_SRC_SHIFT) > 32) { flags=(flags & ~OFMatch.OFPFW_NW_SRC_MASK) | OFMatch.OFPFW_NW_SRC_ALL; } if (((flags & OFMatch.OFPFW_NW_DST_MASK) >> OFMatch.OFPFW_NW_DST_SHIFT) > 32) { flags=(flags & ~OFMatch.OFPFW_NW_DST_MASK) | OFMatch.OFPFW_NW_DST_ALL; } return flags; }
return the OpenFlow 'wire' integer representation of these wildcards. Sanitize nw_src and nw_dst to be max. 32 (values > 32 are technically possible, but don't make semantic sense)
public ToHitData(TargetRollModifier targetRollModifier){ this(targetRollModifier.getValue(),targetRollModifier.getDesc()); }
Construct with a target roll modifier right off the bat.
@Override public void testSendReceive() throws Exception { super.testSendReceive(); messages.clear(); consumer2.setMessageListener(this); assertMessagesAreReceived(); LOG.info("" + data.length + " messages(s) received, closing down connections"); }
Test if all the messages sent are being received.
public void changeState(boolean newState){ if (log.isDebugEnabled()) { log.debug("Change state to " + newState); } isOn=newState; this.setSelected(isOn); for (int i=0; i < listeners.size(); i++) { listeners.get(i).notifyFunctionStateChanged(identity,isOn); } }
Change the state of the function.
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case ExpressionsPackage.SHIFT_EXPRESSION__LEFT_OPERAND: return getLeftOperand(); case ExpressionsPackage.SHIFT_EXPRESSION__OPERATOR: return getOperator(); case ExpressionsPackage.SHIFT_EXPRESSION__RIGHT_OPERAND: return getRightOperand(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
@Override public String toString(){ String result=toString; if (result == null) { result=computeToString(); toString=result; } return result; }
Returns the string representation of this media type in the format described in <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
public static Border createBevelBorder(int type,Color highlightOuter,Color highlightInner,Color shadowOuter,Color shadowInner){ return new BevelBorder(type,highlightOuter,highlightInner,shadowOuter,shadowInner); }
Creates a beveled border of the specified type, using the specified colors for the inner and outer highlight and shadow areas.
public boolean canUserModifyEntry(User user,Entry entry,boolean isAdmin){ return canUserSeeEntry(user,entry,isAdmin); }
API method. Checks if the user is entitled to modify the entry.
public Shape3DPortrayal3D(Geometry geometry,Appearance appearance){ this(new Shape3D(geometry),appearance); }
Constructs a Shape3DPortrayal3D with the given geometry and appearance.
public MessageProducer createProducer(Session session,Destination destination) throws JMSException { MessageProducer producer=session.createProducer(destination); producer.setDeliveryMode(deliveryMode); return producer; }
Creates a producer.
public static AppEventsLogger newLogger(Context context){ return new AppEventsLogger(context,null,null); }
Build an AppEventsLogger instance to log events through. The Facebook app that these events are targeted at comes from this application's metadata. The application ID used to log events will be determined from the app ID specified in the package metadata.
private boolean haveShownMessageBefore(UpdateMessage msg){ if (!msg.isShownOnce()) return false; loadSeenMessages(); if (_seenMessages == null || _seenMessages.size() == 0 || !_seenMessages.contains(msg)) { if (_seenMessages == null) _seenMessages=new HashSet<>(); _seenMessages.add(msg); saveSeenMessages(); return false; } return true; }
Checks on a Message map, if we've seen this message before. The message map is serialized on disk every time we write to it. Its initialized from disk when we start the Update Manager.
public <T>JsonArray<T> createListDtoFromJson(String json,Class<T> dtoInterface){ final DtoProvider<T> dtoProvider=getDtoProvider(dtoInterface); final List<JsonElement> list=gson.fromJson(json,listTypeCache.getUnchecked(JsonElement.class)); final List<T> result=new ArrayList<>(list.size()); for ( JsonElement e : list) { result.add(dtoProvider.fromJson(e)); } return new JsonArrayImpl<>(result); }
Parses the JSON data from the specified sting into list of objects of the specified type.
public boolean isSetHeader(){ return this.header != null; }
Returns true if field header is set (has been assigned a value) and false otherwise
private void updateProgress(String progressLabel,int progress){ if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) { myHost.updateProgress(progressLabel,progress); } previousProgress=progress; previousProgressLabel=progressLabel; }
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
public SimpleProtein(String ac,String id,String name,int length,String md5,String crc64,boolean isProteinFragment){ this.ac=ac; this.id=id; this.name=name; this.length=length; this.md5=md5; this.crc64=crc64; this.taxId=null; this.taxScienceName=null; this.taxFullName=null; this.isProteinFragment=isProteinFragment; }
Construct a SimpleProtein without the taxonomy information.
public VfsStream(){ }
Create an empty VfsStream.
public synchronized Map<String,Class<T>> compile(final Map<String,CharSequence> classes,final DiagnosticCollector<JavaFileObject> diagnosticsList) throws CharSequenceCompilerException { List<JavaFileObject> sources=new ArrayList<>(); for ( Map.Entry<String,CharSequence> entry : classes.entrySet()) { String qualifiedClassName=entry.getKey(); CharSequence javaSource=entry.getValue(); if (javaSource != null) { final int dotPos=qualifiedClassName.lastIndexOf('.'); final String className=dotPos == -1 ? qualifiedClassName : qualifiedClassName.substring(dotPos + 1); final String packageName=dotPos == -1 ? "" : qualifiedClassName.substring(0,dotPos); final JavaFileObjectImpl source=new JavaFileObjectImpl(className,javaSource); sources.add(source); javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH,packageName,className + JAVA_EXTENSION,source); } } final JavaCompiler.CompilationTask task=compiler.getTask(null,javaFileManager,diagnostics,options,null,sources); final Boolean result=task.call(); if (result == null || !result) { StringBuilder cause=new StringBuilder("\n"); for ( Diagnostic d : diagnostics.getDiagnostics()) { cause.append(d).append(" "); } throw new CharSequenceCompilerException("Compilation failed. Causes: " + cause,classes.keySet(),diagnostics); } try { Map<String,Class<T>> compiled=new HashMap<>(); for ( String qualifiedClassName : classLoader.classNames()) { final Class<T> newClass=loadClass(qualifiedClassName); compiled.put(qualifiedClassName,newClass); } return compiled; } catch ( ClassNotFoundException|SecurityException|IllegalArgumentException e) { throw new CharSequenceCompilerException(classes.keySet(),e,diagnostics); } }
Compile multiple Java source strings and return a Map containing the resulting classes. <p/> Thread safety: this method is thread safe if the <var>classes</var> and <var>diagnosticsList</var> are isolated to this thread.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:38:00.428 -0500",hash_original_method="C7335716F5A5FE392DFA727356C682DF",hash_generated_method="A329A8E4FAEC9FF6A4525B62EAF0DCD3") public void addOptionHandler(TelnetOptionHandler opthand) throws InvalidTelnetOptionException { super.addOptionHandler(opthand); }
Registers a new TelnetOptionHandler for this telnet client to use. <p>
public StateMachineConfigurationBuilder(){ super(); }
Instantiates a new state machine configuration builder.
public RowSetEvent(RowSet source){ super(source); }
Constructs a <code>RowSetEvent</code> object initialized with the given <code>RowSet</code> object.
private void returnData(Object ret){ if (myHost != null) { myHost.returnData(ret); } }
Used to communicate a return object from a plugin tool to the main Whitebox user-interface.
public MoveStaticMembersDescriptor(){ super(IJavaRefactorings.MOVE_STATIC_MEMBERS); }
Creates a new refactoring descriptor.
public boolean isActivated() throws RcsGenericException { if (sAccurateLog) { Log.d(LOG_TAG,"isActivated: Request()"); } Bundle result=queryRcsStackByIntent(new Intent(Intents.Service.ACTION_GET_ACTIVATION_MODE)); boolean activated=result.getBoolean(Intents.Service.EXTRA_GET_ACTIVATION_MODE,false); if (sAccurateLog) { Log.d(LOG_TAG,"isActivated: Response() -> " + activated + " (in "+ result.getLong(TIME_SPENT,-1)+ "ms)"); } return activated; }
Returns true if the RCS stack is marked as active on the device.
public void init(boolean encrypting,byte[] key){ this.doEncrypt=encrypting; this.workingKey=key; setKey(this.workingKey); }
initialise a Blowfish cipher.
public static CTutorialDialog instance(){ return m_instance; }
Returns the globally valid instance of the tutorial dialog.
public void play(URL url,String name){ AudioClip clip=getAudioClip(url,name); if (clip != null) { clip.play(); } }
Plays the audio clip given the URL and a specifier that is relative to it. Nothing happens if the audio clip cannot be found.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:32:18.211 -0500",hash_original_method="D2E29F254410117CE819574854BB79EC",hash_generated_method="9E7D819F4E7FE83734719AA0B6321B58") public boolean removeFooterView(View v){ if (mFooterViewInfos.size() > 0) { boolean result=false; if (mAdapter != null && ((HeaderViewListAdapter)mAdapter).removeFooter(v)) { if (mDataSetObserver != null) { mDataSetObserver.onChanged(); } result=true; } removeFixedViewInfo(v,mFooterViewInfos); return result; } return false; }
Removes a previously-added footer view.
@AfterClass public static void closeTemporaryStore() throws InterruptedException { if (temporaryStore == null) { return; } ExecutorService executorService=temporaryStore.getExecutorService(); temporaryStore.close(); QueryEngine queryEngine=QueryEngineFactory.getInstance().getExistingQueryController(temporaryStore); if (queryEngine != null) { queryEngine.shutdownNow(); } SynchronizedHardReferenceQueueWithTimeout.stopStaleReferenceCleaner(); executorService.awaitTermination(20,TimeUnit.SECONDS); temporaryStore=null; }
Close the temporary store used by this test.
public static boolean isSvnBuild(){ return getBuild().equalsIgnoreCase("svn") ? true : false; }
are we a SVN version?
public void characters(char ch[],int start,int length) throws org.xml.sax.SAXException { if (!m_shouldProcess) return; XSLTElementProcessor elemProcessor=getCurrentProcessor(); XSLTElementDef def=elemProcessor.getElemDef(); if (def.getType() != XSLTElementDef.T_PCDATA) elemProcessor=def.getProcessorFor(null,"text()"); if (null == elemProcessor) { if (!XMLCharacterRecognizer.isWhiteSpace(ch,start,length)) error(XSLMessages.createMessage(XSLTErrorResources.ER_NONWHITESPACE_NOT_ALLOWED_IN_POSITION,null),null); } else elemProcessor.characters(this,ch,start,length); }
Receive notification of character data inside an element.