code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
@Override public void run(){
amIActive=true;
String inputHeader=null;
String outputHeader=null;
int row, col, x, y;
int progress=0;
double z;
int i, c;
int[] dX=new int[]{1,1,1,0,-1,-1,-1,0};
int[] dY=new int[]{-1,0,1,1,1,0,-1,-1};
double zFactor=0;
double slopeThreshold=0;
double profCurvThreshold=0;
double planCurvThreshold=0;
double radToDeg=180 / Math.PI;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
for (i=0; i < args.length; i++) {
if (i == 0) {
inputHeader=args[i];
}
else if (i == 1) {
outputHeader=args[i];
}
else if (i == 2) {
zFactor=Double.parseDouble(args[i]);
}
else if (i == 3) {
slopeThreshold=Double.parseDouble(args[i]);
}
else if (i == 4) {
profCurvThreshold=Double.parseDouble(args[i]);
}
else if (i == 5) {
planCurvThreshold=Double.parseDouble(args[i]);
}
}
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster DEM=new WhiteboxRaster(inputHeader,"r");
int rows=DEM.getNumberRows();
int cols=DEM.getNumberColumns();
double noData=DEM.getNoDataValue();
double gridResX=DEM.getCellSizeX();
double gridResY=DEM.getCellSizeY();
double diagGridRes=Math.sqrt(gridResX * gridResX + gridResY * gridResY);
double[] gridLengths=new double[]{diagGridRes,gridResX,diagGridRes,gridResY,diagGridRes,gridResX,diagGridRes,gridResY};
double Zx, Zy, Zxx, Zyy, Zxy, p, Zx2, q, Zy2;
double fx, fy;
double gridResTimes2=gridResX * 2;
double gridResSquared=gridResX * gridResX;
double fourTimesGridResSquared=gridResSquared * 4;
double planCurv, profCurv, slope;
double eightGridRes=8 * gridResX;
double[] N=new double[8];
WhiteboxRaster output=new WhiteboxRaster(outputHeader,"rw",inputHeader,WhiteboxRaster.DataType.FLOAT,-999);
output.setPreferredPalette("landclass.pal");
output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS);
for (row=0; row < rows; row++) {
for (col=0; col < cols; col++) {
z=DEM.getValue(row,col);
if (z != noData) {
z=z * zFactor;
for (c=0; c < 8; c++) {
N[c]=DEM.getValue(row + dY[c],col + dX[c]);
if (N[c] != noData) {
N[c]=N[c] * zFactor;
}
else {
N[c]=z;
}
}
Zx=(N[1] - N[5]) / gridResTimes2;
Zy=(N[7] - N[3]) / gridResTimes2;
Zxx=(N[1] - 2 * z + N[5]) / gridResSquared;
Zyy=(N[7] - 2 * z + N[3]) / gridResSquared;
Zxy=(-N[6] + N[0] + N[4] - N[2]) / fourTimesGridResSquared;
Zx2=Zx * Zx;
Zy2=Zy * Zy;
p=Zx2 + Zy2;
q=p + 1;
if (p > 0) {
fy=(N[6] - N[4] + 2 * (N[7] - N[3]) + N[0] - N[2]) / eightGridRes;
fx=(N[2] - N[4] + 2 * (N[1] - N[5]) + N[0] - N[6]) / eightGridRes;
slope=Math.atan(Math.sqrt(fx * fx + fy * fy));
slope=slope * radToDeg;
planCurv=-1 * (Zxx * Zy2 - 2 * Zxy * Zx* Zy + Zyy * Zx2) / Math.pow(p,1.5);
planCurv=(planCurv * radToDeg);
profCurv=-1 * (Zxx * Zx2 + 2 * Zxy * Zx* Zy + Zyy * Zy2) / Math.pow(p * q,1.5);
profCurv=(profCurv * radToDeg);
if (profCurv < -profCurvThreshold && planCurv <= -planCurvThreshold & slope > slopeThreshold) {
output.setValue(row,col,1);
}
else if (profCurv < -profCurvThreshold && planCurv > planCurvThreshold && slope > slopeThreshold) {
output.setValue(row,col,2);
}
else if (profCurv > profCurvThreshold && planCurv <= planCurvThreshold && slope > slopeThreshold) {
output.setValue(row,col,3);
}
else if (profCurv > profCurvThreshold && planCurv > planCurvThreshold && slope > slopeThreshold) {
output.setValue(row,col,4);
}
else if (profCurv >= -profCurvThreshold && profCurv < profCurvThreshold && slope > slopeThreshold && planCurv <= -planCurvThreshold) {
output.setValue(row,col,5);
}
else if (profCurv >= -profCurvThreshold && profCurv < profCurvThreshold && slope > slopeThreshold && planCurv > planCurvThreshold) {
output.setValue(row,col,6);
}
else if (slope <= slopeThreshold) {
output.setValue(row,col,7);
}
else {
output.setValue(row,col,noData);
}
}
else {
output.setValue(row,col,noData);
}
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress=(int)(100f * row / (rows - 1));
updateProgress(progress);
}
output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
DEM.close();
output.close();
returnData(outputHeader);
String retstr="LANDFORM CLASSIFICATION KEY\n";
retstr+="\nValue:\tClass";
retstr+="\n1\tConvergent Footslope";
retstr+="\n2\tDivergent Footslope";
retstr+="\n3\tConvergent Shoulder";
retstr+="\n4\tDivergent Shoulder";
retstr+="\n5\tConvergent Backslope";
retstr+="\n6\tDivergent Backslope";
retstr+="\n7\tLevel";
returnData(retstr);
}
catch ( OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
}
catch ( Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(),e);
}
finally {
updateProgress("Progress: ",0);
amIActive=false;
myHost.pluginComplete();
}
}
| Used to execute this plugin tool. |
public R reduce(R r1,R r2){
return r1;
}
| Reduces two results into a combined result. The default implementation is to return the first parameter. The general contract of the method is that it may take any action whatsoever. |
public void numParameters(int num) throws IOException {
output.write(num);
}
| Writes <code>num_parameters</code> in <code>Runtime(In)VisibleParameterAnnotations_attribute</code>. This method must be followed by <code>num</code> calls to <code>numAnnotations()</code>. |
public ResultFormatter(Object result){
this.result=result;
printHeader=true;
}
| Creates a new formatter for a particular object. |
@Override public Eval<String> join(){
return Eval.later(null);
}
| Perform an asynchronous join operation |
public GetRequest type(@Nullable String type){
if (type == null) {
type="_all";
}
this.type=type;
return this;
}
| Sets the type of the document to fetch. |
@Override public ImmutableSet<Entry<K,V>> entries(){
ImmutableSet<Entry<K,V>> result=entries;
return result == null ? (entries=new EntrySet<K,V>(this)) : result;
}
| Returns an immutable collection of all key-value pairs in the multimap. Its iterator traverses the values for the first key, the values for the second key, and so on. |
private int luminance(int r,int g,int b){
return (int)((0.299 * r) + (0.58 * g) + (0.11 * b));
}
| Apply the luminance |
private void puntPlay(Team offense){
gameYardLine=(int)(100 - (gameYardLine + offense.getK(0).ratKickPow / 3 + 20 - 10 * Math.random()));
if (gameYardLine < 0) {
gameYardLine=20;
}
gameDown=1;
gameYardsNeed=10;
gamePoss=!gamePoss;
gameTime-=20 + 15 * Math.random();
}
| Punt the ball if it is a 4th down and decided not to go for it. Will turnover possession. |
private List<String[]> readSentence(BufferedReader aReader) throws IOException {
List<String[]> words=new ArrayList<String[]>();
String line;
boolean beginSentence=true;
while ((line=aReader.readLine()) != null) {
if (StringUtils.isBlank(line)) {
beginSentence=true;
break;
}
if (hasHeader && beginSentence) {
beginSentence=false;
continue;
}
String[] fields=line.split(columnSeparator.getValue());
if (!hasEmbeddedNamedEntity && fields.length != 2 + FORM) {
throw new IOException(String.format("Invalid file format. Line needs to have %d %s-separated fields: [%s]",2 + FORM,columnSeparator.getName(),line));
}
else if (hasEmbeddedNamedEntity && fields.length != 3 + FORM) {
throw new IOException(String.format("Invalid file format. Line needs to have %d %s-separated fields: [%s]",3 + FORM,columnSeparator.getName(),line));
}
words.add(fields);
}
if (line == null && words.isEmpty()) {
return null;
}
else {
return words;
}
}
| Read a single sentence. |
public static ConditionOperand OVERFLOW_FROM_SUB(){
return new ConditionOperand(OVERFLOW_FROM_SUB);
}
| Create the condition code operand for OVERFLOW_FROM_SUB |
protected void initCheckLists(){
List<IceMediaStream> streams=getStreamsWithPendingConnectivityEstablishment();
int streamCount=streams.size();
int maxCheckListSize=Integer.getInteger(StackProperties.MAX_CHECK_LIST_SIZE,DEFAULT_MAX_CHECK_LIST_SIZE);
int maxPerStreamSize=streamCount == 0 ? 0 : maxCheckListSize / streamCount;
for ( IceMediaStream stream : streams) {
logger.info("Init checklist for stream " + stream.getName());
stream.setMaxCheckListSize(maxPerStreamSize);
stream.initCheckList();
}
if (streamCount > 0) streams.get(0).getCheckList().computeInitialCheckListPairStates();
}
| Creates, initializes and orders the list of candidate pairs that would be used for the connectivity checks for all components in this stream. |
private void checkSearchables(ArrayList<SearchableInfo> searchablesList){
assertNotNull(searchablesList);
int count=searchablesList.size();
for (int ii=0; ii < count; ii++) {
SearchableInfo si=searchablesList.get(ii);
checkSearchable(si);
}
}
| Generic health checker for an array of searchables. This is designed to pass for any semi-legal searchable, without knowing much about the format of the underlying data. It's fairly easy for a non-compliant application to provide meta-data that will pass here (e.g. a non-existent suggestions authority). |
private void generateImplementsParcelableInterface(PsiClass targetPsiClass){
PsiJavaCodeReferenceElement referenceElement=factory.createReferenceFromText(PARCELABLE_CLASS_SIMPLE_NAME,null);
PsiReferenceList implementsList=targetPsiClass.getImplementsList();
if (null != implementsList) {
implementsList.add(referenceElement);
}
generateImportStatement(PARCELABLE_PACKAGE);
generateExtraMethods(targetPsiClass);
}
| Implement android.os.Parcelable interface |
private RemoteDirectorGroup fetchRDFGroupFromCache(Map<URI,RemoteDirectorGroup> rdfGroupCache,URI srdfGroupURI){
if (rdfGroupCache.containsKey(srdfGroupURI)) {
return rdfGroupCache.get(srdfGroupURI);
}
RemoteDirectorGroup rdfGroup=this.getDbClient().queryObject(RemoteDirectorGroup.class,srdfGroupURI);
if (null != rdfGroup && !rdfGroup.getInactive()) {
rdfGroupCache.put(srdfGroupURI,rdfGroup);
}
return rdfGroup;
}
| Return the RemoteDirectorGroup from cache otherwise query from db. |
public static int minCut(String s){
Set<String> palin=new HashSet<String>();
return minCut(s,0,palin);
}
| Backtracking, generate all cuts |
public ObjectWriter withDateFormat(DateFormat df){
SerializationConfig newConfig=_config.withDateFormat(df);
if (newConfig == _config) {
return this;
}
return new ObjectWriter(this,newConfig);
}
| Fluent factory method that will construct a new writer instance that will use specified date format for serializing dates; or if null passed, one that will serialize dates as numeric timestamps. |
LockMode(final boolean allowsTouch,final boolean allowsCommands){
this.allowsTouch=allowsTouch;
this.allowsCommands=allowsCommands;
}
| Constructs a new LockMode instance. |
public boolean match(Element e,String pseudoE){
return (e instanceof CSSStylableElement) ? ((CSSStylableElement)e).isPseudoInstanceOf(getValue()) : false;
}
| Tests whether this selector matches the given element. |
RandomAccessFile openInputFileAsZip(String fileName) throws IOException {
ZipFile zipFile;
try {
zipFile=new ZipFile(fileName);
}
catch ( FileNotFoundException fnfe) {
System.err.println("Unable to open '" + fileName + "': "+ fnfe.getMessage());
throw fnfe;
}
catch ( ZipException ze) {
return null;
}
ZipEntry entry=zipFile.getEntry(CLASSES_DEX);
if (entry == null) {
System.err.println("Unable to find '" + CLASSES_DEX + "' in '"+ fileName+ "'");
zipFile.close();
throw new ZipException();
}
InputStream zis=zipFile.getInputStream(entry);
File tempFile=File.createTempFile("dexdeps",".dex");
RandomAccessFile raf=new RandomAccessFile(tempFile,"rw");
tempFile.delete();
byte copyBuf[]=new byte[32768];
int actual;
while (true) {
actual=zis.read(copyBuf);
if (actual == -1) break;
raf.write(copyBuf,0,actual);
}
zis.close();
raf.seek(0);
return raf;
}
| Tries to open an input file as a Zip archive (jar/apk) with a "classes.dex" inside. |
public boolean generate(Projection proj){
setNeedToRegenerate(true);
if (proj == null) {
Debug.message("omgraphic","OMRect: null projection in generate!");
return false;
}
switch (renderType) {
case RENDERTYPE_XY:
setShape(createBoxShape((int)Math.min(x2,x1),(int)Math.min(y2,y1),(int)Math.abs(x2 - x1),(int)Math.abs(y2 - y1)));
break;
case RENDERTYPE_OFFSET:
if (!proj.isPlotable(lat1,lon1)) {
setNeedToRegenerate(true);
return false;
}
Point p1=(Point)proj.forward(lat1,lon1,new Point());
setShape(createBoxShape((int)Math.min(p1.x + x1,p1.x + x2),(int)Math.min(p1.y + y1,p1.y + y2),(int)Math.abs(x2 - x1),(int)Math.abs(y2 - y1)));
break;
case RENDERTYPE_LATLON:
ArrayList<float[]> rects;
if (proj instanceof GeoProj) {
rects=((GeoProj)proj).forwardRect(new LatLonPoint.Double(lat1,lon1),new LatLonPoint.Double(lat2,lon2),lineType,nsegs,!isClear(fillPaint));
}
else {
rects=proj.forwardRect(new Point2D.Double(lon1,lat1),new Point2D.Double(lon2,lat2));
}
int size=rects.size();
GeneralPath projectedShape=null;
for (int i=0; i < size; i+=2) {
GeneralPath gp=createShape(rects.get(i),rects.get(i + 1),true);
projectedShape=appendShapeEdge(projectedShape,gp,false);
}
setShape(projectedShape);
break;
case RENDERTYPE_UNKNOWN:
System.err.println("OMRect.generate(): invalid RenderType");
return false;
}
setLabelLocation(getShape(),proj);
setNeedToRegenerate(false);
return true;
}
| Prepare the rectangle for rendering. |
public void stream(OutputStream os) throws IOException {
MessageHeader globals=entries.elementAt(0);
if (globals.findValue("Signature-Version") == null) {
throw new JarException("Signature file requires " + "Signature-Version: 1.0 in 1st header");
}
PrintStream ps=new PrintStream(os);
globals.print(ps);
for (int i=1; i < entries.size(); ++i) {
MessageHeader mh=entries.elementAt(i);
mh.print(ps);
}
}
| Add a signature file at current position in a stream |
public long readDateTimeAsLong(int index){
return this.readULong(index) << 32 | this.readULong(index + 4);
}
| Reads the LONGDATETIME at the given index. |
public static Value BagToSet(Value b){
FcnRcdValue fcn=FcnRcdValue.convert(b);
if (fcn == null) {
throw new EvalException(EC.TLC_MODULE_APPLYING_TO_WRONG_VALUE,new String[]{"BagToSet","a function with a finite domain",Value.ppr(b.toString())});
}
return fcn.getDomain();
}
| // For now, we do not override SubBag. So, We are using the TLA+ definition. public static Value SubBag(Value b) { FcnRcdValue fcn = FcnRcdValue.convert(b); if (fcn == null) { String msg = "Applying SubBag to the following value, which is\n" + "not a function with a finite domain:\n" + Value.ppr(b.toString()); throw new EvalException(msg); } throw new EvalException("SubBag is not implemented."); } |
public static ProjectActionEvent createProjectClosingEvent(ProjectDescriptor project){
return new ProjectActionEvent(project,ProjectAction.CLOSING,false);
}
| Creates a Project Closing Event. |
public int fullyConnectSync(Context srcContext,Handler srcHandler,Handler dstHandler){
int status=connectSync(srcContext,srcHandler,dstHandler);
if (status == STATUS_SUCCESSFUL) {
Message response=sendMessageSynchronously(CMD_CHANNEL_FULL_CONNECTION);
status=response.arg1;
}
return status;
}
| Fully connect two local Handlers synchronously. |
public static boolean hasInterface(String intf,String cls){
try {
return hasInterface(Class.forName(intf),Class.forName(cls));
}
catch ( Exception e) {
return false;
}
}
| Checks whether the given class implements the given interface. |
public void removePropertyChangeListener(String propertyName,PropertyChangeListener in_pcl){
beanContextChildSupport.removePropertyChangeListener(propertyName,in_pcl);
}
| Method for BeanContextChild interface. Uses the BeanContextChildSupport to remove a listener to this object's property. You don't need this function for objects that extend java.awt.Component. |
private boolean isIgnoreLocallyExistingFiles(){
return ignoreLocallyExistingFiles;
}
| Returns true to indicate that locally existing files are treated as they would not exist. This is a extension to the standard cvs-behaviour! |
private boolean isViewDescendantOf(View child,View parent){
if (child == parent) {
return true;
}
final ViewParent theParent=child.getParent();
return (theParent instanceof ViewGroup) && isViewDescendantOf((View)theParent,parent);
}
| Return true if child is an descendant of parent, (or equal to the parent). |
public void add(double value){
if (count == 0) {
count=1;
mean=value;
min=value;
max=value;
if (!isFinite(value)) {
sumOfSquaresOfDeltas=NaN;
}
}
else {
count++;
if (isFinite(value) && isFinite(mean)) {
double delta=value - mean;
mean+=delta / count;
sumOfSquaresOfDeltas+=delta * (value - mean);
}
else {
mean=calculateNewMeanNonFinite(mean,value);
sumOfSquaresOfDeltas=NaN;
}
min=Math.min(min,value);
max=Math.max(max,value);
}
}
| Adds the given value to the dataset. |
private void init(Context context,RuqusTheme theme,String currClassName){
this.currClassName=currClassName;
inflate(context,R.layout.sort_field_view,this);
setOrientation(VERTICAL);
label=(TextView)findViewById(R.id.sort_field_label);
sortFieldChooser=(Spinner)findViewById(R.id.sort_field);
removeButton=(ImageButton)findViewById(R.id.remove_field);
sortDirRg=(RadioGroup)findViewById(R.id.rg_sort_dir);
ascRb=(RadioButton)findViewById(R.id.asc);
descRb=(RadioButton)findViewById(R.id.desc);
setTheme(theme);
sortFieldChooser.setOnTouchListener(sortFieldChooserListener);
sortFieldChooser.setOnItemSelectedListener(sortFieldChooserListener);
}
| Initialize our view. |
protected Future<Void> closeNoThrow(){
Promise<Void> closeFuture;
synchronized (this) {
if (null != closePromise) {
return closePromise;
}
closeFuture=closePromise=new Promise<Void>();
}
cancelTruncation();
Utils.closeSequence(bkDistributedLogManager.getScheduler(),true,getCachedLogWriter(),getAllocatedLogWriter(),getCachedWriteHandler()).proxyTo(closeFuture);
return closeFuture;
}
| Close the writer and release all the underlying resources |
public Boolean isValidating(){
return validating;
}
| Gets the value of the validating property. |
private String scanPlainSpaces(){
int length=0;
while (reader.peek(length) == ' ' || reader.peek(length) == '\t') {
length++;
}
String whitespaces=reader.prefixForward(length);
String lineBreak=scanLineBreak();
if (lineBreak.length() != 0) {
this.allowSimpleKey=true;
String prefix=reader.prefix(3);
if ("---".equals(prefix) || "...".equals(prefix) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) {
return "";
}
StringBuilder breaks=new StringBuilder();
while (true) {
if (reader.peek() == ' ') {
reader.forward();
}
else {
String lb=scanLineBreak();
if (lb.length() != 0) {
breaks.append(lb);
prefix=reader.prefix(3);
if ("---".equals(prefix) || "...".equals(prefix) && Constant.NULL_BL_T_LINEBR.has(reader.peek(3))) {
return "";
}
}
else {
break;
}
}
}
if (!"\n".equals(lineBreak)) {
return lineBreak + breaks;
}
else if (breaks.length() == 0) {
return " ";
}
return breaks.toString();
}
return whitespaces;
}
| See the specification for details. SnakeYAML and libyaml allow tabs inside plain scalar |
public static void w(String tag,String s,Throwable e){
if (LOG.WARN >= LOGLEVEL) Log.w(tag,s,e);
}
| Warning log message. |
public static double mean(double[] vector){
double sum=0;
if (vector.length == 0) {
return 0;
}
for (int i=0; i < vector.length; i++) {
sum+=vector[i];
}
return sum / (double)vector.length;
}
| Computes the mean for an array of doubles. |
protected byte[] toJsonBytes(final Object object) throws Exception {
ObjectMapper mapper=new ObjectMapper();
mapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
return mapper.writeValueAsBytes(object);
}
| Map object to JSON bytes |
public void shuffleInventory(@Nonnull IInventory inv,@Nonnull Random random){
final List<ItemStack> list=getInventoryList(inv);
Collections.shuffle(list,random);
for (int i=0; i < inv.getSizeInventory(); ++i) {
inv.setInventorySlotContents(i,list.get(i));
}
}
| Shuffles all items in the inventory |
public QueueCursor(int capacity){
this(capacity,false);
}
| Creates an <tt>QueueCursor</tt> with the given (fixed) capacity and default access policy. |
public void destroy(DistributedRegion r){
}
| Blows away all the data in this object. |
public Process executeAsync(final CommandLine command,ExecuteResultHandler handler) throws IOException {
return executeAsync(command,null,handler);
}
| Methods for starting asynchronous execution. The child process inherits all environment variables of the parent process. Result provided to callback handler. |
public static void destroy(){
try {
Region region1=cache.getRegion(Region.SEPARATOR + REGION_NAME);
region1.localDestroy("key-1");
}
catch ( Exception e) {
e.printStackTrace();
fail("test failed due to exception in destroy ");
}
}
| destroy key-1 |
public boolean isSelected(){
return this.selected;
}
| Check if item is selected |
public String(String string){
value=string.value;
offset=string.offset;
count=string.count;
}
| Creates a string that is a copy of another string |
private void needNewBuffer(int newSize){
int delta=newSize - size;
int newBufferSize=Math.max(minChunkLen,delta);
currentBufferIndex++;
currentBuffer=new int[newBufferSize];
offset=0;
if (currentBufferIndex >= buffers.length) {
int newLen=buffers.length << 1;
int[][] newBuffers=new int[newLen][];
System.arraycopy(buffers,0,newBuffers,0,buffers.length);
buffers=newBuffers;
}
buffers[currentBufferIndex]=currentBuffer;
buffersCount++;
}
| Prepares next chunk to match new size. The minimal length of new chunk is <code>minChunkLen</code>. |
public void patch_splitMax(LinkedList<Patch> patches){
short patch_size=Match_MaxBits;
String precontext, postcontext;
Patch patch;
int start1, start2;
boolean empty;
Operation diff_type;
String diff_text;
ListIterator<Patch> pointer=patches.listIterator();
Patch bigpatch=pointer.hasNext() ? pointer.next() : null;
while (bigpatch != null) {
if (bigpatch.length1 <= Match_MaxBits) {
bigpatch=pointer.hasNext() ? pointer.next() : null;
continue;
}
pointer.remove();
start1=bigpatch.start1;
start2=bigpatch.start2;
precontext="";
while (!bigpatch.diffs.isEmpty()) {
patch=new Patch();
empty=true;
patch.start1=start1 - precontext.length();
patch.start2=start2 - precontext.length();
if (precontext.length() != 0) {
patch.length1=patch.length2=precontext.length();
patch.diffs.add(new Diff(Operation.EQUAL,precontext));
}
while (!bigpatch.diffs.isEmpty() && patch.length1 < patch_size - Patch_Margin) {
diff_type=bigpatch.diffs.getFirst().operation;
diff_text=bigpatch.diffs.getFirst().text;
if (diff_type == Operation.INSERT) {
patch.length2+=diff_text.length();
start2+=diff_text.length();
patch.diffs.addLast(bigpatch.diffs.removeFirst());
empty=false;
}
else if (diff_type == Operation.DELETE && patch.diffs.size() == 1 && patch.diffs.getFirst().operation == Operation.EQUAL && diff_text.length() > 2 * patch_size) {
patch.length1+=diff_text.length();
start1+=diff_text.length();
empty=false;
patch.diffs.add(new Diff(diff_type,diff_text));
bigpatch.diffs.removeFirst();
}
else {
diff_text=diff_text.substring(0,Math.min(diff_text.length(),patch_size - patch.length1 - Patch_Margin));
patch.length1+=diff_text.length();
start1+=diff_text.length();
if (diff_type == Operation.EQUAL) {
patch.length2+=diff_text.length();
start2+=diff_text.length();
}
else {
empty=false;
}
patch.diffs.add(new Diff(diff_type,diff_text));
if (diff_text.equals(bigpatch.diffs.getFirst().text)) {
bigpatch.diffs.removeFirst();
}
else {
bigpatch.diffs.getFirst().text=bigpatch.diffs.getFirst().text.substring(diff_text.length());
}
}
}
precontext=diff_text2(patch.diffs);
precontext=precontext.substring(Math.max(0,precontext.length() - Patch_Margin));
if (diff_text1(bigpatch.diffs).length() > Patch_Margin) {
postcontext=diff_text1(bigpatch.diffs).substring(0,Patch_Margin);
}
else {
postcontext=diff_text1(bigpatch.diffs);
}
if (postcontext.length() != 0) {
patch.length1+=postcontext.length();
patch.length2+=postcontext.length();
if (!patch.diffs.isEmpty() && patch.diffs.getLast().operation == Operation.EQUAL) {
patch.diffs.getLast().text+=postcontext;
}
else {
patch.diffs.add(new Diff(Operation.EQUAL,postcontext));
}
}
if (!empty) {
pointer.add(patch);
}
}
bigpatch=pointer.hasNext() ? pointer.next() : null;
}
}
| Look through the patches and break up any which are longer than the maximum limit of the match algorithm. Intended to be called only from within patch_apply. |
public static TestResult execJavac(String toCompile,File dir,String jflexTestVersion){
Project p=new Project();
Javac javac=new Javac();
Path path=new Path(p,dir.toString());
javac.setProject(p);
javac.setSrcdir(path);
javac.setDestdir(dir);
javac.setTarget(javaVersion);
javac.setSource(javaVersion);
javac.setSourcepath(new Path(p,""));
javac.setIncludes(toCompile);
Path classPath=javac.createClasspath();
classPath.setPath(System.getProperty("user.home") + "/.m2/repository/de/jflex/jflex/" + jflexTestVersion+ "/jflex-"+ jflexTestVersion+ ".jar");
ByteArrayOutputStream out=new ByteArrayOutputStream();
PrintStream outSafe=System.err;
System.setErr(new PrintStream(out));
try {
javac.execute();
return new TestResult(out.toString(),true);
}
catch ( BuildException e) {
return new TestResult(e + System.getProperty("line.separator") + out.toString(),false);
}
finally {
System.setErr(outSafe);
}
}
| Call javac on toCompile in input dir. If toCompile is null, all *.java files below dir will be compiled. |
private void cloneProperties(BurpCertificate certificate,BurpCertificateBuilder burpCertificateBuilder){
burpCertificateBuilder.setVersion(certificate.getVersionNumber());
burpCertificateBuilder.setSerial(certificate.getSerialNumberBigInteger());
if (certificate.getPublicKeyAlgorithm().equals("RSA")) {
burpCertificateBuilder.setSignatureAlgorithm(certificate.getSignatureAlgorithm());
}
else {
burpCertificateBuilder.setSignatureAlgorithm("SHA256withRSA");
}
burpCertificateBuilder.setIssuer(certificate.getIssuer());
burpCertificateBuilder.setNotAfter(certificate.getNotAfter());
burpCertificateBuilder.setNotBefore(certificate.getNotBefore());
burpCertificateBuilder.setKeySize(certificate.getKeySize());
for ( BurpCertificateExtension extension : certificate.getAllExtensions()) {
burpCertificateBuilder.addExtension(extension);
}
}
| Copy all X.509v3 general information and all extensions 1:1 from one source certificat to one destination certificate. |
protected void emit_PropertyMethodDeclaration_SemicolonKeyword_1_q(EObject semanticObject,ISynNavigable transition,List<INode> nodes){
acceptNodes(transition,nodes);
}
| Ambiguous syntax: ';'? This ambiguous syntax occurs at: body=Block (ambiguity) (rule end) declaredName=LiteralOrComputedPropertyName '(' ')' (ambiguity) (rule end) fpars+=FormalParameter ')' (ambiguity) (rule end) |
public void runTest() throws Throwable {
Document doc;
Element rootNode;
Node newChild;
NodeList elementList;
Node oldChild;
Node replacedChild;
doc=(Document)load("hc_staff",true);
newChild=doc.createAttribute("lang");
elementList=doc.getElementsByTagName("p");
oldChild=elementList.item(1);
rootNode=(Element)oldChild.getParentNode();
{
boolean success=false;
try {
replacedChild=rootNode.replaceChild(newChild,oldChild);
}
catch ( DOMException ex) {
success=(ex.code == DOMException.HIERARCHY_REQUEST_ERR);
}
assertTrue("throw_HIERARCHY_REQUEST_ERR",success);
}
}
| Runs the test case. |
public void preComputeBestReplicaMapping(){
Map<String,Map<String,Map<String,String>>> collectionToShardToCoreMapping=getZkClusterData().getCollectionToShardToCoreMapping();
for ( String collection : collectionNames) {
Map<String,Map<String,String>> shardToCoreMapping=collectionToShardToCoreMapping.get(collection);
for ( String shard : shardToCoreMapping.keySet()) {
Map<String,String> coreToNodeMap=shardToCoreMapping.get(shard);
for ( String core : coreToNodeMap.keySet()) {
String currentCore=core;
String node=coreToNodeMap.get(core);
SolrCore currentReplica=new SolrCore(node,currentCore);
try {
currentReplica.loadStatus();
fillUpAllCoresForShard(currentReplica,coreToNodeMap);
break;
}
catch ( Exception e) {
logger.info(ExceptionUtils.getFullStackTrace(e));
continue;
}
}
shardToBestReplicaMapping.put(shard,coreToBestReplicaMappingByHealth);
}
}
}
| For all the collections in zookeeper, compute the best replica for every shard for every collection. Doing this computation at bootup significantly reduces the computation done during streaming. |
private void statInit(){
lDocumentNo.setLabelFor(fDocumentNo);
fDocumentNo.setBackground(AdempierePLAF.getInfoBackground());
fDocumentNo.addActionListener(this);
lDescription.setLabelFor(fDescription);
fDescription.setBackground(AdempierePLAF.getInfoBackground());
fDescription.addActionListener(this);
lPOReference.setLabelFor(fPOReference);
fPOReference.setBackground(AdempierePLAF.getInfoBackground());
fPOReference.addActionListener(this);
fIsSOTrx.setSelected(!"N".equals(Env.getContext(Env.getCtx(),p_WindowNo,"IsSOTrx")));
fIsSOTrx.addActionListener(this);
fBPartner_ID=new VLookup("C_BPartner_ID",false,false,true,MLookupFactory.get(Env.getCtx(),p_WindowNo,0,MColumn.getColumn_ID(MInOut.Table_Name,MInOut.COLUMNNAME_C_BPartner_ID),DisplayType.Search));
lBPartner_ID.setLabelFor(fBPartner_ID);
fBPartner_ID.setBackground(AdempierePLAF.getInfoBackground());
fBPartner_ID.addActionListener(this);
fShipper_ID=new VLookup("M_Shipper_ID",false,false,true,MLookupFactory.get(Env.getCtx(),p_WindowNo,0,MColumn.getColumn_ID(MInOut.Table_Name,MInOut.COLUMNNAME_M_Shipper_ID),DisplayType.TableDir));
lShipper_ID.setLabelFor(fShipper_ID);
fShipper_ID.setBackground(AdempierePLAF.getInfoBackground());
fShipper_ID.addActionListener(this);
lDateFrom.setLabelFor(fDateFrom);
fDateFrom.setBackground(AdempierePLAF.getInfoBackground());
fDateFrom.setToolTipText(Msg.translate(Env.getCtx(),"DateFrom"));
fDateFrom.addActionListener(this);
lDateTo.setLabelFor(fDateTo);
fDateTo.setBackground(AdempierePLAF.getInfoBackground());
fDateTo.setToolTipText(Msg.translate(Env.getCtx(),"DateTo"));
fDateTo.addActionListener(this);
CPanel datePanel=new CPanel();
datePanel.setLayout(new ALayout(0,0,true));
datePanel.add(fDateFrom,new ALayoutConstraint(0,0));
datePanel.add(lDateTo,null);
datePanel.add(fDateTo,null);
p_criteriaGrid.add(lDocumentNo,new ALayoutConstraint(0,0));
p_criteriaGrid.add(fDocumentNo,null);
p_criteriaGrid.add(lBPartner_ID,null);
p_criteriaGrid.add(fBPartner_ID,null);
p_criteriaGrid.add(fIsSOTrx,new ALayoutConstraint(0,5));
p_criteriaGrid.add(lDescription,new ALayoutConstraint(1,0));
p_criteriaGrid.add(fDescription,null);
p_criteriaGrid.add(lDateFrom,null);
p_criteriaGrid.add(datePanel,null);
p_criteriaGrid.add(lPOReference,new ALayoutConstraint(2,0));
p_criteriaGrid.add(fPOReference,null);
p_criteriaGrid.add(lShipper_ID,null);
p_criteriaGrid.add(fShipper_ID,null);
}
| Static Setup - add fields to parameterPanel |
@Override public boolean check(final CertificateToken certificateToken){
final boolean keyUsage=certificateToken.checkKeyUsage(bit);
return keyUsage == value;
}
| Checks the condition for the given certificate. |
public static boolean isValidFolderPath(Path path){
if (path == null) {
return false;
}
File f=path.toFile();
return path.toString().isEmpty() || (f.isDirectory() && f.canWrite());
}
| Checks is the parameter path a valid for saving fixed file |
public float[][] extract(int maxFeatureValue,int[] distanceSet,int[][] img){
int[] histogram=new int[maxFeatureValue];
final int W=img.length;
final int H=img[0].length;
for (int x=0; x < W; x++) {
for (int y=0; y < H; y++) {
histogram[img[x][y]]++;
}
}
float[][] correlogram=new float[maxFeatureValue][distanceSet.length];
int[] tmpCorrelogram=new int[distanceSet.length];
for (int x=0; x < W; x++) {
for (int y=0; y < H; y++) {
int color=img[x][y];
getNumPixelsInNeighbourhood(x,y,img,tmpCorrelogram,maxFeatureValue,distanceSet);
for (int i=0; i < distanceSet.length; i++) {
correlogram[color][i]+=tmpCorrelogram[i];
}
}
}
float[] max=new float[distanceSet.length];
for (int c=0; c < maxFeatureValue; c++) {
for (int i=0; i < distanceSet.length; i++) {
max[i]=Math.max(correlogram[c][i],max[i]);
}
}
for (int c=0; c < maxFeatureValue; c++) {
for (int i=0; i < distanceSet.length; i++) {
correlogram[c][i]=correlogram[c][i] / max[i];
}
}
return correlogram;
}
| extract extracts an auto-correlogram from an Image. This method create a cummulated auto-correlogram over different distances instead of standard method. Also, uses a different normalization method |
public static CC parseComponentConstraint(String s){
CC cc=new CC();
if (s.length() == 0) {
return cc;
}
String[] parts=toTrimmedTokens(s,',');
for ( String part : parts) {
try {
if (part.length() == 0) {
continue;
}
int ix=-1;
char c=part.charAt(0);
if (c == 'n') {
if (part.equals("north")) {
cc.setDockSide(0);
continue;
}
if (part.equals("newline")) {
cc.setNewline(true);
continue;
}
if (part.startsWith("newline ")) {
String gapSz=part.substring(7).trim();
cc.setNewlineGapSize(parseBoundSize(gapSz,true,true));
continue;
}
}
if (c == 'f' && (part.equals("flowy") || part.equals("flowx"))) {
cc.setFlowX(part.charAt(4) == 'x' ? Boolean.TRUE : Boolean.FALSE);
continue;
}
if (c == 's') {
ix=startsWithLenient(part,"skip",4,true);
if (ix > -1) {
String num=part.substring(ix).trim();
cc.setSkip(num.length() != 0 ? Integer.parseInt(num) : 1);
continue;
}
ix=startsWithLenient(part,"split",5,true);
if (ix > -1) {
String split=part.substring(ix).trim();
cc.setSplit(split.length() > 0 ? Integer.parseInt(split) : LayoutUtil.INF);
continue;
}
if (part.equals("south")) {
cc.setDockSide(2);
continue;
}
ix=startsWithLenient(part,new String[]{"spany","sy"},new int[]{5,2},true);
if (ix > -1) {
cc.setSpanY(parseSpan(part.substring(ix).trim()));
continue;
}
ix=startsWithLenient(part,new String[]{"spanx","sx"},new int[]{5,2},true);
if (ix > -1) {
cc.setSpanX(parseSpan(part.substring(ix).trim()));
continue;
}
ix=startsWithLenient(part,"span",4,true);
if (ix > -1) {
String[] spans=toTrimmedTokens(part.substring(ix).trim(),' ');
cc.setSpanX(spans[0].length() > 0 ? Integer.parseInt(spans[0]) : LayoutUtil.INF);
cc.setSpanY(spans.length > 1 ? Integer.parseInt(spans[1]) : 1);
continue;
}
ix=startsWithLenient(part,"shrinkx",7,true);
if (ix > -1) {
cc.getHorizontal().setShrink(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
continue;
}
ix=startsWithLenient(part,"shrinky",7,true);
if (ix > -1) {
cc.getVertical().setShrink(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
continue;
}
ix=startsWithLenient(part,"shrink",6,false);
if (ix > -1) {
String[] shrinks=toTrimmedTokens(part.substring(ix).trim(),' ');
cc.getHorizontal().setShrink(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
if (shrinks.length > 1) {
cc.getVertical().setShrink(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
}
continue;
}
ix=startsWithLenient(part,new String[]{"shrinkprio","shp"},new int[]{10,3},true);
if (ix > -1) {
String sp=part.substring(ix).trim();
if (sp.startsWith("x") || sp.startsWith("y")) {
(sp.startsWith("x") ? cc.getHorizontal() : cc.getVertical()).setShrinkPriority(Integer.parseInt(sp.substring(2)));
}
else {
String[] shrinks=toTrimmedTokens(sp,' ');
cc.getHorizontal().setShrinkPriority(Integer.parseInt(shrinks[0]));
if (shrinks.length > 1) {
cc.getVertical().setShrinkPriority(Integer.parseInt(shrinks[1]));
}
}
continue;
}
ix=startsWithLenient(part,new String[]{"sizegroupx","sizegroupy","sgx","sgy"},new int[]{9,9,2,2},true);
if (ix > -1) {
String sg=part.substring(ix).trim();
char lc=part.charAt(ix - 1);
if (lc != 'y') {
cc.getHorizontal().setSizeGroup(sg);
}
if (lc != 'x') {
cc.getVertical().setSizeGroup(sg);
}
continue;
}
}
if (c == 'g') {
ix=startsWithLenient(part,"growx",5,true);
if (ix > -1) {
cc.getHorizontal().setGrow(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
continue;
}
ix=startsWithLenient(part,"growy",5,true);
if (ix > -1) {
cc.getVertical().setGrow(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
continue;
}
ix=startsWithLenient(part,"grow",4,false);
if (ix > -1) {
String[] grows=toTrimmedTokens(part.substring(ix).trim(),' ');
cc.getHorizontal().setGrow(parseFloat(grows[0],ResizeConstraint.WEIGHT_100));
cc.getVertical().setGrow(parseFloat(grows.length > 1 ? grows[1] : "",ResizeConstraint.WEIGHT_100));
continue;
}
ix=startsWithLenient(part,new String[]{"growprio","gp"},new int[]{8,2},true);
if (ix > -1) {
String gp=part.substring(ix).trim();
char c0=gp.length() > 0 ? gp.charAt(0) : ' ';
if (c0 == 'x' || c0 == 'y') {
(c0 == 'x' ? cc.getHorizontal() : cc.getVertical()).setGrowPriority(Integer.parseInt(gp.substring(2)));
}
else {
String[] grows=toTrimmedTokens(gp,' ');
cc.getHorizontal().setGrowPriority(Integer.parseInt(grows[0]));
if (grows.length > 1) {
cc.getVertical().setGrowPriority(Integer.parseInt(grows[1]));
}
}
continue;
}
if (part.startsWith("gap")) {
BoundSize[] gaps=parseGaps(part);
if (gaps[0] != null) {
cc.getVertical().setGapBefore(gaps[0]);
}
if (gaps[1] != null) {
cc.getHorizontal().setGapBefore(gaps[1]);
}
if (gaps[2] != null) {
cc.getVertical().setGapAfter(gaps[2]);
}
if (gaps[3] != null) {
cc.getHorizontal().setGapAfter(gaps[3]);
}
continue;
}
}
if (c == 'a') {
ix=startsWithLenient(part,new String[]{"aligny","ay"},new int[]{6,2},true);
if (ix > -1) {
cc.getVertical().setAlign(parseUnitValueOrAlign(part.substring(ix).trim(),false,null));
continue;
}
ix=startsWithLenient(part,new String[]{"alignx","ax"},new int[]{6,2},true);
if (ix > -1) {
cc.getHorizontal().setAlign(parseUnitValueOrAlign(part.substring(ix).trim(),true,null));
continue;
}
ix=startsWithLenient(part,"align",2,true);
if (ix > -1) {
String[] gaps=toTrimmedTokens(part.substring(ix).trim(),' ');
cc.getHorizontal().setAlign(parseUnitValueOrAlign(gaps[0],true,null));
if (gaps.length > 1) {
cc.getVertical().setAlign(parseUnitValueOrAlign(gaps[1],false,null));
}
continue;
}
}
if ((c == 'x' || c == 'y') && part.length() > 2) {
char c2=part.charAt(1);
if (c2 == ' ' || (c2 == '2' && part.charAt(2) == ' ')) {
if (cc.getPos() == null) {
cc.setPos(new UnitValue[4]);
}
else if (cc.isBoundsInGrid() == false) {
throw new IllegalArgumentException("Cannot combine 'position' with 'x/y/x2/y2' keywords.");
}
int edge=(c == 'x' ? 0 : 1) + (c2 == '2' ? 2 : 0);
UnitValue[] pos=cc.getPos();
pos[edge]=parseUnitValue(part.substring(2).trim(),null,c == 'x');
cc.setPos(pos);
cc.setBoundsInGrid(true);
continue;
}
}
if (c == 'c') {
ix=startsWithLenient(part,"cell",4,true);
if (ix > -1) {
String[] grs=toTrimmedTokens(part.substring(ix).trim(),' ');
if (grs.length < 2) {
throw new IllegalArgumentException("At least two integers must follow " + part);
}
cc.setCellX(Integer.parseInt(grs[0]));
cc.setCellY(Integer.parseInt(grs[1]));
if (grs.length > 2) {
cc.setSpanX(Integer.parseInt(grs[2]));
}
if (grs.length > 3) {
cc.setSpanY(Integer.parseInt(grs[3]));
}
continue;
}
}
if (c == 'p') {
ix=startsWithLenient(part,"pos",3,true);
if (ix > -1) {
if (cc.getPos() != null && cc.isBoundsInGrid()) {
throw new IllegalArgumentException("Can not combine 'pos' with 'x/y/x2/y2' keywords.");
}
String[] pos=toTrimmedTokens(part.substring(ix).trim(),' ');
UnitValue[] bounds=new UnitValue[4];
for (int j=0; j < pos.length; j++) {
bounds[j]=parseUnitValue(pos[j],null,j % 2 == 0);
}
if (bounds[0] == null && bounds[2] == null || bounds[1] == null && bounds[3] == null) {
throw new IllegalArgumentException("Both x and x2 or y and y2 can not be null!");
}
cc.setPos(bounds);
cc.setBoundsInGrid(false);
continue;
}
ix=startsWithLenient(part,"pad",3,true);
if (ix > -1) {
UnitValue[] p=parseInsets(part.substring(ix).trim(),false);
cc.setPadding(new UnitValue[]{p[0],p.length > 1 ? p[1] : null,p.length > 2 ? p[2] : null,p.length > 3 ? p[3] : null});
continue;
}
ix=startsWithLenient(part,"pushx",5,true);
if (ix > -1) {
cc.setPushX(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
continue;
}
ix=startsWithLenient(part,"pushy",5,true);
if (ix > -1) {
cc.setPushY(parseFloat(part.substring(ix).trim(),ResizeConstraint.WEIGHT_100));
continue;
}
ix=startsWithLenient(part,"push",4,false);
if (ix > -1) {
String[] pushs=toTrimmedTokens(part.substring(ix).trim(),' ');
cc.setPushX(parseFloat(pushs[0],ResizeConstraint.WEIGHT_100));
cc.setPushY(parseFloat(pushs.length > 1 ? pushs[1] : "",ResizeConstraint.WEIGHT_100));
continue;
}
}
if (c == 't') {
ix=startsWithLenient(part,"tag",3,true);
if (ix > -1) {
cc.setTag(part.substring(ix).trim());
continue;
}
}
if (c == 'w' || c == 'h') {
if (part.equals("wrap")) {
cc.setWrap(true);
continue;
}
if (part.startsWith("wrap ")) {
String gapSz=part.substring(5).trim();
cc.setWrapGapSize(parseBoundSize(gapSz,true,true));
continue;
}
boolean isHor=c == 'w';
if (isHor && (part.startsWith("w ") || part.startsWith("width "))) {
String uvStr=part.substring(part.charAt(1) == ' ' ? 2 : 6).trim();
cc.getHorizontal().setSize(parseBoundSize(uvStr,false,true));
continue;
}
if (!isHor && (part.startsWith("h ") || part.startsWith("height "))) {
String uvStr=part.substring(part.charAt(1) == ' ' ? 2 : 7).trim();
cc.getVertical().setSize(parseBoundSize(uvStr,false,false));
continue;
}
if (part.startsWith("wmin ") || part.startsWith("wmax ") || part.startsWith("hmin ")|| part.startsWith("hmax ")) {
String uvStr=part.substring(5).trim();
if (uvStr.length() > 0) {
UnitValue uv=parseUnitValue(uvStr,null,isHor);
boolean isMin=part.charAt(3) == 'n';
DimConstraint dc=isHor ? cc.getHorizontal() : cc.getVertical();
dc.setSize(new BoundSize(isMin ? uv : dc.getSize().getMin(),dc.getSize().getPreferred(),isMin ? (dc.getSize().getMax()) : uv,uvStr));
continue;
}
}
if (part.equals("west")) {
cc.setDockSide(1);
continue;
}
if (part.startsWith("hidemode ")) {
cc.setHideMode(Integer.parseInt(part.substring(9)));
continue;
}
}
if (c == 'i' && part.startsWith("id ")) {
cc.setId(part.substring(3).trim());
int dIx=cc.getId().indexOf('.');
if (dIx == 0 || dIx == cc.getId().length() - 1) {
throw new IllegalArgumentException("Dot must not be first or last!");
}
continue;
}
if (c == 'e') {
if (part.equals("east")) {
cc.setDockSide(3);
continue;
}
if (part.equals("external")) {
cc.setExternal(true);
continue;
}
ix=startsWithLenient(part,new String[]{"endgroupx","endgroupy","egx","egy"},new int[]{-1,-1,-1,-1},true);
if (ix > -1) {
String sg=part.substring(ix).trim();
char lc=part.charAt(ix - 1);
DimConstraint dc=(lc == 'x' ? cc.getHorizontal() : cc.getVertical());
dc.setEndGroup(sg);
continue;
}
}
if (c == 'd') {
if (part.equals("dock north")) {
cc.setDockSide(0);
continue;
}
if (part.equals("dock west")) {
cc.setDockSide(1);
continue;
}
if (part.equals("dock south")) {
cc.setDockSide(2);
continue;
}
if (part.equals("dock east")) {
cc.setDockSide(3);
continue;
}
if (part.equals("dock center")) {
cc.getHorizontal().setGrow(new Float(100f));
cc.getVertical().setGrow(new Float(100f));
cc.setPushX(new Float(100f));
cc.setPushY(new Float(100f));
continue;
}
}
if (c == 'v') {
ix=startsWithLenient(part,new String[]{"visualpadding","vp"},new int[]{3,2},true);
if (ix > -1) {
UnitValue[] p=parseInsets(part.substring(ix).trim(),false);
cc.setVisualPadding(new UnitValue[]{p[0],p.length > 1 ? p[1] : null,p.length > 2 ? p[2] : null,p.length > 3 ? p[3] : null});
continue;
}
}
UnitValue horAlign=parseAlignKeywords(part,true);
if (horAlign != null) {
cc.getHorizontal().setAlign(horAlign);
continue;
}
UnitValue verAlign=parseAlignKeywords(part,false);
if (verAlign != null) {
cc.getVertical().setAlign(verAlign);
continue;
}
throw new IllegalArgumentException("Unknown keyword.");
}
catch ( Exception ex) {
ex.printStackTrace();
throw new IllegalArgumentException("Error parsing Constraint: '" + part + "'");
}
}
return cc;
}
| Parses one component constraint and returns the parsed value. |
SegmentTreeNode<?> computeRightChild(SegmentTreeNode<?> node){
if (node.right - node.left > 1) {
return constructor.construct((node.left + node.right) / 2,node.right);
}
return null;
}
| Compute the right child node, if it exists |
public static boolean isValidIPAddress(String address){
if (address == null || address.length() == 0) {
return false;
}
boolean ipv6Expected=false;
if (address.charAt(0) == '[') {
if (address.length() > 2 && address.charAt(address.length() - 1) == ']') {
address=address.substring(1,address.length() - 1);
ipv6Expected=true;
}
else {
return false;
}
}
if (Character.digit(address.charAt(0),16) != -1 || (address.charAt(0) == ':')) {
byte[] addr=null;
addr=strToIPv4(address);
if (addr == null) {
addr=strToIPv6(address);
}
else if (ipv6Expected) {
return false;
}
if (addr != null) {
return true;
}
}
return false;
}
| Checks whether <tt>address</tt> is a valid IP address string. |
private void loadVerticesAndRelatives(){
List<CnATreeElement> elementList=new LinkedList<CnATreeElement>();
for ( IGraphElementLoader loader : getLoaderList()) {
loader.setCnaTreeElementDao(getCnaTreeElementDao());
elementList.addAll(loader.loadElements());
}
for ( CnATreeElement element : elementList) {
graph.addVertex(element);
if (LOG.isDebugEnabled()) {
LOG.debug("Vertex added: " + element.getTitle());
}
uuidMap.put(element.getUuid(),element);
}
for ( CnATreeElement parent : elementList) {
Set<CnATreeElement> children=parent.getChildren();
for ( CnATreeElement child : children) {
createParentChildEdge(parent,child);
}
}
}
| Loads all vertices and adds them to the graph. An edge for each children is added if the child is part of the graph. |
private void initializeLiveAttributes(){
transform=createLiveAnimatedTransformList(null,SVG_TRANSFORM_ATTRIBUTE,"");
externalResourcesRequired=createLiveAnimatedBoolean(null,SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE,false);
}
| Initializes the live attribute values of this element. |
public void putParcelable(String key,Parcelable value){
unparcel();
mMap.put(key,value);
mFdsKnown=false;
}
| Inserts a Parcelable value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. |
public static <T>Collection<T> flatten(Iterable<T> self,Closure<? extends T> flattenUsing){
return flatten(self,createSimilarCollection(self),flattenUsing);
}
| Flatten an Iterable. This Iterable and any nested arrays or collections have their contents (recursively) added to the new collection. For any non-Array, non-Collection object which represents some sort of collective type, the supplied closure should yield the contained items; otherwise, the closure should just return any element which corresponds to a leaf. |
public double semiDeviation(){
return Math.sqrt(semiVariance());
}
| returns the semi deviation, defined as the square root of the semi variance. |
public Object runSafely(Catbert.FastStack stack) throws Exception {
String val=getString(stack);
Sage.put(getString(stack),val);
return null;
}
| Sets the property with the specified name to the specified value. If this is called from a client instance then it will use the properties on the server system for this call and the change will be made on the server system. |
protected Preference createUserDictionaryPreference(String locale,Activity activity){
final Preference newPref=new Preference(getActivity());
final Intent intent=new Intent(USER_DICTIONARY_SETTINGS_INTENT_ACTION);
if (null == locale) {
newPref.setTitle(Locale.getDefault().getDisplayName());
}
else {
if ("".equals(locale)) newPref.setTitle(getString(R.string.user_dict_settings_all_languages));
else newPref.setTitle(Utils.createLocaleFromString(locale).getDisplayName());
intent.putExtra("locale",locale);
newPref.getExtras().putString("locale",locale);
}
newPref.setIntent(intent);
newPref.setFragment(com.android.settings.UserDictionarySettings.class.getName());
return newPref;
}
| Create a single User Dictionary Preference object, with its parameters set. |
public static <T>T withPrintWriter(Path self,@ClosureParams(value=SimpleType.class,options="java.io.PrintWriter") Closure<T> closure) throws IOException {
return IOGroovyMethods.withWriter(newPrintWriter(self),closure);
}
| Create a new PrintWriter for this file which is then passed it into the given closure. This method ensures its the writer is closed after the closure returns. |
public void testBug77649() throws Exception {
Properties props=getPropertiesFromTestsuiteUrl();
String host=props.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
String port=props.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);
String[] hosts=new String[]{host,"address","address.somewhere","addressing","addressing.somewhere"};
UnreliableSocketFactory.flushAllStaticData();
for (int i=1; i < hosts.length; i++) {
UnreliableSocketFactory.mapHost(hosts[i],host);
}
props=getHostFreePropertiesFromTestsuiteUrl();
props.setProperty("socketFactory",UnreliableSocketFactory.class.getName());
for ( String h : hosts) {
getConnectionWithProps(String.format("jdbc:mysql://%s:%s",h,port),props).close();
getConnectionWithProps(String.format("jdbc:mysql://address=(protocol=tcp)(host=%s)(port=%s)",h,port),props).close();
}
}
| Tests fix for Bug#77649 - URL start with word "address",JDBC can't parse the "host:port" Correctly. |
public final Iterator<PluginPatternMatcher> pathsIterator(){
return mDataPaths != null ? mDataPaths.iterator() : null;
}
| Return an iterator over the filter's data paths. |
private void checkInMoving(float x,float y){
final int xDiff=(int)Math.abs(x - lastMotionX);
final int yDiff=(int)Math.abs(y - lastMotionY);
final int touchSlop=this.touchSlop;
boolean xMoved=xDiff > touchSlop;
boolean yMoved=yDiff > touchSlop;
if (xMoved) {
touchState=TOUCH_STATE_SCROLLING_X;
lastMotionX=x;
lastMotionY=y;
}
if (yMoved) {
touchState=TOUCH_STATE_SCROLLING_Y;
lastMotionX=x;
lastMotionY=y;
}
}
| Check if the user is moving the cell |
public final boolean checkInstance(Instance instance){
if (instance.numAttributes() != numAttributes()) {
return false;
}
for (int i=0; i < numAttributes(); i++) {
if (instance.isMissing(i)) {
continue;
}
else if (attribute(i).isNominal() || attribute(i).isString()) {
if (!(Utils.eq(instance.value(i),(double)(int)instance.value(i)))) {
return false;
}
else if (Utils.sm(instance.value(i),0) || Utils.gr(instance.value(i),attribute(i).numValues())) {
return false;
}
}
}
return true;
}
| Checks if the given instance is compatible with this dataset. Only looks at the size of the instance and the ranges of the values for nominal and string attributes. |
private static byte[] concatBytes(byte[] array1,byte[] array2){
byte[] cBytes=new byte[array1.length + array2.length];
try {
System.arraycopy(array1,0,cBytes,0,array1.length);
System.arraycopy(array2,0,cBytes,array1.length,array2.length);
}
catch ( Exception e) {
throw new FacesException(e);
}
return cBytes;
}
| This method concatenates two byte arrays |
void layout(int delta,boolean animate){
if (mDataChanged) {
handleDataChanged();
}
if (getCount() == 0) {
resetList();
return;
}
if (mNextSelectedPosition >= 0) {
setSelectedPositionInt(mNextSelectedPosition);
}
recycleAllViews();
detachAllViewsFromParent();
int count=getAdapter().getCount();
float angleUnit=360.0f / count;
float angleOffset=mSelectedPosition * angleUnit;
for (int i=0; i < getAdapter().getCount(); i++) {
float angle=angleUnit * i - angleOffset;
if (angle < 0.0f) angle=360.0f + angle;
makeAndAddView(i,angle);
}
mRecycler.clear();
invalidate();
setNextSelectedPositionInt(mSelectedPosition);
checkSelectionChanged();
mNeedSync=false;
updateSelectedItemMetadata();
}
| Setting up images. |
private void updateMenuItems(boolean isGpsStarted,boolean isRecording){
boolean hasTrack=listView != null && listView.getCount() != 0;
if (startGpsMenuItem != null) {
startGpsMenuItem.setVisible(!isRecording);
if (!isRecording) {
startGpsMenuItem.setTitle(isGpsStarted ? R.string.menu_stop_gps : R.string.menu_start_gps);
startGpsMenuItem.setIcon(isGpsStarted ? R.drawable.ic_menu_stop_gps : R.drawable.ic_menu_start_gps);
TrackIconUtils.setMenuIconColor(startGpsMenuItem);
}
}
if (playMultipleItem != null) {
playMultipleItem.setVisible(hasTrack);
}
if (syncNowMenuItem != null) {
syncNowMenuItem.setTitle(driveSync ? R.string.menu_sync_now : R.string.menu_sync_drive);
}
if (aggregatedStatisticsMenuItem != null) {
aggregatedStatisticsMenuItem.setVisible(hasTrack);
}
if (exportAllMenuItem != null) {
exportAllMenuItem.setVisible(hasTrack && !isRecording);
}
if (importAllMenuItem != null) {
importAllMenuItem.setVisible(!isRecording);
}
if (deleteAllMenuItem != null) {
deleteAllMenuItem.setVisible(hasTrack && !isRecording);
}
}
| Updates the menu items. |
public boolean isDuplicateSupported(){
return duplicateSupported;
}
| Indicates whether this connection request supports duplicate entries in the request queue |
public void onStart(){
}
| Called when the animation starts. |
public static int[][] loadPNMFile(InputStream str) throws IOException {
BufferedInputStream stream=new BufferedInputStream(str);
String type=tokenizeString(stream);
if (type.equals("P1")) return loadPlainPBM(stream);
else if (type.equals("P2")) return loadPlainPGM(stream);
else if (type.equals("P4")) return loadRawPBM(stream);
else if (type.equals("P5")) return loadRawPGM(stream);
else throw new IOException("Not a viable PBM or PGM stream");
}
| Loads plain or raw PGM files or plain or raw PBM files and return the result as an int[][]. The Y dimension is not flipped. |
public BiCorpus alignedFromFiles(String f) throws IOException {
return new BiCorpus(fpath + f + extf,epath + f + exte,apath + f + exta);
}
| Generate aligned BiCorpus. |
public LognormalDistr(double shape,double scale){
numGen=new LogNormalDistribution(scale,shape);
}
| Instantiates a new Log-normal pseudo random number generator. |
private static String contentLengthHeader(final long length){
return String.format("Content-Length: %d",length);
}
| Format Content-Length header. |
@Bean @ConditionalOnMissingBean public AmqpSenderService amqpSenderServiceBean(){
return new DefaultAmqpSenderService(rabbitTemplate());
}
| Create default amqp sender service bean. |
@Override protected void initialize(){
super.initialize();
m_Processor=new MarkdownProcessor();
m_Markdown="";
}
| Initializes the members. |
public void upperBound(byte[] key) throws IOException {
upperBound(key,0,key.length);
}
| Move the cursor to the first entry whose key is strictly greater than the input key. Synonymous to upperBound(key, 0, key.length). The entry returned by the previous entry() call will be invalid. |
public static String replaceLast(String s,char sub,char with){
int index=s.lastIndexOf(sub);
if (index == -1) {
return s;
}
char[] str=s.toCharArray();
str[index]=with;
return new String(str);
}
| Replaces the very last occurrence of a character in a string. |
public static void main(String[] args){
Thrust simulation=new Thrust();
simulation.run();
}
| Entry point for the example application. |
public static <T>T checkNotNull(T reference,@Nullable String errorMessageTemplate,@Nullable Object... errorMessageArgs){
if (reference == null) {
throw new NullPointerException(format(errorMessageTemplate,errorMessageArgs));
}
return reference;
}
| Ensures that an object reference passed as a parameter to the calling method is not null. |
public boolean insert(String name,RegExp definition){
if (Options.DEBUG) Out.debug("inserting macro " + name + " with definition :"+ Out.NL+ definition);
used.put(name,Boolean.FALSE);
return macros.put(name,definition) == null;
}
| Stores a new macro and its definition. |
public boolean add(Object o){
ensureCapacity(size + 1);
elementData[size++]=o;
return true;
}
| Appends the specified element to the end of this list. |
public InvocationTargetException(Throwable target,String s){
super(s,null);
this.target=target;
}
| Constructs a InvocationTargetException with a target exception and a detail message. |
public boolean isExternalSkin(){
return !isDefaultSkin && mResources != null;
}
| whether the skin being used is from external .skin file |
private void updateActions(){
actions.removeAll();
final ActionGroup mainActionGroup=(ActionGroup)actionManager.getAction(getGroupMenu());
if (mainActionGroup == null) {
return;
}
final Action[] children=mainActionGroup.getChildren(null);
for ( final Action action : children) {
final Presentation presentation=presentationFactory.getPresentation(action);
final ActionEvent e=new ActionEvent(ActionPlaces.MAIN_CONTEXT_MENU,presentation,actionManager,0);
action.update(e);
if (presentation.isVisible()) {
actions.add(action);
}
}
}
| Updates the list of visible actions. |
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. |
TechCategory fallthrough(){
switch (this) {
case OMNI_AERO:
return OMNI;
case CLAN_AERO:
case CLAN_VEE:
return CLAN;
case IS_ADVANCED_AERO:
case IS_ADVANCED_VEE:
return IS_ADVANCED;
default :
return null;
}
}
| If no value is provided for ASFs or Vees, use the base value. |
static void svd_dscal(int n,double da,double[] dx,int incx){
if (n <= 0 || incx == 0) return;
int ix=(incx < 0) ? n - 1 : 0;
for (int i=0; i < n; i++) {
dx[ix]*=da;
ix+=incx;
}
return;
}
| Function scales a vector by a constant. * Based on Fortran-77 routine from Linpack by J. Dongarra |
public CampoFechaVO insertValue(final CampoFechaVO value){
try {
DbConnection conn=getConnection();
DbInsertFns.insert(conn,TABLE_NAME,DbUtil.getColumnNames(COL_DEFS),new SigiaDbInputRecord(COL_DEFS,value));
return value;
}
catch ( Exception e) {
logger.error("Error insertando campo de tipo fecha para el descriptor " + value.getIdObjeto(),e);
throw new DBException("insertando campo de tipo fecha",e);
}
}
| Inserta un valor de tipo fecha. |
private synchronized void closeActiveFile(){
StringWriterFile activeFile=this.activeFile;
try {
this.activeFile=null;
if (activeFile != null) {
activeFile.close();
getPolicy().closeActiveFile(activeFile.path());
activeFile=null;
}
}
catch ( IOException e) {
trace.error("error closing active file '{}'",activeFile.path(),e);
}
}
| close, finalize, and apply retention policy |
public void testWARTypeEquality(){
WAR war1=new WAR("/some/path/to/file.war");
WAR war2=new WAR("/otherfile.war");
assertEquals(war1.getType(),war2.getType());
}
| Test equality between WAR deployables. |
public static Vector readSignatureAlgorithmsExtension(byte[] extensionData) throws IOException {
if (extensionData == null) {
throw new IllegalArgumentException("'extensionData' cannot be null");
}
ByteArrayInputStream buf=new ByteArrayInputStream(extensionData);
Vector supported_signature_algorithms=parseSupportedSignatureAlgorithms(false,buf);
TlsProtocol.assertEmpty(buf);
return supported_signature_algorithms;
}
| Read 'signature_algorithms' extension data. |
public void updateNCharacterStream(int columnIndex,java.io.Reader x,long length) throws SQLException {
throw new SQLFeatureNotSupportedException(resBundle.handleGetObject("jdbcrowsetimpl.featnotsupp").toString());
}
| Updates the designated column with a character stream value, which will have the specified number of bytes. The driver does the necessary conversion from Java character format to the national character set in the database. It is intended for use when updating NCHAR,NVARCHAR and LONGNVARCHAR columns. The updater methods are used to update column values in the current row or the insert row. The updater methods do not update the underlying database; instead the updateRow or insertRow methods are called to update the database. |
public boolean isModified(){
return isCustom() && !isUserAdded();
}
| Returns whether the receiver represents a modified template, i.e. a contributed template that has been changed. |