code
stringlengths
10
174k
nl
stringlengths
3
129k
public ImageResizer(Context context,int imageWidth,int imageHeight){ super(context); setImageSize(imageWidth,imageHeight); }
Initialize providing a single target image size (used for both width and height);
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:12.301 -0500",hash_original_method="6C44E95231996B5164D16D96A5AF9CAD",hash_generated_method="40B9E65FBFB1331A55BF5EE628C65CE7") private void nativeLoadUrl(String url,Map<String,String> headers){ addTaint(url.getTaint()); addTaint(headers.getTaint()); }
Returns false if the url is bad.
public static DecomposableMatchBuilder1<Byte,Byte> caseByte(MatchesAny b){ List<Matcher<Object>> matchers=new ArrayList<>(); matchers.add(any()); return new DecomposableMatchBuilder1<>(matchers,0,new PrimitiveFieldExtractor<>(Byte.class)); }
Matches a byte. <p>If matched, the byte value is extracted.
@Override @SideEffectFree public Object clone(){ try { Locale that=(Locale)super.clone(); return that; } catch ( CloneNotSupportedException e) { throw new InternalError(e); } }
Overrides Cloneable.
@Override public synchronized void acceptDataSet(ThresholdDataEvent e){ if (m_env == null) { m_env=Environment.getSystemWide(); } if (!GraphicsEnvironment.isHeadless()) { if (m_visPanel == null) { m_visPanel=new VisualizePanel(); } if (m_masterPlot == null) { m_masterPlot=e.getDataSet(); } try { if (!m_masterPlot.getPlotInstances().relationName().equals(e.getDataSet().getPlotInstances().relationName())) { m_masterPlot=e.getDataSet(); m_visPanel.setMasterPlot(m_masterPlot); m_visPanel.validate(); m_visPanel.repaint(); } else { m_visPanel.addPlot(e.getDataSet()); m_visPanel.validate(); m_visPanel.repaint(); } m_visPanel.setXIndex(4); m_visPanel.setYIndex(5); } catch ( Exception ex) { System.err.println("Problem setting up visualization (ModelPerformanceChart)"); ex.printStackTrace(); } } else { m_headlessEvents.add(e); } if (m_imageListeners.size() > 0 && !m_processingHeadlessEvents) { setupOffscreenRenderer(); if (m_offscreenPlotData == null || !m_offscreenPlotData.get(0).relationName().equals(e.getDataSet().getPlotInstances().relationName())) { m_offscreenPlotData=new ArrayList<Instances>(); m_thresholdSeriesTitles=new ArrayList<String>(); } m_offscreenPlotData.add(e.getDataSet().getPlotInstances()); m_thresholdSeriesTitles.add(e.getDataSet().getPlotName()); List<String> options=new ArrayList<String>(); String additional="-color=/last"; if (m_additionalOptions != null && m_additionalOptions.length() > 0) { additional=m_additionalOptions; try { additional=m_env.substitute(additional); } catch ( Exception ex) { } } String[] optsParts=additional.split(","); for ( String p : optsParts) { options.add(p.trim()); } String xAxis="False Positive Rate"; if (m_xAxis != null && m_xAxis.length() > 0) { xAxis=m_xAxis; try { xAxis=m_env.substitute(xAxis); } catch ( Exception ex) { } } String yAxis="True Positive Rate"; if (m_yAxis != null && m_yAxis.length() > 0) { yAxis=m_yAxis; try { yAxis=m_env.substitute(yAxis); } catch ( Exception ex) { } } String width=m_width; String height=m_height; int defWidth=500; int defHeight=400; try { width=m_env.substitute(width); height=m_env.substitute(height); defWidth=Integer.parseInt(width); defHeight=Integer.parseInt(height); } catch ( Exception ex) { } try { List<Instances> series=new ArrayList<Instances>(); for (int i=0; i < m_offscreenPlotData.size(); i++) { Instances temp=new Instances(m_offscreenPlotData.get(i)); temp.setRelationName(m_thresholdSeriesTitles.get(i)); series.add(temp); } BufferedImage osi=m_offscreenRenderer.renderXYLineChart(defWidth,defHeight,series,xAxis,yAxis,options); ImageEvent ie=new ImageEvent(this,osi); notifyImageListeners(ie); } catch ( Exception e1) { e1.printStackTrace(); } } }
Display a threshold curve.
@Override protected EClass eStaticClass(){ return GamlPackage.Literals.EQUATION_DEFINITION; }
<!-- begin-user-doc --> <!-- end-user-doc -->
@SuppressWarnings("unchecked") public static void matchBlockSystemPools(Object systemPools,Object dbClient,Object coordinator,Object systemId) throws Exception { List<StoragePool> modifiedPools=new ArrayList<StoragePool>(((Map<URI,StoragePool>)systemPools).values()); StringBuffer errorMessage=new StringBuffer(); matchModifiedStoragePoolsWithAllVpool(modifiedPools,(DbClient)dbClient,(CoordinatorClient)coordinator,(URI)systemId,errorMessage); }
Match block system pools with all VirtualPool. This method will be invoked only for block storage systems. This method is written as per the plugin design.
private void renewEntityCapsVersion(){ if (capsManager != null && capsManager.entityCapsEnabled()) capsManager.updateLocalEntityCaps(); }
Updates the Entity Capabilities Verification String if EntityCaps is enabled
SavedState(Parcelable superState){ super(superState); }
Called by onSaveInstanceState.
public void computeSquadronBombLoadout(){ for ( Mounted bomb : bombList) { equipmentList.remove(bomb); } bombList.clear(); for (int btype=0; btype < BombType.B_NUM; btype++) { int maxBombCount=0; for ( Integer fId : fighters) { int bombCount=0; Aero fighter=(Aero)game.getEntity(fId); ArrayList<Mounted> bombs=fighter.getBombs(); for ( Mounted m : bombs) { if (((BombType)m.getType()).getBombType() == btype) { bombCount++; } } maxBombCount=Math.max(bombCount,maxBombCount); } bombChoices[btype]=maxBombCount; } int gameTL=TechConstants.getSimpleLevel(game.getOptions().stringOption("techlevel")); for (int type=0; type < BombType.B_NUM; type++) { for (int i=0; i < bombChoices[type]; i++) { if ((type == BombType.B_ALAMO) && !game.getOptions().booleanOption("at2_nukes")) { continue; } if ((type > BombType.B_TAG) && (gameTL < TechConstants.T_SIMPLE_ADVANCED)) { continue; } if ((null != BombType.getBombWeaponName(type)) && (type != BombType.B_ARROW) && (type != BombType.B_HOMING)) { try { addBomb(EquipmentType.get(BombType.getBombWeaponName(type)),LOC_NOSE); } catch ( LocationFullException ex) { } } if ((type != BombType.B_TAG) && (null == BombType.getBombWeaponName(type))) { try { addEquipment(EquipmentType.get(BombType.getBombInternalName(type)),LOC_NOSE,false); } catch ( LocationFullException ex) { } } } bombChoices[type]=0; } if (game.getOptions().booleanOption("stratops_space_bomb") && game.getBoard().inSpace() && (getBombs(AmmoType.F_SPACE_BOMB).size() > 0)) { try { addEquipment(EquipmentType.get(SPACE_BOMB_ATTACK),LOC_NOSE,false); } catch ( LocationFullException ex) { } } if (!game.getBoard().inSpace() && (getBombs(AmmoType.F_GROUND_BOMB).size() > 0)) { try { addEquipment(EquipmentType.get(DIVE_BOMB_ATTACK),LOC_NOSE,false); } catch ( LocationFullException ex) { } for (int i=0; i < Math.min(10,getBombs(AmmoType.F_GROUND_BOMB).size()); i++) { try { addEquipment(EquipmentType.get(ALT_BOMB_ATTACK),LOC_NOSE,false); } catch ( LocationFullException ex) { } } } updateWeaponGroups(); loadAllWeapons(); }
This method looks at the bombs equipped on all the fighters in the squadron and determines what possible bombing attacks the squadrons can make. TODO: Make this into a generic "clean up bomb loadout" method
public final double correct(){ return m_Correct; }
Gets the number of instances correctly classified (that is, for which a correct prediction was made). (Actually the sum of the weights of these instances)
public void run(InterpreterContextRunner runner){ sendEvent(new RemoteInterpreterEvent(RemoteInterpreterEventType.RUN_INTERPRETER_CONTEXT_RUNNER,gson.toJson(runner))); }
Run paragraph
public PagedQuery(final String query,final QueryLanguage language,final int requestLimit,final int requestOffset){ LOGGER.debug("Query Language: {}, requestLimit: " + requestLimit + ", requestOffset: "+ requestOffset,language); LOGGER.debug("Query: {}",query); String rval=query; hasLimitAndOffset=requestLimit > 0; if (hasLimitAndOffset) { int queryLimit=-1; int queryOffset=-1; final Matcher matcher=LIMIT_OR_OFFSET.matcher(query); while (matcher.find()) { final String clause=matcher.group().toLowerCase(); final int value=Integer.parseInt(SPLITTER.split(clause)[1]); if (clause.startsWith("limit")) { if (query.indexOf('}',matcher.end()) < 0) { queryLimit=value; } } else { queryOffset=value; } } final boolean queryLimitExists=(queryLimit >= 0); final boolean queryOffsetExists=(queryOffset >= 0); final int maxQueryCount=getMaxQueryResultCount(queryLimit,queryOffset,queryLimitExists,queryOffsetExists); final int offset=(requestOffset < 0) ? 0 : requestOffset; final int maxRequestCount=requestLimit + offset; limitSubstitute=(maxRequestCount < maxQueryCount) ? requestLimit : queryLimit - offset; offsetSubstitute=queryOffsetExists ? queryOffset + offset : offset; rval=modifyLimit(language,rval,queryLimit,queryLimitExists,queryOffsetExists,limitSubstitute); rval=modifyOffset(language,offset,rval,queryOffsetExists); LOGGER.debug("Modified Query: {}",rval); } this.modifiedQuery=rval; }
<p> Creates an object that adds or modifies the limit and offset clauses of the query to be executed so that only those results to be displayed are requested from the query engine. </p> <p> Implementation note: The new object contains the user's query with appended or modified LIMIT and OFFSET clauses. </p>
public RectHV(double xmin,double ymin,double xmax,double ymax){ if (Double.isNaN(xmin) || Double.isNaN(xmax)) throw new IllegalArgumentException("x-coordinate cannot be NaN"); if (Double.isNaN(ymin) || Double.isNaN(ymax)) throw new IllegalArgumentException("y-coordinates cannot be NaN"); if (xmax < xmin || ymax < ymin) { throw new IllegalArgumentException("Invalid rectangle"); } this.xmin=xmin; this.ymin=ymin; this.xmax=xmax; this.ymax=ymax; }
Initializes a new rectangle [<em>xmin</em>, <em>xmax</em>] x [<em>ymin</em>, <em>ymax</em>].
public static List<org.oscm.vo.VOCatalogEntry> convertToApiVOCatalogEntry(List<org.oscm.internal.vo.VOCatalogEntry> oldVO){ if (oldVO == null) { return null; } List<org.oscm.vo.VOCatalogEntry> newVO=new ArrayList<org.oscm.vo.VOCatalogEntry>(); for ( org.oscm.internal.vo.VOCatalogEntry tmp : oldVO) { newVO.add(convertToApi(tmp)); } return newVO; }
Convert list of LdapProperties.
public void startCheck(){ checker=new Thread(new CheckForUpdate()); checker.setPriority(Thread.MIN_PRIORITY); checker.start(); }
Start key pair generation in a separate thread.
@Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); if (!USE_EXO_PLAYER) { videoSceneObjectPlayer=makeMediaPlayer(); } else { videoSceneObjectPlayer=makeExoPlayer(); } if (null != videoSceneObjectPlayer) { final Minimal360Video main=new Minimal360Video(videoSceneObjectPlayer); setMain(main,"gvr.xml"); } }
Called when the activity is first created.
public void updateNameOnMigrationCommit(String updatedName){ String currentPath=getPath(); setPath(currentPath.replace(getName(),updatedName)); setName(updatedName); }
Update the virtual volume name after path of the virtual volume when a migration associated with the virtual volume is committed.
public static void executeInBulk(@NotNull Document document,final boolean executeInBulk,@NotNull Runnable task){ if (!(document instanceof DocumentEx)) { task.run(); return; } DocumentEx documentEx=(DocumentEx)document; if (executeInBulk == documentEx.isInBulkUpdate()) { task.run(); return; } documentEx.setInBulkUpdate(executeInBulk); try { task.run(); } finally { documentEx.setInBulkUpdate(!executeInBulk); } }
Ensures that given task is executed when given document is at the given 'in bulk' mode.
protected Date calcSleepTime(Integer SleepSecondsAfterNotice){ if (mapping.getCondition().getSleepSecAfterAction() != null) { Calendar cal=Calendar.getInstance(); cal.setTime(new Date()); cal.add(Calendar.SECOND,SleepSecondsAfterNotice); return cal.getTime(); } else { return null; } }
Calculate sleep time point
public void tagGenerator(byte[] data) throws IOException { if (tags != null) { tags.tagGenerator(data); } }
SWFTagTypes interface
public mat4 copy(mat4 matA){ for (int i=0; i < 16; ++i) { this.m[i]=matA.m[i]; } return this; }
\fn copy \brief Copies the elements of matA to current matrix
@Override public void run(){ amIActive=true; if (args.length < 2) { showFeedback("Plugin parameters have not been set properly."); return; } String inputHeader=args[0]; String outputHeader=args[1]; if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { int row, col; double z1; int progress, oldProgress=-1; double[] data1; WhiteboxRaster inputFile1=new WhiteboxRaster(inputHeader,"r"); int rows=inputFile1.getNumberRows(); int cols=inputFile1.getNumberColumns(); double noData=inputFile1.getNoDataValue(); WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData); outputFile.setPreferredPalette(inputFile1.getPreferredPalette()); for (row=0; row < rows; row++) { data1=inputFile1.getRowValues(row); for (col=0; col < cols; col++) { z1=data1[col]; if (z1 != noData) { outputFile.setValue(row,col,z1 * z1); } else { outputFile.setValue(row,col,noData); } } progress=(int)(100f * row / (rows - 1)); if (progress != oldProgress) { oldProgress=progress; updateProgress((int)progress); if (cancelOp) { cancelOperation(); return; } } } outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); outputFile.addMetadataEntry("Created on " + new Date()); inputFile1.close(); outputFile.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
public boolean hasValue(){ return super.hasTextValue(); }
Returns whether it has the value.
private void internalRemoveConnection(String hostAndPort){ if ((hostAndPort == null) || (hostAndPort.length() == 0)) { throw new ConnectionManagerException("Passed host/port is null or blank."); } try { if (!isConnected(hostAndPort)) { throw new ConnectionManagerException(MessageFormatter.format("The connection manager is not managing a connection to host {}",hostAndPort).getMessage()); } _listener.pause(); CimConnection connection=_connections.get(hostAndPort); if (connection != null) { s_logger.info("Closing connection to the CIM provider on host/port {}",hostAndPort); connection.close(); _connections.remove(hostAndPort); connectionLastTouch.remove(hostAndPort); pinnedConnections.remove(hostAndPort); } } catch ( ConnectionManagerException e) { throw e; } catch ( Exception e) { throw new ConnectionManagerException(MessageFormatter.format("Failed removing the connection to the provider on host/port {}",hostAndPort).getMessage(),e); } finally { _listener.resume(); } }
Looks up the 'hostAndPort' connection in the map. If it exists, the underlying connection will be closed, it will be removed from the map, and related data structures will be updated.
protected void verifyObb1Contents(String filePath){ String path=null; path=doWaitForPath(filePath); doValidateIntContents(path,"OneToOneThousandInts.bin",0,1000); doValidateIntContents(path,"SevenHundredInts.bin",0,700); doValidateZeroLongFile(path,"FiveLongs.bin",5,true); }
Verifies the pre-defined contents of our first OBB (OBB_FILE_1) The OBB contains 4 files and no subdirectories
public SplitAction(DrawingEditor editor){ super(editor,new SVGPathFigure(),false); labels.configureAction(this,ID); }
Creates a new instance.
public static RSAPrivateKey newKey(byte[] encoded) throws InvalidKeyException { RSAPrivateCrtKeyImpl key=new RSAPrivateCrtKeyImpl(encoded); if (key.getPublicExponent().signum() == 0) { return new RSAPrivateKeyImpl(key.getModulus(),key.getPrivateExponent()); } else { return key; } }
Generate a new key from its encoding. Returns a CRT key if possible and a non-CRT key otherwise. Used by RSAKeyFactory.
public String cacheName(){ return cacheName; }
Gets cache name.
@Inject public AddRemoteRepositoryPresenter(AddRemoteRepositoryView view,GitServiceClient service,AppContext appContext){ this.view=view; this.view.setDelegate(this); this.service=service; this.appContext=appContext; }
Create presenter.
public double calculateLogLikelihood(){ return calculateLogLikelihood(intervals,demographicFunction); }
Calculates the log likelihood of this set of coalescent intervals, given a demographic model.
public ScVolume createReplayView(String instanceId,String name) throws StorageCenterAPIException { Parameters params=new Parameters(); params.add("Name",name); params.add("Notes",instanceId); RestResult rr=restClient.post(String.format("StorageCenter/ScReplay/%s/CreateView",instanceId),params.toJson()); if (!checkResults(rr)) { LOG.warn("Error creating view volume of replay {}: {}",instanceId,rr.getErrorMsg()); throw new StorageCenterAPIException(rr.getErrorMsg()); } return gson.fromJson(rr.getResult(),ScVolume.class); }
Create a view volume of a replay.
private ComparableTimSort(Object[] a,Object[] work,int workBase,int workLen){ this.a=a; int len=a.length; int tlen=(len < 2 * INITIAL_TMP_STORAGE_LENGTH) ? len >>> 1 : INITIAL_TMP_STORAGE_LENGTH; if (work == null || workLen < tlen || workBase + tlen > work.length) { tmp=new Object[tlen]; tmpBase=0; tmpLen=tlen; } else { tmp=work; tmpBase=workBase; tmpLen=workLen; } int stackLen=(len < 120 ? 5 : len < 1542 ? 10 : len < 119151 ? 24 : 49); runBase=new int[stackLen]; runLen=new int[stackLen]; }
Creates a TimSort instance to maintain the state of an ongoing sort.
public void handleDiscontinuity(){ if (startMediaTimeState == START_IN_SYNC) { startMediaTimeState=START_NEED_SYNC; } }
Signals to the audio track that the next buffer is discontinuous with the previous buffer.
public CLKernel createKernel(String name,Object... args) throws CLBuildException { }
#documentCallsFunction("clCreateKernel") Find a kernel by its functionName, and optionally bind some arguments to it.
public void addFooterView(View view){ if (null == view) { throw new IllegalArgumentException("the view to add must not be null!"); } else if (mWrapAdapter == null) { mTmpFooterView.add(view); } else { mWrapAdapter.addFooterView(view); } }
Adds a footer view
public T caseS_Declaration(S_Declaration object){ return null; }
Returns the result of interpreting the object as an instance of '<em>SDeclaration</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc -->
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 15:01:14.718 -0400",hash_original_method="29A8172D11EE1F6C2B41EDC469205BD4",hash_generated_method="59F81D826E94B385983D565339AE7DB1") private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { try { s.defaultReadObject(); this.queue=new Object[q.size()]; comparator=q.comparator(); addAll(q); } finally { q=null; } }
Reconstitutes this queue from a stream (that is, deserializes it).
public static OrganizationAuthorityException convertToApi(org.oscm.internal.types.exception.OrganizationAuthorityException oldEx){ return convertExceptionToApi(oldEx,OrganizationAuthorityException.class); }
Convert source version Exception to target version Exception
public static <T>void assertIterator(List<T> expected,Iterator<T> it){ assertIterator(expected,it,true); }
Asserts the contents of an iterator.
public synchronized void remove(ComponentName componentName,UserHandleCompat user){ mCache.remove(new ComponentKey(componentName,user)); }
Remove any records for the supplied ComponentName.
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:38:12.483 -0500",hash_original_method="CEA0E6C41E8B0166BD3ED01845CB7616",hash_generated_method="2A0DF62DC3D6BDA6FD332746248CC193") public int receive(byte[] data,int length) throws IOException { __receivePacket.setData(data); __receivePacket.setLength(length); _socket_.receive(__receivePacket); return __receivePacket.getLength(); }
Receives echoed data and returns its length. The data may be divided up among multiple datagrams, requiring multiple calls to receive. Also, the UDP packets will not necessarily arrive in the same order they were sent. <p>
private void checkContains(Spanned text,String[] spans,String spanName,int start,int end) throws Exception { for ( String i : spans) { if (i.equals(spanName)) { assertEquals(start,text.getSpanStart(i)); assertEquals(end,text.getSpanEnd(i)); return; } } fail(); }
Fail unless text+spans contains a span 'spanName' with the given start and end.
public CSSClassCondition(String localName,String namespaceURI,String value){ super(localName,namespaceURI,true,value); }
Creates a new CSSAttributeCondition object.
public final int length(){ return (m_lastChunk << m_chunkBits) + m_firstFree; }
Get the length of the list. Synonym for size().
@Override public float idf(long docFreq,long docCount){ return (float)(Math.log((docCount + 1) / (double)(docFreq + 1)) + 1.0); }
Implemented as <code>log((docCount+1)/(docFreq+1)) + 1</code>.
public boolean isDrawCenterTextEnabled(){ return mDrawCenterText; }
returns true if drawing the center text is enabled
public _MelLexer(java.io.Reader in){ this.zzReader=in; }
Creates a new scanner
public static <T>List<T> createUnsafeList(Collection<? extends T> collection){ List<T> list=new UnsafeArrayList<>(collection.size()); list.addAll(collection); return list; }
Construct new unsafe array list. Unsafe array lists are like array lists but doesn't check for concurrent modifications. <br> NOTE: They are not created for concurrent usage! They are not thread safe!
public void ensureCapacity(int minCapacity){ modCount++; int oldCapacity=elementData.length; if (minCapacity > oldCapacity) { Object oldData[]=elementData; int newCapacity=(oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) newCapacity=minCapacity; elementData=Arrays.copyOf(elementData,newCapacity); } }
Increases the capacity of this <tt>IdentityArrayList</tt> instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
public static int scale(float val,int max){ if (val == 1) return max - 1; return (int)(val * max); }
Return the int in the range [0,max-1] represented by the given float which is in the range [0.0,1.0).
protected void appendDetail(StringBuffer buffer,String fieldName,int[] array){ buffer.append(arrayStart); for (int i=0; i < array.length; i++) { if (i > 0) { buffer.append(arraySeparator); } appendDetail(buffer,fieldName,array[i]); } buffer.append(arrayEnd); }
<p>Append to the <code>toString</code> the detail of an <code>int</code> array.</p>
protected float parseFraction() throws ParseException, IOException { float value=0; if (current < '0' || current > '9') { reportUnexpectedCharacterError(current); } float weight=0.1f; do { value+=weight * (current - '0'); weight*=0.1f; current=reader.read(); } while (current >= '0' && current <= '9'); return value; }
Parses a '.' and a sequence of digits and returns the float.
public int readSignedExpGolombCodedInt(){ int codeNum=readExpGolombCodeNum(); return ((codeNum % 2) == 0 ? -1 : 1) * ((codeNum + 1) / 2); }
Reads an signed Exp-Golomb-coded format integer.
@SuppressWarnings({"unchecked","rawtypes"}) public TableViewerColumn build(){ TableViewerColumn viewerColumn=new TableViewerColumn(builder.getTableViewer(),style); TableColumn column=viewerColumn.getColumn(); column.setText(headerText); column.setMoveable(moveable); column.setResizable(resizable); column.setToolTipText(toolTipText); if (cellLabelProvider != null) { viewerColumn.setLabelProvider(cellLabelProvider); } else { if (propertyName == null) { viewerColumn.setLabelProvider(new ColumnLabelProvider()); } else { PropertyDescriptor descriptor=builder.getPropertyDescriptor(propertyName); viewerColumn.setLabelProvider(new PropertyCellLabelProvider(descriptor,valueFormatter)); } } if (widthPixel != null && widthPercent != null) { throw new IllegalArgumentException("Cannot specify a width both in pixel and in percent!"); } if (widthPercent == null) { builder.getTableLayout().setColumnData(column,new ColumnPixelData(widthPixel == null ? 100 : widthPixel)); } else { builder.getTableLayout().setColumnData(column,new ColumnWeightData(widthPercent)); } if (editingSupport != null) { viewerColumn.setEditingSupport(editingSupport); } return viewerColumn; }
Builds the column and returns the TableViewerColumn
public void benchHasChildMatchAll(){ TermsByQueryRequestBuilder stringFilter=this.newTermsByQueryRequestBuilder(); stringFilter.setIndices(CHILD_INDEX).setTypes(CHILD_TYPE).setField("pid").setTermsEncoding(TermsByQueryRequest.TermsEncoding.LONG); TermsByQueryRequestBuilder longFilter=this.newTermsByQueryRequestBuilder(); longFilter.setIndices(CHILD_INDEX).setTypes(CHILD_TYPE).setField("num").setTermsEncoding(TermsByQueryRequest.TermsEncoding.LONG); long tookString=0; long tookLong=0; long expected=NUM_PARENTS; warmFieldData("id","pid"); warmFieldData("num","num"); log("==== HAS CHILD MATCH-ALL ===="); for (int i=0; i < NUM_QUERIES; i++) { tookString+=runQuery("string",i,expected,stringFilter); tookLong+=runQuery("long",i,expected,longFilter); } log("string: " + (tookString / NUM_QUERIES) + "ms avg"); log("long : " + (tookLong / NUM_QUERIES) + "ms avg"); log(""); }
Search for parent documents that have any child. Expect all parent documents returned. <p/> Parent string field = "id" Parent long field = "num" Child string field = "pid" Child long field = "num"
private static int capacityForInitSize(int size){ int result=(size >> 1) + size; return (result & ~(MAXIMUM_CAPACITY - 1)) == 0 ? result : MAXIMUM_CAPACITY; }
Returns an appropriate capacity for the specified initial size. Does not round the result up to a power of two; the caller must do this! The returned value will be between 0 and MAXIMUM_CAPACITY (inclusive).
public LogStream print(long l){ if (ps != null) { indent(); lineBuffer.append(l); } return this; }
Writes a long value to this stream.
public static byte[] fromBase64(String input){ return new Base64().decode(input); }
Converts a Base64-String to binary.
public static void d(String tag,String msg,Throwable tr){ println(DEBUG,tag,msg,tr); }
Prints a message at DEBUG priority.
public int bitsLeft(){ return (byteLimit - byteOffset) * 8 - bitOffset; }
Returns the number of bits yet to be read.
public static Formatter of(String message,Object... objects){ return new Formatter(message,objects); }
Factory method.
public SendablePhotoMessage.SendablePhotoMessageBuilder replyMarkup(ReplyMarkup replyMarkup){ this.replyMarkup=replyMarkup; return this; }
*Optional Sets the ReplyMarkup that you want to send with the message
public ElasticSearchTransportClient(ElasticSearchIndexRequestBuilderFactory indexBuilderFactory){ this.indexRequestBuilderFactory=indexBuilderFactory; openLocalDiscoveryClient(); }
Local transport client only for testing
public static void main(String... a) throws Exception { TestBase.createCaller().init().test(); }
Run just this test.
public DeleteWarmerRequest(String... names){ names(names); }
Constructs a new delete warmer request for the specified name.
@Override public void run(){ amIActive=true; String inputHeader=null; String outputHeader=null; int row, col, x, y; double z; float progress=0; int a; int filterSizeX=3; int filterSizeY=3; double n; double sum; int[] dX; int[] dY; int midPointX; int midPointY; int numPixelsInFilter; boolean filterRounded=false; double[] filterShape; boolean reflectAtBorders=false; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } for (int i=0; i < args.length; i++) { if (i == 0) { inputHeader=args[i]; } else if (i == 1) { outputHeader=args[i]; } else if (i == 2) { filterSizeX=Integer.parseInt(args[i]); } else if (i == 3) { filterSizeY=Integer.parseInt(args[i]); } else if (i == 4) { filterRounded=Boolean.parseBoolean(args[i]); } else if (i == 5) { reflectAtBorders=Boolean.parseBoolean(args[i]); } } if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster inputFile=new WhiteboxRaster(inputHeader,"r"); inputFile.isReflectedAtEdges=reflectAtBorders; int rows=inputFile.getNumberRows(); int cols=inputFile.getNumberColumns(); double noData=inputFile.getNoDataValue(); WhiteboxRaster outputFile=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,noData); outputFile.setPreferredPalette(inputFile.getPreferredPalette()); if (Math.floor(filterSizeX / 2d) == (filterSizeX / 2d)) { showFeedback("Filter dimensions must be odd numbers. The specified filter x-dimension" + " has been modified."); filterSizeX++; } if (Math.floor(filterSizeY / 2d) == (filterSizeY / 2d)) { showFeedback("Filter dimensions must be odd numbers. The specified filter y-dimension" + " has been modified."); filterSizeY++; } numPixelsInFilter=filterSizeX * filterSizeY; dX=new int[numPixelsInFilter]; dY=new int[numPixelsInFilter]; filterShape=new double[numPixelsInFilter]; midPointX=(int)Math.floor(filterSizeX / 2); midPointY=(int)Math.floor(filterSizeY / 2); if (!filterRounded) { a=0; for (row=0; row < filterSizeY; row++) { for (col=0; col < filterSizeX; col++) { dX[a]=col - midPointX; dY[a]=row - midPointY; filterShape[a]=1; a++; } } } else { double aSqr=midPointX * midPointX; double bSqr=midPointY * midPointY; a=0; for (row=0; row < filterSizeY; row++) { for (col=0; col < filterSizeX; col++) { dX[a]=col - midPointX; dY[a]=row - midPointY; z=(dX[a] * dX[a]) / aSqr + (dY[a] * dY[a]) / bSqr; if (z > 1) { filterShape[a]=0; } else { filterShape[a]=1; } a++; } } } for (row=0; row < rows; row++) { for (col=0; col < cols; col++) { z=inputFile.getValue(row,col); if (z != noData) { n=0; sum=0; for (a=0; a < numPixelsInFilter; a++) { x=col + dX[a]; y=row + dY[a]; z=inputFile.getValue(y,x); if (z != noData) { n+=filterShape[a]; sum+=z * filterShape[a]; } } if (n > 0) { outputFile.setValue(row,col,sum / n); } else { outputFile.setValue(row,col,noData); } } else { outputFile.setValue(row,col,noData); } } if (cancelOp) { cancelOperation(); return; } progress=(float)(100f * row / (rows - 1)); updateProgress((int)progress); } outputFile.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); outputFile.addMetadataEntry("Created on " + new Date()); inputFile.close(); outputFile.close(); returnData(outputHeader); } catch ( OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch ( Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(),e); } finally { updateProgress("Progress: ",0); amIActive=false; myHost.pluginComplete(); } }
Used to execute this plugin tool.
protected POInfo initPO(Properties ctx){ POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName()); return poi; }
Load Meta Data
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.
private void addExposedTypes(GenericArrayType type,Class<?> cause){ if (done(type)) { return; } visit(type); logger.debug("Adding exposed types from {}, which is the component type on generic array type {}",type.getGenericComponentType(),type); addExposedTypes(type.getGenericComponentType(),cause); }
Adds any types exposed from the given array type. The array type itself is not added. The cause of the exposure of the underlying type is considered whatever type exposed the array type.
public boolean equalsDefault(){ return false; }
Check if the expression is equal to its default static value
public Boolean isMemoryHotAddEnabled(){ return memoryHotAddEnabled; }
Gets the value of the memoryHotAddEnabled property.
public Set(Class<?> type,String name){ super(type,type); this.name=name; }
Constructs a new node for assigning the value of a named variable within the current scope.
public static int readInt(){ return scanner.nextInt(); }
Reads the next token from standard input, parses it as an integer, and returns the integer.
public static void deviceBind(Context context,String accessToken,String deviceKey,AsyncHttpResponseHandler responseHandler){ List<Header> headerList=new ArrayList<Header>(); headerList.add(new BasicHeader(ApiKey.HeadKey.ACCESS_TOKEN,accessToken)); try { String jsonParams=new JSONStringer().object().key(ApiKey.DEVICE_KEY).value(deviceKey).endObject().toString(); if (DEBUG) { LogUtils.d(jsonParams); } post(context,getApiServerUrl() + DEVICE_BINDING,headerList,jsonParams,responseHandler); } catch ( JSONException e) { e.printStackTrace(); responseHandler.onFailure(INNER_ERROR_CODE,null,null,e); } catch ( UnsupportedEncodingException e) { e.printStackTrace(); responseHandler.onFailure(INNER_ERROR_CODE,null,null,e); } }
device binding(/v1/devices/binding) bind device
public void snapshotAfter(){ after=new HeapSnapshot(); }
Take a snapshot of the heap after collection
public void createMonthScenarioParAndUserAssignChange() throws Exception { BillingIntegrationTestBase.setDateFactoryInstance("2013-02-04 12:00:00"); VOServiceDetails serviceDetails=serviceSetup.createPublishAndActivateMarketableService(basicSetup.getSupplierAdminKey(),"PARCHARGE_PU_MONTH_ASSIGN",TestService.EXAMPLE,TestPriceModel.EXAMPLE_PERUNIT_MONTH_ROLES_PARS,technicalService,supplierMarketplace); setCutOffDay(basicSetup.getSupplierAdminKey(),1); VORoleDefinition role=VOServiceFactory.getRole(serviceDetails,"USER"); container.login(basicSetup.getCustomerAdminKey(),ROLE_ORGANIZATION_ADMIN); VOSubscriptionDetails subDetails=subscrSetup.subscribeToService("PARCHARGE_PU_MONTH_ASSIGN",serviceDetails,basicSetup.getCustomerUser1(),role); subDetails=subscrSetup.modifyParameterForSubscription(subDetails,DateTimeHandling.calculateMillis("2013-02-11 12:00:00"),"MAX_FOLDER_NUMBER","4"); BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-02-13 06:00:00")); subDetails=subscrSetup.revokeUser(basicSetup.getCustomerUser1(),subDetails.getSubscriptionId()); BillingIntegrationTestBase.setDateFactoryInstance(DateTimeHandling.calculateMillis("2013-02-15 00:00:00")); subDetails=subscrSetup.addUser(basicSetup.getCustomerUser1(),VOServiceFactory.getRole(serviceDetails,"GUEST"),subDetails.getSubscriptionId()); subDetails=subscrSetup.modifyParameterForSubscription(subDetails,DateTimeHandling.calculateMillis("2013-02-22 00:00:00"),"MAX_FOLDER_NUMBER","88"); BillingIntegrationTestBase.setDateFactoryInstance("2013-02-25 12:00:00"); subscrSetup.unsubscribeToService(subDetails.getSubscriptionId()); resetCutOffDay(basicSetup.getSupplierAdminKey()); BillingIntegrationTestBase.updateSubscriptionListForTests("PARCHARGE_PU_MONTH_ASSIGN",subDetails); }
A customer subscribes to a service and terminates the subscription within a time unit. The value of a parameter is changed several times in the time unit. In addition the assigned user is deassigned and reassigned with a different role in the time unit. The parameter fees are charged in a "pro rata" way. See example 3 in requirement http://wwwi.est.fujitsu.com/confluence/x/4I7H
public Insert columns(Property<?>... columns){ for ( Property<?> column : columns) { this.columns.add(column.getExpression()); } defaultValues=false; invalidateCompileCache(); return this; }
Specify columns to insert into
public static <A,V extends MonadicValue<? extends Observable<A>>>ObservableTValue<A> fromValue(final V monadicValue){ return of(AnyM.ofValue(monadicValue)); }
Construct an ObservableTValue by wrapping the supplied MonadValue which contains an Observable
public static DictionarySelector createVectorDictionaryEditor(JPanel scalarPanel,JPanel vectorPanel){ DictionarySelector editor=new DictionarySelector(scalarPanel,vectorPanel); editor.addButton(new JButton(new ShowHelpAction("Pages/Worlds/TextWorld/TextWorld.html"))); editor.setMinimumSize(new Dimension(300,400)); return editor; }
Factory method to create the editor.
public TenantDeletionConstraintException(String message,ApplicationExceptionBean bean){ super(message,bean); }
Constructs a new exception with the specified detail message and bean for JAX-WS exception serialization.
public void addStateValueAsBoolean(String name,boolean booleanValue){ addStateValueAsBoolean(null,name,booleanValue); }
Adds a new StateObject with the specified <code>name</code> and Boolean <code>value</code>. The new StateObject is placed beneath the document root. If a StateObject with this name already exists, a new one is still created.
final long fn(long v,long x){ return v + x; }
Version of plus for use in retryUpdate
static Class lookUpFactoryClass(String factoryId,String propertiesFilename,String fallbackClassName) throws ConfigurationError { String factoryClassName=lookUpFactoryClassName(factoryId,propertiesFilename,fallbackClassName); ClassLoader cl=findClassLoader(); if (factoryClassName == null) { factoryClassName=fallbackClassName; } try { Class providerClass=findProviderClass(factoryClassName,cl,true); debugPrintln("created new instance of " + providerClass + " using ClassLoader: "+ cl); return providerClass; } catch ( ClassNotFoundException x) { throw new ConfigurationError("Provider " + factoryClassName + " not found",x); } catch ( Exception x) { throw new ConfigurationError("Provider " + factoryClassName + " could not be instantiated: "+ x,x); } }
Finds the implementation Class object in the specified order. The specified order is the following: <ol> <li>query the system property using <code>System.getProperty</code> <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file <li>read <code>META-INF/services/<i>factoryId</i></code> file <li>use fallback classname </ol>
private long tryDecReaderOverflow(long s){ if ((s & ABITS) == RFULL) { if (U.compareAndSwapLong(this,STATE,s,s | RBITS)) { int r; long next; if ((r=readerOverflow) > 0) { readerOverflow=r - 1; next=s; } else next=s - RUNIT; state=next; return next; } } else if ((LockSupport.nextSecondarySeed() & OVERFLOW_YIELD_RATE) == 0) Thread.yield(); return 0L; }
Tries to decrement readerOverflow.
@Override public void draw(Object object,Graphics2D graphics,DrawInfo2D info){ GeomInfo2D gInfo; if (info instanceof GeomInfo2D) { gInfo=(GeomInfo2D)info; } else { gInfo=new GeomInfo2D(info,new AffineTransform()); } MasonGeometry gm=(MasonGeometry)object; Geometry geometry=gm.getGeometry(); if (geometry.isEmpty()) { return; } if (paint != null) { graphics.setPaint(paint); } if ((gm.isMovable) || (gm.shape == null) || (!gm.transform.equals(gInfo.transform))) { gm.transform.setTransform(gInfo.transform); if (geometry instanceof Point) { Point point=(Point)geometry; double offset=3 * scale / 2.0; Ellipse2D.Double ellipse=new Ellipse2D.Double(point.getX() - offset,point.getY() - offset,3 * scale,3 * scale); GeneralPath path=(GeneralPath)(new GeneralPath(ellipse).createTransformedShape(gInfo.transform)); gm.shape=path; } else if (geometry instanceof LineString) { gm.shape=drawGeometry(geometry,gInfo,false); filled=false; } else if (geometry instanceof Polygon) { gm.shape=drawPolygon((Polygon)geometry,gInfo,filled); } else if (geometry instanceof MultiLineString) { MultiLineString multiLine=(MultiLineString)geometry; for (int i=0; i < multiLine.getNumGeometries(); i++) { GeneralPath p=drawGeometry(multiLine.getGeometryN(i),gInfo,false); if (i == 0) { gm.shape=p; } else { gm.shape.append(p,false); } } filled=false; } else if (geometry instanceof MultiPolygon) { MultiPolygon multiPolygon=(MultiPolygon)geometry; for (int i=0; i < multiPolygon.getNumGeometries(); i++) { GeneralPath p=drawPolygon((Polygon)multiPolygon.getGeometryN(i),gInfo,filled); if (i == 0) { gm.shape=p; } else { gm.shape.append(p,false); } } } else { throw new UnsupportedOperationException("Unsupported JTS type for draw()" + geometry); } } if (filled) { graphics.fill(gm.shape); } else { graphics.draw(gm.shape); } }
Draw a JTS geometry object. The JTS geometries are converted to Java general path objects, which are then drawn using the native Graphics2D methods.
public SetShuffle(int playerId,boolean shuffle){ super(); addParameterToRequest("playerid",playerId); addParameterToRequest("shuffle",shuffle); }
Shuffle/Unshuffle items in the player
@Override public Object eGet(int featureID,boolean resolve,boolean coreType){ switch (featureID) { case UmplePackage.ANONYMOUS_NUM_EXPR_1__TAIL_1: return getTail_1(); } return super.eGet(featureID,resolve,coreType); }
<!-- begin-user-doc --> <!-- end-user-doc -->
private void switchOverToHash(int numAtts){ for (int index=0; index < numAtts; index++) { String qName=super.getQName(index); Integer i=new Integer(index); m_indexFromQName.put(qName,i); String uri=super.getURI(index); String local=super.getLocalName(index); m_buff.setLength(0); m_buff.append('{').append(uri).append('}').append(local); String key=m_buff.toString(); m_indexFromQName.put(key,i); } }
We are switching over to having a hash table for quick look up of attributes, but up until now we haven't kept any information in the Hashtable, so we now update the Hashtable. Future additional attributes will update the Hashtable as they are added.
@Deprecated @Override public final void remove(){ throw new UnsupportedOperationException(); }
Guaranteed to throw an exception and leave the underlying data unmodified.
public static List<HttpCookie> parse(String header){ return new CookieParser(header).parse(); }
Constructs a cookie from a string. The string should comply with set-cookie or set-cookie2 header format as specified in <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>. Since set-cookies2 syntax allows more than one cookie definitions in one header, the returned object is a list.
public void addExtension(ASN1ObjectIdentifier oid,boolean critical,byte[] value){ if (extensions.containsKey(oid)) { throw new IllegalArgumentException("extension " + oid + " already added"); } extOrdering.addElement(oid); extensions.put(oid,new X509Extension(critical,new DEROctetString(value))); }
Add an extension with the given oid and the passed in byte array to be wrapped in the OCTET STRING associated with the extension.
public boolean isCancelled(){ return cancelled; }
Returns true if the operation is being cancelled.
public Function build(Class<?> cls){ EdmFunction edmFunction=cls.getAnnotation(EdmFunction.class); EdmReturnType edmReturnType=cls.getAnnotation(EdmReturnType.class); if (edmReturnType == null) { throw new IllegalArgumentException("The class must have EdmReturnType: " + cls.getName()); } Set<Parameter> parameters=new HashSet<>(); for ( Field field : cls.getDeclaredFields()) { EdmParameter parameterAnnotation=field.getAnnotation(EdmParameter.class); if (parameterAnnotation != null) { String parameterName=isNullOrEmpty(parameterAnnotation.name()) ? field.getName() : parameterAnnotation.name(); String parameterType=isNullOrEmpty(parameterAnnotation.type()) ? field.getType().getSimpleName() : parameterAnnotation.type(); parameters.add(new ParameterImpl.Builder().setMaxLength(parameterAnnotation.maxLength()).setName(parameterName).setNullable(parameterAnnotation.nullable()).setPrecision(parameterAnnotation.precision()).setScale(parameterAnnotation.scale()).setSRID(parameterAnnotation.srid()).setType(parameterType).setUnicode(parameterAnnotation.unicode()).setJavaField(field).build()); } } return new FunctionImpl.Builder().setBound(edmFunction.isBound()).setComposable(edmFunction.isComposable()).setEntitySetPath(edmFunction.entitySetPath()).setName(edmFunction.name()).setParameters(parameters).setReturnType(edmReturnType.type()).setNamespace(edmFunction.namespace()).setJavaClass(cls).build(); }
Method to build Function implementation with parameters by class.
public static void finishStartingService(Service service,int startId){ synchronized (mStartingServiceSync) { if (mStartingService != null) { if (service.stopSelfResult(startId)) { mStartingService.release(); } } } }
Called back by the service when it has finished processing notifications, releasing the wake lock if the service is now stopping.
public void copyUTF8Bytes(BytesRef bytes){ copyUTF8Bytes(bytes.bytes,bytes.offset,bytes.length); }
Copy the provided bytes, interpreted as UTF-8 bytes.
public void accept(final ClassVisitor cv){ FieldVisitor fv=cv.visitField(access,name,desc,signature,value); if (fv == null) { return; } int i, n; n=visibleAnnotations == null ? 0 : visibleAnnotations.size(); for (i=0; i < n; ++i) { AnnotationNode an=visibleAnnotations.get(i); an.accept(fv.visitAnnotation(an.desc,true)); } n=invisibleAnnotations == null ? 0 : invisibleAnnotations.size(); for (i=0; i < n; ++i) { AnnotationNode an=invisibleAnnotations.get(i); an.accept(fv.visitAnnotation(an.desc,false)); } n=visibleTypeAnnotations == null ? 0 : visibleTypeAnnotations.size(); for (i=0; i < n; ++i) { TypeAnnotationNode an=visibleTypeAnnotations.get(i); an.accept(fv.visitTypeAnnotation(an.typeRef,an.typePath,an.desc,true)); } n=invisibleTypeAnnotations == null ? 0 : invisibleTypeAnnotations.size(); for (i=0; i < n; ++i) { TypeAnnotationNode an=invisibleTypeAnnotations.get(i); an.accept(fv.visitTypeAnnotation(an.typeRef,an.typePath,an.desc,false)); } n=attrs == null ? 0 : attrs.size(); for (i=0; i < n; ++i) { fv.visitAttribute(attrs.get(i)); } fv.visitEnd(); }
Makes the given class visitor visit this field.
public static void debug(Object message){ RuntimeSingleton.debug(message); }
Log a debug message.
@Command(description="Deletes a key") public void deleteKey(@Param(name="keyId",description="Key ID") String keyId) throws Exception { Map<String,Object> logData=new LinkedHashMap<>(); logData.put(KEY_ID_PARAM,keyId); try { SignerClient.execute(new DeleteKey(keyId,true)); AuditLogger.log(DELETE_THE_KEY_EVENT,XROAD_USER,logData); } catch ( Exception e) { AuditLogger.log(DELETE_THE_KEY_EVENT,XROAD_USER,e.getMessage(),logData); throw e; } }
Deletes a key.
public static byte[] toMACAddress(String macAddress){ return MACAddress.valueOf(macAddress).toBytes(); }
Accepts a MAC address of the form 00:aa:11:bb:22:cc, case does not matter, and returns a corresponding byte[].