code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private void readCpuUsage(){
try {
final BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(M.e("/proc/stat"))),1000);
final String load=reader.readLine();
reader.close();
final String[] toks=load.split(" ");
final long currTotal=Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]);
final long currIdle=Long.parseLong(toks[5]);
this.cpuUsage=((currTotal - cpuTotal) * 100.0f / (currTotal - cpuTotal + currIdle - cpuIdle));
this.cpuTotal=currTotal;
this.cpuIdle=currIdle;
}
catch ( final IOException ex) {
if (Cfg.EXCEPTION) {
Check.log(ex);
}
if (Cfg.DEBUG) {
Check.log(ex);
}
}
}
| Read cpu usage. |
public URL(String protocol,String host,int port,String file) throws MalformedURLException {
this(protocol,host,port,file,null);
}
| Creates a new URL of the given component parts. The URL uses the protocol's default port. |
@Override public void writeTerm(final String term,final Posting post) throws IOException {
final MemorySBOS Docs=post.getDocs();
Docs.pad();
byte[] buffer=new byte[Docs.getMOS().getPos() + 1];
System.arraycopy(Docs.getMOS().getBuffer(),0,buffer,0,Math.min(Docs.getMOS().getBuffer().length,Docs.getMOS().getPos() + 1));
try {
context.write(NewSplitEmittedTerm.createNewTerm(term,splitId,flushNo),MapEmittedPostingList.create_Hadoop_WritableRunPostingData(mapId,flushNo,splitId,buffer,post.getDocF(),post.getTF()));
}
catch ( InterruptedException e) {
throw new WrappedIOException(e);
}
}
| Write the posting to the output collector |
public static Object parse(String s){
StringReader in=new StringReader(s);
return parse(in);
}
| Parse JSON text into java object from the given string. Please use parseWithException() if you don't want to ignore the exception. |
public TPrimitiveHash(){
super();
}
| Creates a new <code>THash</code> instance with the default capacity and load factor. |
public XML write(){
try {
FilesManager.write(xmlJmapper,xmlPath);
}
catch ( IOException e) {
JmapperLog.ERROR(e);
}
return this;
}
| Writes the xml mapping file starting from xmlJmapper object. |
protected void updateCursorForDrag(int piece){
if (getPreferences().getBoolean(PreferenceKeys.BOARD_IS_USING_CROSSHAIRS_CURSOR)) {
getShell().setCursor(Raptor.getInstance().getDisplay().getSystemCursor(SWT.CURSOR_CROSS));
}
else if (piece != EMPTY) {
int imageSide=getImageSize();
getShell().setCursor(ChessBoardUtils.getCursorForPiece(piece,imageSide));
}
else if (piece == EMPTY) {
int imageSide=getImageSize();
getShell().setCursor(ChessBoardUtils.getCursorForPiece(ChessBoardUtils.pieceJailSquareToPiece(getId()),imageSide));
}
}
| Updates the cursor for a drag with the specified piece. |
private void startVoiceRecognitionActivity(){
Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Voice recognition test...");
startActivityForResult(intent,REQUEST_CODE);
}
| Fire an intent to start the voice recognition activity. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:52.241 -0400",hash_original_method="354338F8D39FF6509677FF2A4C707E5F",hash_generated_method="7D2535B6C55EA233FAA41D561AE981CE") public NullWriter(){
}
| Constructs a new NullWriter. |
private void showFeedback(String message){
if (myHost != null) {
myHost.showFeedback(message);
}
else {
System.out.println(message);
}
}
| Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. |
public boolean isFinished(){
AsyncHttpRequest _request=request.get();
return _request == null || _request.isDone();
}
| Returns true if this task completed. Completion may be due to normal termination, an exception, or cancellation -- in all of these cases, this method will return true. |
public static void declareAll(ExtensionProfile profile){
profile.declareAdditionalNamespace(NS);
profile.declare(BaseEntry.class,MediaGroup.getDefaultDescription());
profile.declare(BaseEntry.class,MediaContent.getDefaultDescription(false));
profile.declare(MediaGroup.class,MediaContent.getDefaultDescription(true));
for ( ExtensionDescription desc : STANDARD_EXTENSIONS) {
profile.declare(BaseEntry.class,desc);
profile.declare(BaseFeed.class,desc);
profile.declare(MediaGroup.class,desc);
profile.declare(MediaContent.class,desc);
}
}
| Extends given profile with Yahoo media RSS extensions. |
@SuppressWarnings("unchecked") protected E removeAt(int pos){
if (pos < 0 || pos >= size) {
return null;
}
final E ret=(E)queue[pos];
final Object reinsert=queue[size - 1];
queue[size - 1]=null;
size--;
heapifyDown(pos,reinsert);
heapModified();
return ret;
}
| Remove the element at the given position. |
public static CompactSketch union(CompactSketch skA,CompactSketch skB){
final short seedHash=checkOrderedAndSeedHash(skA,skB);
long thetaLong=Math.min(skA.getThetaLong(),skB.getThetaLong());
int indexA=0;
int indexB=0;
int outCount=0;
long[] cacheA=skA.getCache();
long[] cacheB=skB.getCache();
long[] outCache=new long[cacheA.length + cacheB.length];
while ((indexA < cacheA.length) || (indexB < cacheB.length)) {
long hashA=(indexA >= cacheA.length) ? thetaLong : cacheA[indexA];
long hashB=(indexB >= cacheB.length) ? thetaLong : cacheB[indexB];
if (hashA >= thetaLong && hashB >= thetaLong) {
break;
}
if (hashA == hashB) {
outCache[outCount++]=hashA;
++indexA;
++indexB;
}
else if (hashA < hashB) {
outCache[outCount++]=hashA;
++indexA;
}
else {
outCache[outCount++]=hashB;
++indexB;
}
}
boolean empty=skA.isEmpty() && skB.isEmpty();
return new HeapCompactOrderedSketch(Arrays.copyOf(outCache,outCount),empty,seedHash,outCount,thetaLong);
}
| This implements a stateless, pair-wise union operation on ordered, CompactSketches that are either Heap-based or Direct. |
private void writeDataToFile(File file) throws FileNotFoundException, IOException {
FileOutputStream fos=new FileOutputStream(file);
try {
fos.write(CONTENT_AS_BYTES);
}
finally {
fos.close();
}
}
| Initializes test file. |
@SuppressWarnings({"unchecked","rawtypes"}) public void fireChange(final Property property){
for ( final EntityChangeListener l : changeListeners) {
l.entityChanged(this,property);
}
}
| Fire change to all registered listeners. |
private void assertReadVarint(byte[] data,long value) throws Exception {
CodedInputStream input=CodedInputStream.newInstance(data);
assertEquals((int)value,input.readRawVarint32());
assertDataConsumed(data,input);
input=CodedInputStream.newInstance(data);
assertEquals(value,input.readRawVarint64());
assertDataConsumed(data,input);
input=CodedInputStream.newInstance(data);
assertEquals(value,input.readRawVarint64SlowPath());
assertDataConsumed(data,input);
input=CodedInputStream.newInstance(data);
assertTrue(input.skipField(WireFormat.WIRETYPE_VARINT));
assertDataConsumed(data,input);
for (int blockSize=1; blockSize <= 16; blockSize*=2) {
input=CodedInputStream.newInstance(new SmallBlockInputStream(data,blockSize));
assertEquals((int)value,input.readRawVarint32());
assertDataConsumed(data,input);
input=CodedInputStream.newInstance(new SmallBlockInputStream(data,blockSize));
assertEquals(value,input.readRawVarint64());
assertDataConsumed(data,input);
input=CodedInputStream.newInstance(new SmallBlockInputStream(data,blockSize));
assertEquals(value,input.readRawVarint64SlowPath());
assertDataConsumed(data,input);
input=CodedInputStream.newInstance(new SmallBlockInputStream(data,blockSize));
assertTrue(input.skipField(WireFormat.WIRETYPE_VARINT));
assertDataConsumed(data,input);
}
byte[] longerData=new byte[data.length + 1];
System.arraycopy(data,0,longerData,0,data.length);
InputStream rawInput=new ByteArrayInputStream(longerData);
assertEquals((int)value,CodedInputStream.readRawVarint32(rawInput));
assertEquals(1,rawInput.available());
}
| Parses the given bytes using readRawVarint32() and readRawVarint64() and checks that the result matches the given value. |
public double distance(IMultiPoint imp){
if (imp.dimensionality() != 2) {
throw new IllegalArgumentException("distance computation can only be performed between two-dimensional points");
}
double ox=imp.getCoordinate(1);
double oy=imp.getCoordinate(2);
return Math.sqrt((ox - x) * (ox - x) + (oy - y) * (oy - y));
}
| Return the Euclidean distance between the given multipoint. Ensures that only valid for two-dimensional comparison. |
public PacProxyException(String message){
super(message);
}
| Creates a new PacProxyException with the specified message. |
private Segment segmentFor(int hash){
return segs[(hash >>> segmentShift) & segmentMask];
}
| Returns the segment that should be used for key with given hash |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:34:10.558 -0500",hash_original_method="668D89CF48F3ADC6BE7AF94D782DA652",hash_generated_method="2ABA277C680FC2569DEF64D5B0C8092B") public ColorMatrix(ColorMatrix src){
System.arraycopy(src.mArray,0,mArray,0,20);
}
| Create a new colormatrix initialized with the specified colormatrix. |
public DistributedLogMultiStreamWriter build(){
Preconditions.checkArgument((null != _streams && !_streams.isEmpty()),"No streams provided");
Preconditions.checkNotNull(_client,"No distributedlog client provided");
Preconditions.checkNotNull(_codec,"No compression codec provided");
Preconditions.checkArgument(_firstSpeculativeTimeoutMs > 0 && _firstSpeculativeTimeoutMs <= _maxSpeculativeTimeoutMs && _speculativeBackoffMultiplier > 0 && _maxSpeculativeTimeoutMs < _requestTimeoutMs,"Invalid speculative timeout settings");
return new DistributedLogMultiStreamWriter(_streams,_client,Math.min(_bufferSize,MAX_LOGRECORDSET_SIZE),_flushIntervalMs,_requestTimeoutMs,_firstSpeculativeTimeoutMs,_maxSpeculativeTimeoutMs,_speculativeBackoffMultiplier,_codec,_ticker,_executorService);
}
| Build the multi stream writer. |
public void clear(){
userHostMap.clear();
}
| Clear all stored UUID-vhosts. |
public final void print(boolean b) throws IOException {
print(b ? "true" : "false");
}
| Prints a boolean. |
public void squareThis(){
long[] pol=getElement();
int f=mLength - 1;
int b=mBit - 1;
long TWOTOMAXLONGM1=mBitmask[MAXLONG - 1];
boolean old, now;
old=(pol[f] & mBitmask[b]) != 0;
for (int i=0; i < f; i++) {
now=(pol[i] & TWOTOMAXLONGM1) != 0;
pol[i]=pol[i] << 1;
if (old) {
pol[i]^=1;
}
old=now;
}
now=(pol[f] & mBitmask[b]) != 0;
pol[f]=pol[f] << 1;
if (old) {
pol[f]^=1;
}
if (now) {
pol[f]^=mBitmask[b + 1];
}
assign(pol);
}
| squares <tt>this</tt> element. |
public static HostAndPortRange parse(String addrStr,int dfltPortFrom,int dfltPortTo,String errMsgPrefix) throws IgniteCheckedException {
assert dfltPortFrom <= dfltPortTo;
String host;
int portFrom;
int portTo;
final int colIdx=addrStr.indexOf(':');
if (colIdx > 0) {
String portFromStr;
String portToStr;
host=addrStr.substring(0,colIdx);
String portStr=addrStr.substring(colIdx + 1,addrStr.length());
if (F.isEmpty(portStr)) throw createParseError(addrStr,errMsgPrefix,"port range is not specified");
int portRangeIdx=portStr.indexOf("..");
if (portRangeIdx >= 0) {
portFromStr=portStr.substring(0,portRangeIdx);
portToStr=portStr.substring(portRangeIdx + 2,portStr.length());
}
else {
portFromStr=portStr;
portToStr=portStr;
}
portFrom=parsePort(portFromStr,addrStr,errMsgPrefix);
portTo=parsePort(portToStr,addrStr,errMsgPrefix);
if (portFrom > portTo) throw createParseError(addrStr,errMsgPrefix,"start port cannot be less than end port");
}
else {
host=addrStr;
portFrom=dfltPortFrom;
portTo=dfltPortTo;
}
return new HostAndPortRange(host,portFrom,portTo);
}
| Parse string into host and port pair. |
public String toString(int max){
ensureOpen();
StringBuilder sb=new StringBuilder();
int upperl=Math.min(max,indexReader.maxDoc());
for (int i=0; i < upperl; i++) {
try {
FacetLabel category=this.getPath(i);
if (category == null) {
sb.append(i + ": NULL!! \n");
continue;
}
if (category.length == 0) {
sb.append(i + ": EMPTY STRING!! \n");
continue;
}
sb.append(i + ": " + category.toString()+ "\n");
}
catch ( IOException e) {
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST,e.getMessage(),e);
}
}
}
return sb.toString();
}
| Returns ordinal -> label mapping, up to the provided max ordinal or number of ordinals, whichever is smaller. |
public boolean equals(Object other){
if (other == null) return false;
if (!other.getClass().equals(this.getClass())) return false;
NameValue that=(NameValue)other;
if (this == that) return true;
if (this.name == null && that.name != null || this.name != null && that.name == null) return false;
if (this.name != null && that.name != null && this.name.compareToIgnoreCase(that.name) != 0) return false;
if (this.value != null && that.value == null || this.value == null && that.value != null) return false;
if (this.value == that.value) return true;
if (value instanceof String) {
if (isQuotedString) return this.value.equals(that.value);
String val=(String)this.value;
String val1=(String)that.value;
return val.compareToIgnoreCase(val1) == 0;
}
else return this.value.equals(that.value);
}
| Equality comparison predicate. |
public CacheHeader(String key,Entry entry){
this.key=key;
this.size=entry.data.length;
this.etag=entry.etag;
this.serverDate=entry.serverDate;
this.lastModified=entry.lastModified;
this.ttl=entry.ttl;
this.softTtl=entry.softTtl;
this.responseHeaders=entry.responseHeaders;
}
| Instantiates a new CacheHeader object |
public final BufferedImage filter(BufferedImage src,BufferedImage dst){
if (src == null) {
throw new NullPointerException("src image is null");
}
if (src == dst) {
throw new IllegalArgumentException("src image cannot be the " + "same as the dst image");
}
boolean needToConvert=false;
ColorModel srcCM=src.getColorModel();
ColorModel dstCM;
BufferedImage origDst=dst;
if (dst == null) {
dst=createCompatibleDestImage(src,null);
dstCM=srcCM;
origDst=dst;
}
else {
dstCM=dst.getColorModel();
if (srcCM.getColorSpace().getType() != dstCM.getColorSpace().getType()) {
int type=xform.getType();
boolean needTrans=((type & (xform.TYPE_MASK_ROTATION | xform.TYPE_GENERAL_TRANSFORM)) != 0);
if (!needTrans && type != xform.TYPE_TRANSLATION && type != xform.TYPE_IDENTITY) {
double[] mtx=new double[4];
xform.getMatrix(mtx);
needTrans=(mtx[0] != (int)mtx[0] || mtx[3] != (int)mtx[3]);
}
if (needTrans && srcCM.getTransparency() == Transparency.OPAQUE) {
ColorConvertOp ccop=new ColorConvertOp(hints);
BufferedImage tmpSrc=null;
int sw=src.getWidth();
int sh=src.getHeight();
if (dstCM.getTransparency() == Transparency.OPAQUE) {
tmpSrc=new BufferedImage(sw,sh,BufferedImage.TYPE_INT_ARGB);
}
else {
WritableRaster r=dstCM.createCompatibleWritableRaster(sw,sh);
tmpSrc=new BufferedImage(dstCM,r,dstCM.isAlphaPremultiplied(),null);
}
src=ccop.filter(src,tmpSrc);
}
else {
needToConvert=true;
dst=createCompatibleDestImage(src,null);
}
}
}
if (interpolationType != TYPE_NEAREST_NEIGHBOR && dst.getColorModel() instanceof IndexColorModel) {
dst=new BufferedImage(dst.getWidth(),dst.getHeight(),BufferedImage.TYPE_INT_ARGB);
}
if (ImagingLib.filter(this,src,dst) == null) {
throw new ImagingOpException("Unable to transform src image");
}
if (needToConvert) {
ColorConvertOp ccop=new ColorConvertOp(hints);
ccop.filter(dst,origDst);
}
else if (origDst != dst) {
java.awt.Graphics2D g=origDst.createGraphics();
try {
g.setComposite(AlphaComposite.Src);
g.drawImage(dst,0,0,null);
}
finally {
g.dispose();
}
}
return origDst;
}
| Transforms the source <CODE>BufferedImage</CODE> and stores the results in the destination <CODE>BufferedImage</CODE>. If the color models for the two images do not match, a color conversion into the destination color model is performed. If the destination image is null, a <CODE>BufferedImage</CODE> is created with the source <CODE>ColorModel</CODE>. <p> The coordinates of the rectangle returned by <code>getBounds2D(BufferedImage)</code> are not necessarily the same as the coordinates of the <code>BufferedImage</code> returned by this method. If the upper-left corner coordinates of the rectangle are negative then this part of the rectangle is not drawn. If the upper-left corner coordinates of the rectangle are positive then the filtered image is drawn at that position in the destination <code>BufferedImage</code>. <p> An <CODE>IllegalArgumentException</CODE> is thrown if the source is the same as the destination. |
public final boolean checkTag(int identifier){
return this.id == identifier;
}
| Tests provided identifier. |
public void deleteKernel(String name){
Kernel kernel=getKernelByName(name);
if (kernel != null) {
kernel.dispose();
Integer oldSize=Integer.valueOf(_kernelHashTable.size());
_kernelHashTable.remove(name);
setDirtyAndFirePropertyChange(KERNEL_LISTLENGTH_CHANGED_PROPERTY,oldSize,Integer.valueOf(_kernelHashTable.size()));
}
}
| Delete a Kernel by name |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public void testWriteVarint() throws Exception {
assertWriteVarint(bytes(0x00),0);
assertWriteVarint(bytes(0x01),1);
assertWriteVarint(bytes(0x7f),127);
assertWriteVarint(bytes(0xa2,0x74),(0x22 << 0) | (0x74 << 7));
assertWriteVarint(bytes(0xbe,0xf7,0x92,0x84,0x0b),(0x3e << 0) | (0x77 << 7) | (0x12 << 14)| (0x04 << 21)| (0x0bL << 28));
assertWriteVarint(bytes(0xbe,0xf7,0x92,0x84,0x1b),(0x3e << 0) | (0x77 << 7) | (0x12 << 14)| (0x04 << 21)| (0x1bL << 28));
assertWriteVarint(bytes(0x80,0xe6,0xeb,0x9c,0xc3,0xc9,0xa4,0x49),(0x00 << 0) | (0x66 << 7) | (0x6b << 14)| (0x1c << 21)| (0x43L << 28)| (0x49L << 35)| (0x24L << 42)| (0x49L << 49));
assertWriteVarint(bytes(0x9b,0xa8,0xf9,0xc2,0xbb,0xd6,0x80,0x85,0xa6,0x01),(0x1b << 0) | (0x28 << 7) | (0x79 << 14)| (0x42 << 21)| (0x3bL << 28)| (0x56L << 35)| (0x00L << 42)| (0x05L << 49)| (0x26L << 56)| (0x01L << 63));
}
| Tests writeRawVarint32() and writeRawVarint64(). |
@Override public int readTimeout(byte[] buffer,int offset,int length,long timeout) throws IOException {
int sublen=getDelegate().readTimeout(buffer,offset,length,timeout);
if (sublen > 0) {
logStream().write(buffer,offset,sublen);
}
return sublen;
}
| Reads the next chunk from the stream in non-blocking mode. |
@LogMessageDoc(level="ERROR",message="Failed to clear all flows on switch {switch}",explanation="An I/O error occured while trying send " + "topology discovery packet",recommendation=LogMessageDoc.CHECK_SWITCH) public void doMultiActionPacketOut(byte[] packetData,IOFSwitch sw,Set<Short> ports,FloodlightContext cntx){
if (ports == null) return;
if (packetData == null || packetData.length <= 0) return;
OFPacketOut po=(OFPacketOut)floodlightProvider.getOFMessageFactory().getMessage(OFType.PACKET_OUT);
List<OFAction> actions=new ArrayList<OFAction>();
for ( short p : ports) {
actions.add(new OFActionOutput(p,(short)0));
}
po.setActions(actions);
po.setActionsLength((short)(OFActionOutput.MINIMUM_LENGTH * ports.size()));
po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
po.setInPort(OFPort.OFPP_NONE.getValue());
po.setPacketData(packetData);
short poLength=(short)(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() + packetData.length);
po.setLength(poLength);
try {
if (log.isTraceEnabled()) {
log.trace("write broadcast packet on switch-id={} " + "interaces={} packet-data={} packet-out={}",new Object[]{sw.getId(),ports,packetData,po});
}
sw.write(po,cntx);
}
catch ( IOException e) {
log.error("Failure writing packet out",e);
}
}
| TODO This method must be moved to a layer below forwarding so that anyone can use it. |
public NaryJoin(TupleExpr... args){
super(args);
}
| Creates a new natural join operator. |
public ResultSet read(Reader reader,String[] colNames) throws IOException {
init(null,null);
this.input=reader;
return readResultSet(colNames);
}
| Reads CSV data from a reader and returns a result set. The rows in the result set are created on demand, that means the reader is kept open until all rows are read or the result set is closed. |
public boolean isProcessing(){
Object oo=get_Value(COLUMNNAME_Processing);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Process Now. |
public void memberJoined(final InternalDistributedMember id){
if (!isListening()) {
return;
}
synchronized (this) {
if (!this.distributedMembers.contains(id)) {
this.distributedMembers.add(id);
addPendingJoin(id);
joinProcessor.resumeHandling();
}
}
}
| This method is invoked when a new member joins the system. If the member is an application VM or a GemFire system manager, we note it. |
public StringSendPacket send(String str,SendListener listener){
if (str == null) throw new NullPointerException("Send string can't be null.");
StringSendPacket entity=null;
try {
entity=new StringSendPacket(str,listener);
send(entity);
}
catch ( Exception e) {
e.printStackTrace();
}
return entity;
}
| Send string to queue |
@Override public Future<List<Future<DLSN>>> writeBulk(final List<LogRecord> records){
final Stopwatch stopwatch=Stopwatch.createStarted();
return Future.value(asyncWriteBulk(records)).addEventListener(new OpStatsListener<List<Future<DLSN>>>(bulkWriteOpStatsLogger,stopwatch));
}
| Write many log records to the stream. The return type here is unfortunate but its a direct result of having to combine FuturePool and the asyncWriteBulk method which returns a future as well. The problem is the List that asyncWriteBulk returns can't be materialized until getLogSegmentWriter completes, so it has to be wrapped in a future itself. |
private void trimPc(Node t){
for ( Node x : new LinkedList<>(pc.get(t))) {
if (!pc.containsKey(x)) {
pc.put(x,mmpc(x));
}
if (!pc.get(x).contains(t)) {
pc.get(t).remove(x);
}
}
}
| Trims away false positives from the given node. Used in the symmetric algorithm. |
public void addItems(List<T> items){
if (items == null || items.isEmpty()) {
return;
}
if (mItemList != null && mItemList.isEmpty()) {
mItemList.addAll(items);
}
else {
mItemList.addAll(items);
}
mScrollAdapter=new AutoScrollPagerAdapter<T>(mItemList,this);
this.setAdapter(mScrollAdapter);
}
| Add set of item. |
synchronized void commit(Session session){
session.setAllCommitted();
}
| Commit the current transaction of the given session. |
public JSONObject(Object bean){
this();
this.populateMap(bean);
}
| Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named <code>"getName"</code>, and if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, then the JSONObject will contain <code>"name": "Larry Fine"</code>. |
public void runBenchmarks(Reporter reporter,boolean verbose){
for (int i=0; i < binfo.length; i++) {
if (verbose) System.out.println("Running benchmark " + i + " ("+ binfo[i].getName()+ ")");
try {
binfo[i].runBenchmark();
}
catch ( Exception e) {
System.err.println("Error: benchmark " + i + " failed: "+ e);
e.printStackTrace();
}
cleanup();
}
try {
reporter.writeReport(binfo,System.getProperties());
}
catch ( IOException e) {
System.err.println("Error: failed to write benchmark report");
}
}
| Run benchmarks, writing results to the given reporter. |
public static Container encloseIn(int columns,boolean growHorizontally,Component... cmps){
int rows=cmps.length;
if (rows % columns > 0) {
rows=rows / columns + 1;
}
else {
rows=rows / columns;
}
TableLayout tl=new TableLayout(rows,columns);
tl.setGrowHorizontally(growHorizontally);
return Container.encloseIn(tl,cmps);
}
| <p>Creates a table layout container, the number of rows is automatically calculated based on the number of columns. See usage:</p> <script src="https://gist.github.com/codenameone/2b4d9a13f409e297fb2e.js"></script> <img src="https://www.codenameone.com/img/developer-guide/table-layout-enclose.png" alt="TableLayout that grows the last column" /> |
public void clear(){
int oldSize=size();
super.clear();
if (oldSize > 0 && getComponent() != null) {
getComponent().componentInputMapChanged(this);
}
}
| Removes all the mappings from this object. |
public static String readStream(InputStream in){
BufferedReader reader=new BufferedReader(new InputStreamReader(in));
StringBuilder sb=new StringBuilder();
String line=null;
try {
while ((line=reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch ( IOException e) {
FreshAirLog.e("Error reading stream",e);
}
finally {
try {
in.close();
}
catch ( IOException e) {
}
try {
reader.close();
}
catch ( IOException e) {
}
}
return sb.toString();
}
| Utility method for pulling plain text from an InputStream object |
@Override public void eUnset(int featureID){
switch (featureID) {
case StextPackage.EVENT_RAISING_EXPRESSION__EVENT:
setEvent((Expression)null);
return;
case StextPackage.EVENT_RAISING_EXPRESSION__VALUE:
setValue((Expression)null);
return;
}
super.eUnset(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void tagExport(String[] names,int[] ids) throws IOException {
if (tags != null) {
tags.tagExport(names,ids);
}
}
| SWFTagTypes interface |
private void generateL1(){
int dim=vi[vi.length - 1] - vi[0];
this.A1=new short[dim][dim];
this.A1inv=null;
ComputeInField c=new ComputeInField();
while (A1inv == null) {
for (int i=0; i < dim; i++) {
for (int j=0; j < dim; j++) {
A1[i][j]=(short)(sr.nextInt() & GF2Field.MASK);
}
}
A1inv=c.inverse(A1);
}
b1=new short[dim];
for (int i=0; i < dim; i++) {
b1[i]=(short)(sr.nextInt() & GF2Field.MASK);
}
}
| This function generates the invertible affine linear map L1 = A1*x + b1 <p> The translation part b1, is stored in a separate array. The inverse of the matrix-part of L1 A1inv is also computed here. </p><p> This linear map hides the output of the map F. It is on k^(n-v1). </p> |
public void testGetAttributeNodeNS1() throws Throwable {
Document doc;
Element element;
Attr attribute1;
Attr attribute2;
Attr attribute;
String attrValue;
String attrName;
String attNodeName;
String attrLocalName;
String attrNS;
doc=(Document)load("staffNS",builder);
element=doc.createElementNS("namespaceURI","root");
attribute1=doc.createAttributeNS("http://www.w3.org/DOM/Level2","l2:att");
element.setAttributeNodeNS(attribute1);
attribute2=doc.createAttributeNS("http://www.w3.org/DOM/Level1","att");
element.setAttributeNodeNS(attribute2);
attribute=element.getAttributeNodeNS("http://www.w3.org/DOM/Level2","att");
attrValue=attribute.getNodeValue();
attrName=attribute.getName();
attNodeName=attribute.getNodeName();
attrLocalName=attribute.getLocalName();
attrNS=attribute.getNamespaceURI();
assertEquals("elementgetattributenodens01_attrValue","",attrValue);
assertEquals("elementgetattributenodens01_attrName","l2:att",attrName);
assertEquals("elementgetattributenodens01_attrNodeName","l2:att",attNodeName);
assertEquals("elementgetattributenodens01_attrLocalName","att",attrLocalName);
assertEquals("elementgetattributenodens01_attrNs","http://www.w3.org/DOM/Level2",attrNS);
}
| Runs the test case. |
public static boolean checkURLforSpiders(HttpServletRequest request){
boolean result=false;
String spiderRequest=(String)request.getAttribute("_REQUEST_FROM_SPIDER_");
if (UtilValidate.isNotEmpty(spiderRequest)) {
if ("Y".equals(spiderRequest)) {
return true;
}
else {
return false;
}
}
else {
String initialUserAgent=request.getHeader("User-Agent") != null ? request.getHeader("User-Agent") : "";
List<String> spiderList=StringUtil.split(UtilProperties.getPropertyValue("url","link.remove_lsessionid.user_agent_list"),",");
if (UtilValidate.isNotEmpty(spiderList)) {
for ( String spiderNameElement : spiderList) {
Pattern pattern=null;
try {
pattern=PatternFactory.createOrGetPerl5CompiledPattern(spiderNameElement,false);
}
catch ( MalformedPatternException e) {
Debug.logError(e,module);
}
PatternMatcher matcher=new Perl5Matcher();
if (matcher.contains(initialUserAgent,pattern)) {
request.setAttribute("_REQUEST_FROM_SPIDER_","Y");
result=true;
break;
}
}
}
}
if (!result) {
request.setAttribute("_REQUEST_FROM_SPIDER_","N");
}
return result;
}
| checks, if the current request comes from a searchbot |
private void useGemFirePropertiesFileInTemporaryFolder(final String fileName,final Properties gemfireProperties) throws Exception {
File propertiesFile=new File(this.temporaryFolder.getRoot().getCanonicalPath(),fileName);
System.setProperty(DistributedSystem.PROPERTIES_FILE_PROPERTY,propertiesFile.getCanonicalPath());
gemfireProperties.store(new FileWriter(propertiesFile,false),this.testName.getMethodName());
assertThat(propertiesFile.isFile()).isTrue();
assertThat(propertiesFile.exists()).isTrue();
}
| Creates a gemfire properties file in temporaryFolder: <li>creates <code>fileName</code> in <code>temporaryFolder</code> <li>sets "gemfirePropertyFile" system property <li>writes <code>gemfireProperties</code> to the file |
@Override @Deprecated public void shutdown(){
throw new UnsupportedOperationException();
}
| Not supported and throws an exception when used. |
@Override public void update(){
dispatchUpdate();
}
| UpdateDispatcher.update() -> BaseObservable.dispatchUpdate() |
public void updateUI(){
setUI((InternalFrameUI)UIManager.getUI(this));
invalidate();
if (desktopIcon != null) {
desktopIcon.updateUIWhenHidden();
}
}
| Notification from the <code>UIManager</code> that the look and feel has changed. Replaces the current UI object with the latest version from the <code>UIManager</code>. |
public Extensions extensions(){
if (extensions == null) {
extensions=new Extensions(this);
}
return extensions;
}
| Offers common utility extensions. |
public static Context fromUserPass(Subject s,String user,char[] pass,boolean storeKey) throws Exception {
Context out=new Context();
out.name=user;
out.s=s;
Krb5LoginModule krb5=new Krb5LoginModule();
Map<String,String> map=new HashMap<>();
Map<String,Object> shared=new HashMap<>();
if (pass != null) {
map.put("useFirstPass","true");
shared.put("javax.security.auth.login.name",user);
shared.put("javax.security.auth.login.password",pass);
}
else {
map.put("doNotPrompt","true");
map.put("useTicketCache","true");
if (user != null) {
map.put("principal",user);
}
}
if (storeKey) {
map.put("storeKey","true");
}
krb5.initialize(out.s,null,shared,map);
krb5.login();
krb5.commit();
return out;
}
| Logins with username/password as an existing Subject. The same subject can be used multiple times to simulate multiple logins. |
@SuppressWarnings("unchecked") public <T>Source<T> sequence(T... ts){
return sequence(java.util.Arrays.asList(ts));
}
| Generates a value in order deterministically from the supplied values. If more examples are requested than are supplied then the sequence will be repeated. |
public Builder cacheOnDisc(){
cacheOnDisc=true;
return this;
}
| Loaded image will be cached on disc |
private void removeEntry(String key){
CacheHeader entry=mEntries.get(key);
if (entry != null) {
mTotalSize-=entry.size;
mEntries.remove(key);
}
}
| Removes the entry identified by 'key' from the cache. |
public JSONObject put(String key,boolean value) throws JSONException {
this.put(key,value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
| Put a key/boolean pair in the JSONObject. |
public static void writeBoolList(IonWriter writer,boolean[] values) throws IOException {
if (writer instanceof PrivateListWriter) {
((PrivateListWriter)writer).writeBoolList(values);
return;
}
writer.stepIn(IonType.LIST);
for (int ii=0; ii < values.length; ii++) {
writer.writeBool(values[ii]);
}
writer.stepOut();
}
| writes an IonList with a series of IonBool values. This starts a List, writes the values (without any annoations) and closes the list. For text and tree writers this is just a convienience, but for the binary writer it can be optimized internally. |
public OutlierResult run(Database database,Relation<N> nrel,Relation<? extends NumberVector> relation){
final NeighborSetPredicate npred=getNeighborSetPredicateFactory().instantiate(database,nrel);
WritableDoubleDataStore means=DataStoreUtil.makeDoubleStorage(relation.getDBIDs(),DataStoreFactory.HINT_TEMP);
CovarianceMatrix covm=new CovarianceMatrix(2);
for (DBIDIter iditer=relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
final double local=relation.get(iditer).doubleValue(0);
Mean mean=new Mean();
DBIDs neighbors=npred.getNeighborDBIDs(iditer);
for (DBIDIter iter=neighbors.iter(); iter.valid(); iter.advance()) {
if (DBIDUtil.equal(iditer,iter)) {
continue;
}
mean.put(relation.get(iter).doubleValue(0));
}
final double m;
if (mean.getCount() > 0) {
m=mean.getMean();
}
else {
m=local;
}
means.putDouble(iditer,m);
covm.put(new double[]{local,m});
}
final double slope, inter;
{
double[] meanv=covm.getMeanVector();
double[][] fmat=covm.destroyToSampleMatrix();
final double covxx=fmat[0][0], covxy=fmat[0][1];
slope=covxy / covxx;
inter=meanv[1] - slope * meanv[0];
}
WritableDoubleDataStore scores=DataStoreUtil.makeDoubleStorage(relation.getDBIDs(),DataStoreFactory.HINT_STATIC);
MeanVariance mv=new MeanVariance();
for (DBIDIter iditer=relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
double y_i=relation.get(iditer).doubleValue(0);
double e=means.doubleValue(iditer) - (slope * y_i + inter);
scores.putDouble(iditer,e);
mv.put(e);
}
DoubleMinMax minmax=new DoubleMinMax();
{
final double mean=mv.getMean();
final double variance=mv.getNaiveStddev();
for (DBIDIter iditer=relation.iterDBIDs(); iditer.valid(); iditer.advance()) {
double score=Math.abs((scores.doubleValue(iditer) - mean) / variance);
minmax.put(score);
scores.putDouble(iditer,score);
}
}
DoubleRelation scoreResult=new MaterializedDoubleRelation("SPO","Scatterplot-Outlier",scores,relation.getDBIDs());
OutlierScoreMeta scoreMeta=new BasicOutlierScoreMeta(minmax.getMin(),minmax.getMax(),0.0,Double.POSITIVE_INFINITY,0);
OutlierResult or=new OutlierResult(scoreMeta,scoreResult);
or.addChildResult(npred);
return or;
}
| Main method. |
private String createString(String f){
return "maxThreadsPerBlock=" + maxThreadsPerBlock + f+ "maxThreadsDim="+ Arrays.toString(maxThreadsDim)+ f+ "maxGridSize="+ Arrays.toString(maxGridSize)+ f+ "sharedMemPerBlock="+ sharedMemPerBlock+ f+ "totalConstantMemory="+ totalConstantMemory+ f+ "regsPerBlock="+ regsPerBlock+ f+ "SIMDWidth="+ SIMDWidth+ f+ "memPitch="+ memPitch+ f+ "regsPerBlock="+ regsPerBlock+ f+ "clockRate="+ clockRate+ f+ "textureAlign="+ textureAlign;
}
| Creates and returns a string representation of this object, using the given separator for the fields |
public void fireDataSourceRemoved(final int index){
for ( ChartListener listener : listenerList) {
listener.dataSourceRemoved(index);
}
}
| Fire data source removed event. |
public void testArrayListToJsonArrayConversion(){
try {
JSONArray array=StoreRetrieveData.toJSONArray(mTestData);
assertEquals(mTestData.size(),array.length());
}
catch ( Exception e) {
fail("Exception thrown when converting to JSONArray: " + e.getMessage());
}
}
| Ensure JSONArray conversion works as intended |
@DELETE @Produces(MediaType.APPLICATION_JSON) @Path("/{alertId}/triggers") @Description("Deletes all triggers for the given alert ID. All associations to alert notifications are also removed.") public Response deleteAllTriggersByAlertId(@Context HttpServletRequest req,@PathParam("alertId") BigInteger alertId){
if (alertId == null || alertId.compareTo(BigInteger.ZERO) < 1) {
throw new WebApplicationException("Alert Id cannot be null and must be a positive non-zero number.",Status.BAD_REQUEST);
}
Alert alert=alertService.findAlertByPrimaryKey(alertId);
if (alert == null) {
throw new WebApplicationException(Response.Status.NOT_FOUND.getReasonPhrase(),Response.Status.NOT_FOUND);
}
validateResourceAuthorization(req,alert.getOwner(),getRemoteUser(req));
for ( Notification notification : alert.getNotifications()) {
notification.setTriggers(new ArrayList<Trigger>(0));
}
alert.setTriggers(new ArrayList<Trigger>(0));
alert.setModifiedBy(getRemoteUser(req));
alertService.updateAlert(alert);
return Response.status(Status.OK).build();
}
| Deletes all triggers. |
@Override public void close(){
if (this.isTemporaryFile) {
File f1=new File(this.headerFile);
f1.delete();
f1=new File(this.dataFile);
f1.delete();
}
else {
if (saveChanges) {
if (isDirty) {
writeDataBlock();
}
findMinAndMaxVals();
writeHeaderFile();
}
}
grid=null;
}
| Used to perform closing functionality when a whiteboxRaster is no longer needed. |
static int findBestSampleSize(int actualWidth,int actualHeight,int desiredWidth,int desiredHeight){
double wr=(double)actualWidth / desiredWidth;
double hr=(double)actualHeight / desiredHeight;
double ratio=Math.min(wr,hr);
float n=1.0f;
while ((n * 2) <= ratio) {
n*=2;
}
return (int)n;
}
| Returns the largest power-of-two divisor for use in downscaling a bitmap that will not result in the scaling past the desired dimensions. |
protected void initView(){
p.setFakeBoldText(false);
p.setAntiAlias(true);
p.setTextSize(MINI_DAY_NUMBER_TEXT_SIZE);
p.setStyle(Style.FILL);
mMonthNumPaint=new Paint();
mMonthNumPaint.setFakeBoldText(true);
mMonthNumPaint.setAntiAlias(true);
mMonthNumPaint.setTextSize(MINI_DAY_NUMBER_TEXT_SIZE);
mMonthNumPaint.setColor(mFocusMonthColor);
mMonthNumPaint.setStyle(Style.FILL);
mMonthNumPaint.setTextAlign(Align.CENTER);
}
| Sets up the text and style properties for painting. Override this if you want to use a different paint. |
protected void validateStartState(State startState){
ValidationUtils.validateState(startState);
ValidationUtils.validateTaskStage(startState.taskState);
}
| This method validates a state object for internal consistency. |
public ColladaPhong(String ns){
super(ns);
}
| Construct an instance. |
public final static byte[] decode(char[] sArr){
int sLen=sArr != null ? sArr.length : 0;
if (sLen == 0) return new byte[0];
int sepCnt=0;
for (int i=0; i < sLen; i++) if (IA[sArr[i]] < 0) sepCnt++;
if ((sLen - sepCnt) % 4 != 0) return null;
int pad=0;
for (int i=sLen; i > 1 && IA[sArr[--i]] <= 0; ) if (sArr[i] == '=') pad++;
int len=((sLen - sepCnt) * 6 >> 3) - pad;
byte[] dArr=new byte[len];
for (int s=0, d=0; d < len; ) {
int i=0;
for (int j=0; j < 4; j++) {
int c=IA[sArr[s++]];
if (c >= 0) i|=c << (18 - j * 6);
else j--;
}
dArr[d++]=(byte)(i >> 16);
if (d < len) {
dArr[d++]=(byte)(i >> 8);
if (d < len) dArr[d++]=(byte)i;
}
}
return dArr;
}
| Decodes a BASE64 encoded char array. All illegal characters will be ignored and can handle both arrays with and without line separators. |
public void ConfigParams(){
int height=Config.singletonConfig.getHeight();
int width=Config.singletonConfig.getWidth();
assertEquals((height > 0) & (width > 0),true);
}
| Check height and width types served by the singleton class Config |
static boolean isXAWTToplevelWindow(long window){
return XToolkit.windowToXWindow(window) instanceof XWindowPeer;
}
| Checks if the given window is a Java window and is an instance of XWindowPeer |
public static ComponentUI createUI(JComponent h){
return new BETableHeaderUI();
}
| Creates the ui. |
private String createAttribute(AttributeModel attr){
StringBuffer sb=new StringBuffer();
sb.append(" ");
String visibility=attr.getVisibility().toString();
if (!visibility.equals("package")) {
sb.append(attr.getVisibility().toString());
sb.append(" ");
}
if (attr.isStatic()) {
sb.append("static ");
}
sb.append(attr.getType());
sb.append(" ");
sb.append(attr.getName());
if (attr.getParent() instanceof InterfaceModel) {
if (UMLJavaUtils.isPrimitive(attr.getType())) {
if (attr.getType().equals("boolean")) {
sb.append(" = false");
}
else {
sb.append(" = 0");
}
}
else {
sb.append(" = null");
}
}
sb.append(";");
return sb.toString();
}
| Creates a part of an attribute. |
public static synchronized Bitmap decodeSampledBitmapFromFile(String filename,int reqWidth,int reqHeight){
final BitmapFactory.Options options=new BitmapFactory.Options();
options.inJustDecodeBounds=true;
BitmapFactory.decodeFile(filename,options);
options.inSampleSize=calculateInSampleSize(options,reqWidth,reqHeight);
options.inJustDecodeBounds=false;
return BitmapFactory.decodeFile(filename,options);
}
| Decode and sample down a bitmap from a file to the requested width and height. |
public AudioData duplicate() throws IOException, ClassNotFoundException {
AudioData result=new AudioData();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(baos);
writeExternal(oos);
oos.close();
byte[] buf=baos.toByteArray();
baos.close();
ByteArrayInputStream bais=new ByteArrayInputStream(buf);
ObjectInputStream ois=new ObjectInputStream(bais);
result.readExternal(ois);
ois.close();
bais.close();
if (header != null) {
result.setHeader(header.clone());
}
return result;
}
| Duplicate this message / event. |
public static void main(String[] args){
try {
File rootFolder=GeneratorUtils.getRootFolder(args);
System.out.println(" ------------------------------------------------------------------------ ");
System.out.println(String.format("Searching for Extensions in %s",rootFolder.getAbsolutePath()));
System.out.println(" ------------------------------------------------------------------------ ");
findExtensions();
generateExtensionManager(rootFolder);
}
catch ( IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
| Entry point. --rootDir is the optional parameter. |
public void add(KeywordInfo info){
keywords.put(info.getKeyword(),info);
}
| Adds information about a keyword to this collection. |
private void addReference(final int sourcePosition,final int referencePosition){
if (srcAndRefPositions == null) {
srcAndRefPositions=new int[6];
}
if (referenceCount >= srcAndRefPositions.length) {
int[] a=new int[srcAndRefPositions.length + 6];
System.arraycopy(srcAndRefPositions,0,a,0,srcAndRefPositions.length);
srcAndRefPositions=a;
}
srcAndRefPositions[referenceCount++]=sourcePosition;
srcAndRefPositions[referenceCount++]=referencePosition;
}
| Adds a forward reference to this label. This method must be called only for a true forward reference, i.e. only if this label is not resolved yet. For backward references, the offset of the reference can be, and must be, computed and stored directly. |
public FileSystemConfiguration(FileSystemConfiguration cfg){
assert cfg != null;
blockSize=cfg.getBlockSize();
bufSize=cfg.getStreamBufferSize();
colocateMeta=cfg.isColocateMetadata();
dataCacheName=cfg.getDataCacheName();
dfltMode=cfg.getDefaultMode();
dualModeMaxPendingPutsSize=cfg.getDualModeMaxPendingPutsSize();
dualModePutExec=cfg.getDualModePutExecutorService();
dualModePutExecShutdown=cfg.getDualModePutExecutorServiceShutdown();
fragmentizerConcurrentFiles=cfg.getFragmentizerConcurrentFiles();
fragmentizerLocWritesRatio=cfg.getFragmentizerLocalWritesRatio();
fragmentizerEnabled=cfg.isFragmentizerEnabled();
fragmentizerThrottlingBlockLen=cfg.getFragmentizerThrottlingBlockLength();
fragmentizerThrottlingDelay=cfg.getFragmentizerThrottlingDelay();
secondaryFs=cfg.getSecondaryFileSystem();
initDfltPathModes=cfg.isInitializeDefaultPathModes();
ipcEndpointCfg=cfg.getIpcEndpointConfiguration();
ipcEndpointEnabled=cfg.isIpcEndpointEnabled();
maxSpace=cfg.getMaxSpaceSize();
maxTaskRangeLen=cfg.getMaximumTaskRangeLength();
metaCacheName=cfg.getMetaCacheName();
mgmtPort=cfg.getManagementPort();
name=cfg.getName();
pathModes=cfg.getPathModes();
perNodeBatchSize=cfg.getPerNodeBatchSize();
perNodeParallelBatchCnt=cfg.getPerNodeParallelBatchCount();
prefetchBlocks=cfg.getPrefetchBlocks();
relaxedConsistency=cfg.isRelaxedConsistency();
seqReadsBeforePrefetch=cfg.getSequentialReadsBeforePrefetch();
trashPurgeTimeout=cfg.getTrashPurgeTimeout();
updateFileLenOnFlush=cfg.isUpdateFileLengthOnFlush();
}
| Constructs the copy of the configuration. |
public QueryPanel(JFrame parent){
super();
m_Parent=parent;
m_QueryExecuteListeners=new HashSet<QueryExecuteListener>();
m_HistoryChangedListeners=new HashSet<HistoryChangedListener>();
m_DbUtils=null;
m_Connected=false;
createPanel();
}
| initializes the panel. |
public void loadDataFromPush(Node sourceNode,InputStream in,OutputStream out) throws IOException {
loadDataFromPush(sourceNode,null,in,out);
}
| Load database from input stream and write acknowledgment to output stream. This is used for a "push" request with a response of an acknowledgment. |
public TStructMember basicGetDefinedMember(){
return definedMember;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private void declareExtensions(){
new IssueCommentsFeed().declareExtensions(extProfile);
new IssuesFeed().declareExtensions(extProfile);
new ProjectsFeed().declareExtensions(extProfile);
}
| Declare the extensions of the feeds for the Project Hosting GData API. |
public void addMethodThrowingExceptionNoBidirectionalUpdate(MethodType type){
if (null == methodsThrowingThisException) {
methodsThrowingThisException=new MethodTypeSet();
}
methodsThrowingThisException.add(type);
}
| Adds a method that is throwing this class as exception WITHOUT setting the back-reference. Please be aware that this method should only be called internally as this might mess up the bidirectional structure. |
private boolean isValid(int type,String value){
if (value == null) {
return false;
}
if (ALLOWED_STRINGS[type] != null) {
return verifyStringGroup(value,ALLOWED_STRINGS[type]);
}
switch (type) {
case TYPE_NUMBER:
return verify(value,DIGITS,null);
case TYPE_PIXELS_OR_PERCENTAGE:
if (value.endsWith("%")) {
value=value.substring(0,value.length() - 1);
}
else if (value.endsWith("px")) {
value=value.substring(0,value.length() - 2);
}
return verify(value,DIGITS,null);
case TYPE_CHAR:
return verify(value,DIGITS | ABC,null,1,1);
case TYPE_COLOR:
if (value.length() == 0) {
return false;
}
if (value.charAt(0) != '#') {
return verifyStringGroup(value,COLOR_STRINGS);
}
else {
return verify(value.substring(1),HEX,null,3,6);
}
default :
return true;
}
}
| Verifies that the specified value conforms with the attribute's type restrictions. This basically checks the attribute type and according to that checks the value. |
public static Map<String,String> messageToMap(Message msg){
Map<String,String> map=new HashMap<>();
if (msg == null) return map;
if (msg.fixedHeader().messageType() == MqttMessageType.PUBLISH) {
MqttPublishVariableHeader variableHeader=(MqttPublishVariableHeader)msg.variableHeader();
MqttPublishPayload payload=(MqttPublishPayload)msg.payload();
map.put("type",String.valueOf(MqttMessageType.PUBLISH.value()));
map.put("retain",BooleanUtils.toString(msg.fixedHeader().retain(),"1","0"));
map.put("qos",String.valueOf(msg.fixedHeader().qos().value()));
map.put("dup",BooleanUtils.toString(msg.fixedHeader().dup(),"1","0"));
map.put("version",msg.additionalHeader().version().toString());
if (!msg.fixedHeader().retain()) map.put("clientId",msg.additionalHeader().clientId());
map.put("userName",msg.additionalHeader().userName());
map.put("topicName",variableHeader.topicName());
if (!msg.fixedHeader().retain()) map.put("packetId",String.valueOf(variableHeader.packetId()));
if (payload != null && payload.bytes() != null && payload.bytes().length > 0) try {
map.put("payload",new String(payload.bytes(),"ISO-8859-1"));
}
catch ( UnsupportedEncodingException ignore) {
}
return map;
}
else if (msg.fixedHeader().messageType() == MqttMessageType.PUBREL) {
MqttPacketIdVariableHeader variableHeader=(MqttPacketIdVariableHeader)msg.variableHeader();
map.put("type",String.valueOf(MqttMessageType.PUBREL.value()));
map.put("version",msg.additionalHeader().version().toString());
map.put("clientId",msg.additionalHeader().clientId());
map.put("userName",msg.additionalHeader().userName());
map.put("packetId",String.valueOf(variableHeader.packetId()));
return map;
}
else {
throw new IllegalArgumentException("Invalid in-flight MQTT message type: " + msg.fixedHeader().messageType());
}
}
| Convert (MQTT) Message to Map |
public void startStatementWithinTransaction(){
startStatement=-1;
}
| Start a new statement within a transaction. |
public void remove(){
throw new UnsupportedOperationException();
}
| Not supported. |
@Override public int hashCode(){
return this.hash;
}
| Returns the hash used for routing. Never negative. |
public static Integer createServerCache() throws Exception {
new OperationsPropagationDUnitTest().createCache(new Properties());
AttributesFactory factory=new AttributesFactory();
factory.setScope(Scope.DISTRIBUTED_ACK);
factory.setDataPolicy(DataPolicy.REPLICATE);
RegionAttributes attrs=factory.create();
region=cache.createRegion(REGION_NAME,attrs);
CacheServerImpl server=(CacheServerImpl)cache.addCacheServer();
assertNotNull(server);
int port=AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
server.setPort(port);
server.setNotifyBySubscription(true);
server.start();
return new Integer(server.getPort());
}
| Create the server |
public MethodInfo(ConstPool cp,String methodname,String desc){
this(cp);
accessFlags=0;
name=cp.addUtf8Info(methodname);
cachedName=methodname;
descriptor=constPool.addUtf8Info(desc);
}
| Constructs a <code>method_info</code> structure. The initial value of <code>access_flags</code> is zero. |
public DTMIterator createDTMIterator(String xpathString,PrefixResolver presolver){
return m_dtmManager.createDTMIterator(xpathString,presolver);
}
| Create a new <code>DTMIterator</code> based on an XPath <a href="http://www.w3.org/TR/xpath#NT-LocationPath>LocationPath</a> or a <a href="http://www.w3.org/TR/xpath#NT-UnionExpr">UnionExpr</a>. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.