code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
|---|---|
public static long tpsToTpw(OperatorContext context,long tuplesPerSecond){
Preconditions.checkArgument(tuplesPerSecond > 0);
BigDecimal tuplesPerWindow=new BigDecimal(getAppWindowDurationMs(context));
tuplesPerWindow=tuplesPerWindow.divide(new BigDecimal(1000));
tuplesPerWindow=tuplesPerWindow.multiply(new BigDecimal(tuplesPerSecond));
Preconditions.checkArgument(tuplesPerWindow.compareTo(new BigDecimal(Long.MAX_VALUE)) <= 0,"Overflow computing tuples per window.");
tuplesPerWindow=tuplesPerWindow.stripTrailingZeros();
long tuplesPerWindowLong=tuplesPerWindow.longValue();
if (tuplesPerWindow.scale() > 0) {
LOG.debug("{}",tuplesPerWindow);
tuplesPerWindowLong++;
}
return tuplesPerWindowLong;
}
|
Converts tuples per second into tuples per application window. The value for tuples per application window is rounded up.
|
private void stopDrag(MotionEvent ev){
mTouchMode=TOUCH_MODE_IDLE;
boolean commitChange=ev.getAction() == MotionEvent.ACTION_UP && isEnabled();
cancelSuperTouch(ev);
if (commitChange) {
boolean newState;
mVelocityTracker.computeCurrentVelocity(1000);
float xvel=mVelocityTracker.getXVelocity();
if (Math.abs(xvel) > mMinFlingVelocity) {
newState=isLayoutRtl() ? (xvel < 0) : (xvel > 0);
}
else {
newState=getTargetCheckedState();
}
animateThumbToCheckedState(newState);
}
else {
animateThumbToCheckedState(isChecked());
}
}
|
Called from onTouchEvent to end a drag operation.
|
public SelectUndirectedAction(GraphWorkbench workbench){
super("Highlight Undirected Edges");
if (workbench == null) {
throw new NullPointerException("Desktop must not be null.");
}
this.workbench=workbench;
}
|
Creates a new copy subsession action for the given desktop and clipboard.
|
public boolean hasValue(){
return getValue() != null;
}
|
Returns whether it has the value.
|
public boolean isSecure(){
return secure;
}
|
Returns the security state of this <tt>ResourceAccessRequest</tt>.
|
public JSONObject putOpt(String key,Object value) throws JSONException {
if (key != null && value != null) {
this.put(key,value);
}
return this;
}
|
Put a key/value pair in the JSONObject, but only if the key and the value are both non-null.
|
void onSourcesChanged(SsaInsn insn,RegisterSpecList oldSources){
if (useList == null) return;
if (oldSources != null) {
removeFromUseList(insn,oldSources);
}
RegisterSpecList sources=insn.getSources();
int szNew=sources.size();
for (int i=0; i < szNew; i++) {
int reg=sources.get(i).getReg();
useList[reg].add(insn);
}
}
|
Updates the use list for a source list change.
|
public Kit(Context context){
Kit.context=context.getApplicationContext();
}
|
public Kit(Context context) you need set a context to a kit to use it
|
public Vector normalize(){
return divide(length());
}
|
Get the normalized vector, which is the vector divided by its length, as a new vector.
|
public NoSuchProviderException(String msg){
super(msg);
}
|
Constructs a NoSuchProviderException with the specified detail message. A detail message is a String that describes this particular exception.
|
private void decrementExportCount(){
assert Thread.holdsLock(this);
exportCount--;
if (exportCount == 0 && getEndpoint().getListenPort() != 0) {
ServerSocket ss=server;
server=null;
try {
ss.close();
}
catch ( IOException e) {
}
}
}
|
Decrements the count of exported objects, closing the current server socket if the count reaches zero.
|
public View findViewById(int id){
View v;
if (mSlidingMenu != null) {
v=mSlidingMenu.findViewById(id);
if (v != null) return v;
}
return null;
}
|
Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
|
public WekaEnumeration(List<E> vector){
m_Counter=0;
m_Vector=vector;
m_SpecialElement=-1;
}
|
Constructs an enumeration.
|
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
|
The doPost method of the servlet. <br> This method is called when a form has its tag value method equals to post.
|
private void writeAttribute(java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
|
Util method to write an attribute without the ns prefix
|
public static GraphQueryResult evaluateGraphQuery(final AbstractTripleStore store,final ASTContainer astContainer,final QueryBindingSet globallyScopedBS,final Dataset dataset) throws QueryEvaluationException {
final AST2BOpContext context=new AST2BOpContext(astContainer,store);
final boolean isDescribe=astContainer.getOriginalAST().getQueryType() == QueryType.DESCRIBE;
final Map<String,BigdataBNode> bnodes=(isDescribe ? new LinkedHashMap<String,BigdataBNode>() : null);
final IDescribeCache describeCache;
final Set<IVariable<?>> describeVars;
if (isDescribe && context.describeCache != null) {
describeCache=context.getDescribeCache();
describeVars=astContainer.getOriginalAST().getProjectedVars(new LinkedHashSet<IVariable<?>>());
}
else {
describeCache=null;
describeVars=null;
}
final QueryRoot optimizedQuery=optimizeQuery(astContainer,context,globallyScopedBS,dataset);
final boolean materializeProjectionInQuery=context.materializeProjectionInQuery && !optimizedQuery.hasSlice();
final DescribeModeEnum describeMode=context.getDescribeMode(optimizedQuery.getProjection());
final int describeIterationLimit=context.getDescribeIterationLimit(optimizedQuery.getProjection());
final int describeStatementlimit=context.getDescribeStatementLimit(optimizedQuery.getProjection());
GraphQueryResult result=null;
final CloseableIteration<BindingSet,QueryEvaluationException> solutions=ASTEvalHelper.evaluateQuery(astContainer,context,materializeProjectionInQuery,optimizedQuery.getProjection().getProjectionVars());
try {
final CloseableIteration<BindingSet,QueryEvaluationException> solutions2;
final Set<BigdataValue> describedResources;
if (describeCache != null) {
describedResources=Collections.newSetFromMap(new ConcurrentHashMap<BigdataValue,Boolean>());
solutions2=new DescribeBindingsCollector(describeVars,describedResources,solutions);
}
else {
solutions2=solutions;
describedResources=null;
}
final CloseableIteration<BigdataStatement,QueryEvaluationException> src=new ASTConstructIterator(context,store,optimizedQuery.getConstruct(),optimizedQuery.getWhereClause(),bnodes,solutions2);
final CloseableIteration<BigdataStatement,QueryEvaluationException> src2;
if (isDescribe) {
switch (describeMode) {
case SymmetricOneStep:
case ForwardOneStep:
src2=src;
break;
case CBD:
case SCBD:
{
src2=new CBD(store,describeMode,describeIterationLimit,describeStatementlimit,bnodes).computeClosure(src);
break;
}
default :
throw new UnsupportedOperationException("describeMode=" + describeMode);
}
}
else {
src2=src;
}
final CloseableIteration<BigdataStatement,QueryEvaluationException> src3;
if (describeCache != null) {
src3=new DescribeCacheUpdater(describeCache,describedResources,src2);
}
else {
src3=src2;
}
result=new GraphQueryResultImpl(optimizedQuery.getPrefixDecls(),src3);
}
finally {
if (result == null) {
solutions.close();
}
}
return result;
}
|
Evaluate a CONSTRUCT/DESCRIBE query. <p> Note: For a DESCRIBE query, this also updates the DESCRIBE cache.
|
public LSH(final int stages,final int buckets){
this.stages=stages;
this.buckets=buckets;
}
|
Instantiates a LSH instance with s stages (or bands) and b buckets (per stage), in a space with n dimensions.
|
private void prepareBlockSnapshotData(String name,int numSnapshots) throws Exception {
Volume volume=new Volume();
URI volumeURI=URIUtil.createId(Volume.class);
StorageSystem storageSystem=createStorageSystem(false);
volume.setId(volumeURI);
volume.setStorageController(storageSystem.getId());
String volName="blockSnapshotVolume";
volume.setLabel(volName);
BlockConsistencyGroup cg=createBlockConsistencyGroup("blockSnapshotConsistencyGroup",storageSystem.getId(),Types.LOCAL.name(),true);
volume.setConsistencyGroup(cg.getId());
_dbClient.createObject(volume);
for (int i=1; i <= numSnapshots; i++) {
BlockSnapshot blockSnapshot=new BlockSnapshot();
URI blockSnapshotURI=URIUtil.createId(BlockSnapshot.class);
blockSnapshotURIs.add(blockSnapshotURI);
blockSnapshot.setId(blockSnapshotURI);
blockSnapshot.setLabel(name + i);
blockSnapshot.setSnapsetLabel(name + i);
blockSnapshot.setParent(new NamedURI(volume.getId(),name + i));
blockSnapshot.addConsistencyGroup(cg.getId().toString());
_dbClient.createObject(blockSnapshot);
}
}
|
Creates the BlockObject BlockSnapshot data.
|
public static void main(final String[] args){
DOMTestCase.doMain(domimplementationfeaturexml.class,args);
}
|
Runs this test from the command line.
|
public AndroidAuthenticator(Context context,Account account,String authTokenType){
this(context,account,authTokenType,false);
}
|
Creates a new authenticator.
|
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
else {
System.out.println(progressLabel + " " + progress+ "%");
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
|
Used to communicate a progress update between a plugin tool and the main Whitebox user interface.
|
public void bindProperty(String prop,BindTarget target){
}
|
Binds the given property name to the given bind target
|
public PowerLawGrowthModel(Parameter N0Parameter,Parameter growthRateParameter,Type units){
this(PowerLawGrowthModelParser.POWER_LAW_GROWTH_MODEL,N0Parameter,growthRateParameter,units);
}
|
Construct demographic model with default settings
|
protected Object visit(BinaryLogicOperator filter,Object extraData){
LOGGER.finer("exporting LogicFilter");
final List<FilterBuilder> filterList=new ArrayList<>();
for ( final Filter child : filter.getChildren()) {
child.accept(this,extraData);
filterList.add(filterBuilder);
}
final FilterBuilder[] filters;
filters=filterList.toArray(new FilterBuilder[filterList.size()]);
if (extraData.equals("AND")) {
filterBuilder=FilterBuilders.andFilter(filters);
}
else {
filterBuilder=FilterBuilders.orFilter(filters);
}
return extraData;
}
|
Common implementation for BinaryLogicOperator filters. This way they're all handled centrally.
|
public static int StringRegionMatches(String value,boolean ignoreCase,int thisStart,String string,int start,int length){
if (value == null || string == null) throw new NullPointerException();
if (start < 0 || string.length() - start < length) {
return -BooleanHelper.K;
}
if (thisStart < 0 || value.length() - thisStart < length) {
return -BooleanHelper.K;
}
if (length <= 0) {
return BooleanHelper.K;
}
if (ignoreCase && value.regionMatches(ignoreCase,thisStart,string,start,length)) {
return BooleanHelper.K;
}
String s1=value;
String s2=string;
if (ignoreCase) {
s1=s1.toLowerCase();
s2=s2.toLowerCase();
}
if (Properties.DYNAMIC_POOL > 0.0) {
String sub1=s1.substring(thisStart,length + thisStart);
String sub2=s2.substring(start,length + start);
String sn1=s1.substring(0,thisStart) + sub2 + s1.substring(thisStart + length);
String sn2=s2.substring(0,start) + sub1 + s2.substring(start + length);
ConstantPoolManager.getInstance().addDynamicConstant(sn1);
ConstantPoolManager.getInstance().addDynamicConstant(sn2);
}
return StringEquals(s1.substring(thisStart,Math.min(length + thisStart,s1.length())),s2.substring(start,Math.min(length + start,s2.length())));
}
|
<p> StringRegionMatches </p>
|
public static boolean reflectionEquals(final Object lhs,final Object rhs,final boolean testTransients){
return reflectionEquals(lhs,rhs,testTransients,null);
}
|
<p>This method uses reflection to determine if the two <code>Object</code>s are equal.</p> <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly. Non-primitive fields are compared using <code>equals()</code>.</p> <p>If the TestTransients parameter is set to <code>true</code>, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the <code>Object</code>.</p> <p>Static fields will not be tested. Superclass fields will be included.</p>
|
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:01:13.445 -0500",hash_original_method="E2E038DF81C8876BEF1DC650925A08F9",hash_generated_method="64087033E04A614553C34B8F59B74AC2") public void write(byte[] vector){
check(vector.length);
System.arraycopy(vector,0,buffer,write_pos,vector.length);
write_pos+=vector.length;
}
|
writes vector of opaque values
|
private void finishStringSection(List<StringSection> sections,StringSection currentSection,StringBuilder templateExpressions,Position lastSourcePosition,Position targetPosition){
if (currentSection.lastSourcePosition != null) {
return;
}
currentSection.lastSourcePosition=new Position(lastSourcePosition);
sections.add(currentSection);
append(templateExpressions,targetPosition,"out<<_s[_i=" + index++ + "];");
currentSection.lastTargetPosition=new Position(targetPosition.row,targetPosition.column);
}
|
Called to handle the ending of a string section.
|
public static final void pushTransform(GL2 gl){
gl.glPushMatrix();
}
|
Saves the current OpenGL transformation matrix.
|
public Contract persistContract(final Contract transientInstance) throws PersistentModelException {
try {
if (null == transientInstance.getIdContract()) {
Contract currentContract=m_contractHome.findByUniqueKey(transientInstance.getSecType(),transientInstance.getSymbol(),transientInstance.getExchange(),transientInstance.getCurrency(),transientInstance.getExpiry());
if (null != currentContract) {
transientInstance.setIdContract(currentContract.getIdContract());
}
}
return m_aspectHome.persist(transientInstance,true);
}
catch ( OptimisticLockException ex1) {
throw new PersistentModelException("Error saving Contract please refresh before save.");
}
catch ( Exception e) {
throw new PersistentModelException("Error saving Contract: " + transientInstance.getSymbol() + "\n Msg: "+ e.getMessage());
}
}
|
Method persistContract.
|
public void addChild(IXMLElement child){
if (child == null) {
throw new IllegalArgumentException("child must not be null");
}
if ((child.getName() == null) && (!this.children.isEmpty())) {
IXMLElement lastChild=(IXMLElement)this.children.get(this.children.size() - 1);
if (lastChild.getName() == null) {
lastChild.setContent(lastChild.getContent() + child.getContent());
return;
}
}
((XMLElement)child).parent=this;
this.children.add(child);
}
|
Adds a child element.
|
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 static Flag registerExcludeUnplacedFlag(final CFlags flags){
return flags.registerOptional(EXCLUDE_UNPLACED_FLAG,EXCLUDE_UNPLACED_DESC).setCategory(SENSITIVITY_TUNING);
}
|
Register flag for excluding unmapped results.
|
public void dispose(){
}
|
We can use this method to dispose of any system resources we previously allocated.
|
public synchronized ICCColorSpaceExt request(String profileName){
return (ICCColorSpaceExt)super.requestImpl(profileName);
}
|
If this returns null then you are now 'on the hook'. to put the ICCColorSpaceExt associated with String into the cache.
|
public void actionPerformed(ActionEvent e){
String cmd=e.getActionCommand();
if (cmd.equals("Cut")) {
evalTextArea.cut();
}
else if (cmd.equals("Copy")) {
evalTextArea.copy();
}
else if (cmd.equals("Paste")) {
evalTextArea.paste();
}
}
|
Performs an action on the text area.
|
public boolean hasMergedIntoUpdate(){
return hasExtension(MergedIntoUpdate.class);
}
|
Returns whether it has the merged into update.
|
protected int downsample(int[] data,int start,int end,int size){
int sum=0;
for (int i=start; i < end; i++) {
sum+=data[i];
}
return sum;
}
|
Perform downsampling on a number of bins.
|
public CreateRouteRequest(String sourceUrn,String sinkUrn,String presentationId,int requestId,ChromeMediaRouter router){
mSourceUrn=sourceUrn;
mMediaSource=MediaSource.from(sourceUrn);
mSinkId=sinkUrn;
mPresentationId=presentationId;
mRequestId=requestId;
mMediaRouter=router;
}
|
Initializes the request.
|
@Override public void test(String t) throws ParameterException {
if (t.length() < minlength) {
throw new WrongParameterValueException("Parameter Constraint Error.\n" + "Parameter value length must be at least " + minlength + ".");
}
if (maxlength > 0 && t.length() > maxlength) {
throw new WrongParameterValueException("Parameter Constraint Error.\n" + "Parameter value length must be at most " + maxlength + ".");
}
}
|
Checks if the given string value of the string parameter is within the length restrictions. If not, a parameter exception is thrown.
|
public static String stringFor(int k){
switch (k) {
case cudaMemcpyHostToHost:
return "cudaMemcpyHostToHost";
case cudaMemcpyHostToDevice:
return "cudaMemcpyHostToDevice";
case cudaMemcpyDeviceToHost:
return "cudaMemcpyDeviceToHost";
case cudaMemcpyDeviceToDevice:
return "cudaMemcpyDeviceToDevice";
case cudaMemcpyDefault:
return "cudaMemcpyDefault";
}
return "INVALID cudaMemcpyKind: " + k;
}
|
Returns the String identifying the given cudaMemcpyKind
|
private static void scaleComponentFonts(Component component,float size){
Font f=component.getFont().deriveFont(size);
component.setFont(f);
if (component instanceof Container) {
for ( Component child : ((Container)component).getComponents()) {
scaleComponentFonts(child,size);
}
}
}
|
Scale the font of a component and its subcomponents.
|
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:01.287 -0500",hash_original_method="5B3F4DCDB18701B7EDED77C3B9D3C550",hash_generated_method="1059C2B39BA7CB5FDAEFB1C86FD435AA") private void appendEvaluated(StringBuffer buffer,String s){
boolean escape=false;
boolean dollar=false;
for (int i=0; i < s.length(); i++) {
char c=s.charAt(i);
if (c == '\\' && !escape) {
escape=true;
}
else if (c == '$' && !escape) {
dollar=true;
}
else if (c >= '0' && c <= '9' && dollar) {
buffer.append(group(c - '0'));
dollar=false;
}
else {
buffer.append(c);
dollar=false;
escape=false;
}
}
if (escape) {
throw new ArrayIndexOutOfBoundsException(s.length());
}
}
|
Internal helper method to append a given string to a given string buffer. If the string contains any references to groups, these are replaced by the corresponding group's contents.
|
public static TypeReference newTryCatchReference(int tryCatchBlockIndex){
return new TypeReference((EXCEPTION_PARAMETER << 24) | (tryCatchBlockIndex << 8));
}
|
Returns a reference to the type of the exception declared in a 'catch' clause of a method.
|
public void loadThis(){
if ((access & Opcodes.ACC_STATIC) != 0) {
throw new IllegalStateException("no 'this' pointer within static method");
}
mv.visitVarInsn(Opcodes.ALOAD,0);
}
|
Generates the instruction to load 'this' on the stack.
|
public void removeMethod(){
if (uriParms != null) uriParms.delete(METHOD);
}
|
remove the Method.
|
public IMqttDeliveryToken publish(String clientHandle,String topic,MqttMessage message,String invocationContext,String activityToken) throws MqttPersistenceException, MqttException {
MqttConnection client=getConnection(clientHandle);
return client.publish(topic,message,invocationContext,activityToken);
}
|
Publish a message to a topic
|
@Override public ExchangeClient connect(URL url,ExchangeHandler handler) throws RemotingException {
return null;
}
|
Description: <br>
|
private static void queryLocales() throws IOException, ServiceException {
URL url=urlFactory.getLocalesFeedURL();
GoogleBaseQuery query=new GoogleBaseQuery(url);
System.out.println("Sending request to: " + query.getUrl());
try {
GoogleBaseFeed feed=service.query(query);
for ( GoogleBaseEntry entry : feed.getEntries()) {
System.out.println(entry.getTitle().getPlainText());
}
}
catch ( ServiceException e) {
printServiceException(e);
}
}
|
Retrieves and prints the locales.
|
public synchronized void remove(String item){
int index=items.indexOf(item);
if (index < 0) {
throw new IllegalArgumentException("item " + item + " not found in list");
}
else {
remove(index);
}
}
|
Removes the first occurrence of an item from the list. If the specified item is selected, and is the only selected item in the list, the list is set to have no selection.
|
public Seq<CharSeq> eachLine(){
return this.split("\n|\r\n");
}
|
Split the CharSeq by the newline character and return the result as a Seq of CharSeq.
|
public void testPathModeSwitchToPrimary() throws Exception {
mode=DUAL_SYNC;
pathModes(F.t("/dir1",PRIMARY),F.t("/dir2",DUAL_SYNC));
startUp();
checkMode("/dir",PRIMARY);
checkMode("/dir1",PRIMARY);
checkMode("/dir2",PRIMARY);
}
|
Ensure that path modes switch to PRIMARY in case secondary FS config is not provided.
|
public List<ValueBox> addArgumentHotspots(String signature,int arg){
List<ValueBox> sigSpots=StringAnalysis.getArgumentExpressions(signature,arg);
return addArgumentHotspots(signature,arg,sigSpots);
}
|
Add a hotspot for matching calls.
|
public GVTGlyphVector createGlyphVector(FontRenderContext frc,int[] glyphCodes,CharacterIterator ci){
int nGlyphs=glyphCodes.length;
StringBuffer workBuff=new StringBuffer(nGlyphs);
for (int i=0; i < nGlyphs; i++) {
workBuff.append(glyphUnicodes[glyphCodes[i]]);
}
StringCharacterIterator sci=new StringCharacterIterator(workBuff.toString());
return createGlyphVector(frc,sci);
}
|
Returns a new GVTGlyphVector object for the glyphs in the the glyph code array.
|
public XTIFFImage(SeekableStream stream,TIFFDecodeParam param,int directory) throws IOException {
this.stream=stream;
if (param == null || !(param instanceof XTIFFDecodeParam)) {
param=new XTIFFDecodeParam(param);
}
this.param=param;
decodePaletteAsShorts=param.getDecodePaletteAsShorts();
dir=XTIFFDirectory.create(stream,directory);
properties.put("tiff.directory",dir);
((XTIFFDecodeParam)param).setDirectory(dir);
isBigEndian=dir.isBigEndian();
setupImageParameters();
setupSamplesAndColor();
dir.setImageType(image_type);
tilesX=(width + tileWidth - 1) / tileWidth;
tilesY=(height + tileHeight - 1) / tileHeight;
tileSize=tileWidth * tileHeight * bands;
try {
codec=dir.createTileCodec((XTIFFDecodeParam)param);
}
catch ( Exception e) {
}
}
|
Constructs a XTIFFImage that acquires its data from a given SeekableStream and reads from a particular IFD of the stream. The index of the first IFD is 0.
|
public void checkShape(AbstractMatrix3D B,AbstractMatrix3D C){
if (slices != B.slices || rows != B.rows || columns != B.columns || slices != C.slices || rows != C.rows || columns != C.columns) throw new IllegalArgumentException("Incompatible dimensions: " + toStringShort() + ", "+ B.toStringShort()+ ", "+ C.toStringShort());
}
|
Sanity check for operations requiring matrices with the same number of slices, rows and columns.
|
public static int intValue(String option){
String s=value(option);
if (s != null) {
try {
int val=Integer.parseInt(s);
if (val > 0) return (val);
}
catch ( NumberFormatException e) {
}
}
return (-1);
}
|
Returns the value of an option as an integer, or -1 if not defined.
|
public String globalInfo(){
return "Generates output for a data and script file for GnuPlot.";
}
|
Returns a string describing the matrix.
|
protected SystemMember createSystemMember(InternalDistributedMember member) throws org.apache.geode.admin.AdminException {
return new SystemMemberJmxImpl(this,member);
}
|
Constructs & returns a SystemMember instance using the corresponding InternalDistributedMember object.
|
protected void onPostProcess(String what,String[] oldPathNames,String[] newPathNames,int modifyCount,int itemCount,int opCode){
}
|
called for each modified/deleted file
|
private long parseLong() throws IOException {
int sign=1;
int ch=read();
if (ch == '-') {
sign=-1;
ch=read();
}
long value=0;
for (; ch >= '0' && ch <= '9'; ch=read()) value=10 * value + ch - '0';
_peek=ch;
return sign * value;
}
|
Parses a 64-bit long value from the stream.
|
@Override public boolean eventGeneratable(String eventName){
if (eventName.compareTo("graph") == 0) {
if (!(m_Clusterer instanceof weka.core.Drawable)) {
return false;
}
if (!m_listenees.containsKey("trainingSet")) {
return false;
}
Object source=m_listenees.get("trainingSet");
if (source instanceof EventConstraints) {
if (!((EventConstraints)source).eventGeneratable("trainingSet")) {
return false;
}
}
}
if (eventName.compareTo("batchClusterer") == 0) {
if (!m_listenees.containsKey("trainingSet")) {
return false;
}
Object source=m_listenees.get("trainingSet");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints)source).eventGeneratable("trainingSet")) {
return false;
}
}
}
if (eventName.compareTo("text") == 0) {
if (!m_listenees.containsKey("trainingSet")) {
return false;
}
Object source=m_listenees.get("trainingSet");
if (source != null && source instanceof EventConstraints) {
if (!((EventConstraints)source).eventGeneratable("trainingSet")) {
return false;
}
}
}
if (eventName.compareTo("batchClassifier") == 0) {
return false;
}
if (eventName.compareTo("incrementalClassifier") == 0) {
return false;
}
return true;
}
|
Returns true, if at the current time, the named event could be generated. Assumes that the supplied event name is an event that could be generated by this bean
|
private ResolvedMigration extractMigrationInfo(Resource resource){
ResolvedMigration migration=new ResolvedMigration();
Pair<MigrationVersion,String> info=MigrationInfoHelper.extractVersionAndDescription(resource.getFilename(),CQL_MIGRATION_PREFIX,CQL_MIGRATION_SEPARATOR,CQL_MIGRATION_SUFFIX);
migration.setVersion(info.getLeft());
migration.setDescription(info.getRight());
migration.setScript(extractScriptName(resource));
migration.setChecksum(calculateChecksum(resource.loadAsBytes()));
migration.setType(MigrationType.CQL);
return migration;
}
|
Extracts the migration info for this resource.
|
public boolean hasSessionId(){
return sessionId != null && sessionId.length() > 0;
}
|
Checks whether this message contains a session ID.
|
public WhereBuilder or(String columnName,String op,Object value){
appendCondition(whereItems.size() == 0 ? null : "OR",columnName,op,value);
return this;
}
|
add OR condition
|
public static Date previous(Date self){
return minus(self,1);
}
|
Decrement a Date by one day.
|
@Restricted(value=NoExternalUse.class) public GitHubPRTrigger() throws ANTLRException {
super("");
}
|
For groovy UI
|
public final void testHashCode02(){
assertTrue(new ECFieldFp(BigInteger.valueOf(23L)).hashCode() == new ECFieldFp(BigInteger.valueOf(23L)).hashCode());
}
|
Test #2 for <code>hashCode()</code> method.<br> Assertion: must return the same value if invoked on equal (according to the <code>equals(Object)</code> method) objects.
|
private int findPosition(@NonNull String tmpTotal,@NonNull SpannableStringBuilder ssb,@NonNull SpannableStringBuilder tmp){
String tmpTmpTotal=tmpTotal;
int position=tmpTmpTotal.indexOf(KEY_INLINE_CODE);
if (position == -1) {
return -1;
}
else {
if (checkInHyperLink(ssb,tmp.length() + position,KEY_INLINE_CODE.length()) || checkInImage(ssb,tmp.length() + position,KEY_INLINE_CODE.length())) {
StringBuilder sb=new StringBuilder(tmpTmpTotal.substring(0,position)).append("$").append(tmpTmpTotal.substring(position + KEY_INLINE_CODE.length(),tmpTmpTotal.length()));
return findPosition(sb.toString(),ssb,tmp);
}
else {
return position;
}
}
}
|
find the position of next "`" ignore the "`" in inline code grammar or image grammar
|
private void clearPendingOMADownload(long downloadId,String installNotifyURI){
ClearPendingOMADownloadTask task=new ClearPendingOMADownloadTask(downloadId,installNotifyURI);
task.execute();
}
|
Clear pending OMA downloads for a particular download ID.
|
private View makeAndAddView(int position,int y,boolean flow,int childrenLeft,boolean selected,int where){
View child;
if (!mDataChanged) {
child=mRecycler.getActiveView(position);
if (child != null) {
setupChild(child,position,y,flow,childrenLeft,selected,true,where);
return child;
}
}
child=obtainView(position,mIsScrap);
setupChild(child,position,y,flow,childrenLeft,selected,mIsScrap[0],where);
return child;
}
|
Obtain the view and add it to our list of children. The view can be made fresh, converted from an unused view, or used as is if it was in the recycle bin.
|
public static ResourcesSoot v(){
return instance;
}
|
singleton access
|
public synchronized void addObject(Object obj){
fifo.addElement(obj);
nbObjects++;
notifyAll();
}
|
Add an object in the buffer
|
private void editTag(TagItem tagItem,String newValue){
tagItem.setValue(newValue);
change=true;
}
|
Edit tag value
|
public static void packFile(Path fileToPack,Path packageFile) throws IOException {
pack(fileToPack,packageFile,false);
}
|
Pack file without compression
|
private static long freeSpaceCalculation(String path){
StatFs stat=new StatFs(path);
long blockSize=stat.getBlockSize();
long availableBlocks=stat.getAvailableBlocks();
return availableBlocks * blockSize / 1024;
}
|
Given a path return the number of free KB
|
public static void dump(ServletContext ctx){
log.config("ServletContext " + ctx.getServletContextName());
log.config("- ServerInfo=" + ctx.getServerInfo());
if (!CLogMgt.isLevelFiner()) return;
boolean first=true;
Enumeration e=ctx.getInitParameterNames();
while (e.hasMoreElements()) {
if (first) log.finer("InitParameter:");
first=false;
String key=(String)e.nextElement();
Object value=ctx.getInitParameter(key);
log.finer("- " + key + " = "+ value);
}
first=true;
e=ctx.getAttributeNames();
while (e.hasMoreElements()) {
if (first) log.finer("Attributes:");
first=false;
String key=(String)e.nextElement();
Object value=ctx.getAttribute(key);
log.finer("- " + key + " = "+ value);
}
}
|
Dump Session
|
@SuppressWarnings({"unchecked","rawtypes"}) @Override public void endWindow(){
boolean emit=(++windowCount) % windowSize == 0;
if (!emit) {
return;
}
boolean dosum=sum.isConnected();
if (dosum) {
for ( Map.Entry<K,SumEntry> e : sums.entrySet()) {
K key=e.getKey();
if (dosum) {
sum.emit(new KeyValPair(key,getValue(e.getValue().sum.doubleValue())));
}
}
}
sums.clear();
}
|
Emit only at the end of windowSize window boundary.
|
public static boolean isLegalPropertyKey(String key){
return (key.equals(OutputKeys.CDATA_SECTION_ELEMENTS) || key.equals(OutputKeys.DOCTYPE_PUBLIC) || key.equals(OutputKeys.DOCTYPE_SYSTEM)|| key.equals(OutputKeys.ENCODING)|| key.equals(OutputKeys.INDENT)|| key.equals(OutputKeys.MEDIA_TYPE)|| key.equals(OutputKeys.METHOD)|| key.equals(OutputKeys.OMIT_XML_DECLARATION)|| key.equals(OutputKeys.STANDALONE)|| key.equals(OutputKeys.VERSION)|| (key.length() > 0) && (key.charAt(0) == '{') && (key.lastIndexOf('{') == 0)&& (key.indexOf('}') > 0)&& (key.lastIndexOf('}') == key.indexOf('}')));
}
|
Report if the key given as an argument is a legal xsl:output key.
|
public void testBadStreamBounds(){
SplittableRandom r=new SplittableRandom();
executeAndCatchIAE(null);
executeAndCatchIAE(null);
executeAndCatchIAE(null);
executeAndCatchIAE(null);
testDoubleBadOriginBound(null);
}
|
Invoking bounded ints, long, doubles, with illegal bounds throws IllegalArgumentException
|
public static String createTempFile(String prefix,String suffix,boolean deleteOnExit,boolean inTempDir) throws IOException {
return FilePath.get(prefix).createTempFile(suffix,deleteOnExit,inTempDir).toString();
}
|
Create a new temporary file.
|
private static boolean less(Comparable v,Comparable w){
return v.compareTo(w) < 0;
}
|
Helper sorting functions.
|
public char charAt(int index){
return ((char[])m_obj)[index + m_start];
}
|
Returns the character at the specified index. An index ranges from <code>0</code> to <code>length() - 1</code>. The first character of the sequence is at index <code>0</code>, the next at index <code>1</code>, and so on, as for array indexing.
|
public BadLocationException(String s,int offs){
super(s);
this.offs=offs;
}
|
Creates a new BadLocationException object.
|
public boolean isTranformInProgress(){
return m_transact.isRunning();
}
|
Indicates if a view transformation is currently underway.
|
public static String makeLogTag(Class cls){
return makeLogTag(cls.getSimpleName());
}
|
Don't use this when obfuscating class names!
|
private static void packSmsChar(byte[] packedChars,int bitOffset,int value){
int byteOffset=bitOffset / 8;
int shift=bitOffset % 8;
packedChars[++byteOffset]|=value << shift;
if (shift > 1) {
packedChars[++byteOffset]=(byte)(value >> (8 - shift));
}
}
|
Pack a 7-bit char into its appropriate place in a byte array
|
public ConditionalExpressionItemProvider(AdapterFactory adapterFactory){
super(adapterFactory);
}
|
This constructs an instance from a factory and a notifier. <!-- begin-user-doc --> <!-- end-user-doc -->
|
public void onConnect(String host,Integer port,Integer clientId){
this.m_clientId=clientId;
m_client.eConnect(host,port,clientId);
openOrders.clear();
}
|
Method onConnect.
|
public void removeListener(TapListener listener){
mListeners.remove(listener);
}
|
Removes the listener from receiving data or events from this tap
|
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:24.424 -0500",hash_original_method="07989C3909E96A7576DAE0D29DD189A0",hash_generated_method="4CC6F7815479BD2C24DC503B87EA800A") private void addRoute(RecordRouteList recordRouteList){
try {
if (this.isClientDialog()) {
this.routeList=new RouteList();
ListIterator li=recordRouteList.listIterator(recordRouteList.size());
boolean addRoute=true;
while (li.hasPrevious()) {
RecordRoute rr=(RecordRoute)li.previous();
if (addRoute) {
Route route=new Route();
AddressImpl address=((AddressImpl)((AddressImpl)rr.getAddress()).clone());
route.setAddress(address);
route.setParameters((NameValueList)rr.getParameters().clone());
this.routeList.add(route);
}
}
}
else {
this.routeList=new RouteList();
ListIterator li=recordRouteList.listIterator();
boolean addRoute=true;
while (li.hasNext()) {
RecordRoute rr=(RecordRoute)li.next();
if (addRoute) {
Route route=new Route();
AddressImpl address=((AddressImpl)((AddressImpl)rr.getAddress()).clone());
route.setAddress(address);
route.setParameters((NameValueList)rr.getParameters().clone());
routeList.add(route);
}
}
}
}
finally {
if (sipStack.getStackLogger().isLoggingEnabled()) {
Iterator it=routeList.iterator();
while (it.hasNext()) {
SipURI sipUri=(SipURI)(((Route)it.next()).getAddress().getURI());
if (!sipUri.hasLrParam()) {
if (sipStack.isLoggingEnabled()) {
sipStack.getStackLogger().logWarning("NON LR route in Route set detected for dialog : " + this);
sipStack.getStackLogger().logStackTrace();
}
}
}
}
}
}
|
Add a route list extracted from a record route list. If this is a server dialog then we assume that the record are added to the route list IN order. If this is a client dialog then we assume that the record route headers give us the route list to add in reverse order.
|
public void addListener(final ITagManagerListener listener){
m_listeners.addListener(listener);
}
|
Adds an object that is notified about changes in the tag manager.
|
protected Type determineInferredType(Method method){
if (method == null) {
return null;
}
Type genericParameterType=null;
boolean hasAck=false;
for (int i=0; i < method.getParameterTypes().length; i++) {
MethodParameter methodParameter=new MethodParameter(method,i);
if (eligibleParameter(methodParameter) && (methodParameter.getParameterAnnotations().length == 0 || methodParameter.hasParameterAnnotation(Payload.class))) {
if (genericParameterType == null) {
genericParameterType=methodParameter.getGenericParameterType();
if (genericParameterType instanceof ParameterizedType) {
ParameterizedType parameterizedType=(ParameterizedType)genericParameterType;
if (parameterizedType.getRawType().equals(Message.class)) {
genericParameterType=((ParameterizedType)genericParameterType).getActualTypeArguments()[0];
}
else if (parameterizedType.getRawType().equals(List.class) && parameterizedType.getActualTypeArguments().length == 1) {
Type paramType=parameterizedType.getActualTypeArguments()[0];
this.isConsumerRecordList=paramType.equals(ConsumerRecord.class) || (paramType instanceof ParameterizedType && ((ParameterizedType)paramType).getRawType().equals(ConsumerRecord.class));
this.isMessageList=paramType.equals(Message.class) || (paramType instanceof ParameterizedType && ((ParameterizedType)paramType).getRawType().equals(Message.class));
}
}
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Ambiguous parameters for target payload for method " + method + "; no inferred type available");
}
break;
}
}
else if (methodParameter.getGenericParameterType().equals(Acknowledgment.class)) {
hasAck=true;
}
}
Assert.state(!this.isConsumerRecordList || method.getParameterTypes().length == 1 || (method.getGenericParameterTypes().length == 2 && hasAck),"A parameter of type 'List<ConsumerRecord>' must be the only parameter " + "(except for an optional 'Acknowledgment')");
Assert.state(!this.isMessageList || method.getParameterTypes().length == 1 || (method.getGenericParameterTypes().length == 2 && hasAck),"A parameter of type 'List<Message<?>>' must be the only parameter " + "(except for an optional 'Acknowledgment')");
return genericParameterType;
}
|
Subclasses can override this method to use a different mechanism to determine the target type of the payload conversion.
|
final public int limit(){
return limit;
}
|
The read limit (there is no write limit on the buffer since the capacity will be automatically extended on overflow).
|
@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 filterSize=3;
double n;
double sum;
int[] dX;
int[] dY;
double[] weights;
int midPoint;
int numPixelsInFilter;
boolean reflectAtBorders=false;
double sigma=0;
double recipRoot2PiTimesSigma;
double twoSigmaSqr;
double zN, zFinal;
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) {
sigma=Double.parseDouble(args[i]);
}
else if (i == 3) {
reflectAtBorders=Boolean.parseBoolean(args[i]);
}
}
if (sigma < 0.5) {
sigma=0.5;
}
else if (sigma > 20) {
sigma=20;
}
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("grey.pal");
recipRoot2PiTimesSigma=1 / (Math.sqrt(2 * Math.PI) * sigma);
twoSigmaSqr=2 * sigma * sigma;
double weight;
for (int i=0; i <= 250; i++) {
weight=recipRoot2PiTimesSigma * Math.exp(-1 * (i * i) / twoSigmaSqr);
if (weight <= 0.001) {
filterSize=i * 2 + 1;
break;
}
}
if (filterSize % 2 == 0) {
filterSize++;
}
if (filterSize < 3) {
filterSize=3;
}
numPixelsInFilter=filterSize * filterSize;
dX=new int[numPixelsInFilter];
dY=new int[numPixelsInFilter];
weights=new double[numPixelsInFilter];
int cellsOnEitherSide=(int)Math.floor((double)filterSize / 2);
double term1=-1 / (Math.PI * sigma * sigma* sigma* sigma);
double term2=0;
double term3=0;
a=0;
for (row=0; row < filterSize; row++) {
for (col=0; col < filterSize; col++) {
x=col - cellsOnEitherSide;
y=row - cellsOnEitherSide;
term2=1 - ((x * x + y * y) / twoSigmaSqr);
term3=Math.exp(-(x * x + y * y) / twoSigmaSqr);
weight=term1 * term2 * term3;
weights[a]=weight;
dX[a]=x;
dY[a]=y;
a++;
}
}
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
z=inputFile.getValue(row,col);
if (z != noData) {
sum=0;
zFinal=0;
for (a=0; a < numPixelsInFilter; a++) {
x=col + dX[a];
y=row + dY[a];
zN=inputFile.getValue(y,x);
if (zN != noData) {
sum+=weights[a];
zFinal+=weights[a] * zN;
}
}
outputFile.setValue(row,col,zFinal / sum);
}
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.
|
private Collection<Integer> interactWithServer() throws Exception {
ProcessStartResult srvStartRes=startSharedMemoryTestServer();
ProcessStartResult clientStartRes=startSharedMemoryTestClient();
clientStartRes.isReadyLatch().await();
info("Going to kill server.");
srvStartRes.proc().kill();
srvStartRes.isKilledLatch().await();
info("Going to kill client.");
clientStartRes.proc().kill();
clientStartRes.isKilledLatch().await();
return clientStartRes.shmemIds();
}
|
Launches IgfsSharedMemoryTestServer and IgfsSharedMemoryTestClient. After successful connection kills firstly server and secondly client.
|
private static double expm1(double x,double hiPrecOut[]){
if (x != x || x == 0.0) {
return x;
}
if (x <= -1.0 || x >= 1.0) {
double hiPrec[]=new double[2];
exp(x,0.0,hiPrec);
if (x > 0.0) {
return -1.0 + hiPrec[0] + hiPrec[1];
}
else {
final double ra=-1.0 + hiPrec[0];
double rb=-(ra + 1.0 - hiPrec[0]);
rb+=hiPrec[1];
return ra + rb;
}
}
double baseA;
double baseB;
double epsilon;
boolean negative=false;
if (x < 0.0) {
x=-x;
negative=true;
}
{
int intFrac=(int)(x * 1024.0);
double tempA=ExpFracTable.EXP_FRAC_TABLE_A[intFrac] - 1.0;
double tempB=ExpFracTable.EXP_FRAC_TABLE_B[intFrac];
double temp=tempA + tempB;
tempB=-(temp - tempA - tempB);
tempA=temp;
temp=tempA * HEX_40000000;
baseA=tempA + temp - temp;
baseB=tempB + (tempA - baseA);
epsilon=x - intFrac / 1024.0;
}
double zb=0.008336750013465571;
zb=zb * epsilon + 0.041666663879186654;
zb=zb * epsilon + 0.16666666666745392;
zb=zb * epsilon + 0.49999999999999994;
zb*=epsilon;
zb*=epsilon;
double za=epsilon;
double temp=za + zb;
zb=-(temp - za - zb);
za=temp;
temp=za * HEX_40000000;
temp=za + temp - temp;
zb+=za - temp;
za=temp;
double ya=za * baseA;
temp=ya + za * baseB;
double yb=-(temp - ya - za * baseB);
ya=temp;
temp=ya + zb * baseA;
yb+=-(temp - ya - zb * baseA);
ya=temp;
temp=ya + zb * baseB;
yb+=-(temp - ya - zb * baseB);
ya=temp;
temp=ya + baseA;
yb+=-(temp - baseA - ya);
ya=temp;
temp=ya + za;
yb+=-(temp - ya - za);
ya=temp;
temp=ya + baseB;
yb+=-(temp - ya - baseB);
ya=temp;
temp=ya + zb;
yb+=-(temp - ya - zb);
ya=temp;
if (negative) {
double denom=1.0 + ya;
double denomr=1.0 / denom;
double denomb=-(denom - 1.0 - ya) + yb;
double ratio=ya * denomr;
temp=ratio * HEX_40000000;
final double ra=ratio + temp - temp;
double rb=ratio - ra;
temp=denom * HEX_40000000;
za=denom + temp - temp;
zb=denom - za;
rb+=(ya - za * ra - za * rb - zb * ra - zb * rb) * denomr;
rb+=yb * denomr;
rb+=-ya * denomb * denomr* denomr;
ya=-ra;
yb=-rb;
}
if (hiPrecOut != null) {
hiPrecOut[0]=ya;
hiPrecOut[1]=yb;
}
return ya + yb;
}
|
Internal helper method for expm1
|
public ByteVector putShort(final int s){
int length=this.length;
if (length + 2 > data.length) {
enlarge(2);
}
byte[] data=this.data;
data[length++]=(byte)(s >>> 8);
data[length++]=(byte)s;
this.length=length;
return this;
}
|
Puts a short into this byte vector. The byte vector is automatically enlarged if necessary.
|
public String exportersTipText(){
return "The base exporters to use.";
}
|
Describes this property.
|
private String findTerritoryName(final Point p){
return Util.findTerritoryName(p,m_polygons,"unknown");
}
|
java.lang.String findTerritoryName(java.awt.Point) Finds a land territory name or some sea zone name.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.