code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private int[] locate(int number){
return new int[]{number >> SHIFT,number & MOD};
}
| Locate the bit position of given number. |
public Container add(String label){
return add(new Label(label));
}
| Simpler version of addComponent that allows chaining the calls for shorter syntax |
public final void yyclose() throws java.io.IOException {
zzAtEOF=true;
zzEndRead=zzStartRead;
if (zzReader != null) zzReader.close();
}
| Closes the input stream. |
public static void clear(){
PM.clear();
ConfigBean config=getConfig();
if (config == null || !Env.APP_SETTINGS.get(Settings.INITIAL_PER_MIN_CALC_EXCL_TIME).equals(config.getInitialPerMinCalcExclTime())) {
try {
Files.deleteIfExists(PATH_CONFIG_BEAN);
}
catch ( final IOException ie) {
Env.LOGGER.error("Failed to delete replay processor cache config: " + PATH_CONFIG_BEAN,ie);
}
config=new ConfigBean();
config.setInitialPerMinCalcExclTime(Env.APP_SETTINGS.get(Settings.INITIAL_PER_MIN_CALC_EXCL_TIME));
setConfig(config);
}
}
| Clears the replay processor cache. |
public void runRaptorScheduled(TIntIntMap initialStops,int departureTime){
long startClockTime=System.currentTimeMillis();
max_time=departureTime + req.maxTripDurationMinutes * 60;
round=0;
patternsTouchedThisRound.clear();
stopsTouchedThisSearch.clear();
stopsTouchedThisRound.clear();
TIntIntIterator iterator=initialStops.iterator();
while (iterator.hasNext()) {
iterator.advance();
int stopIndex=iterator.key();
int time=iterator.value() + departureTime;
RaptorState state=scheduleState.get(0);
if (time < state.bestTimes[stopIndex]) {
state.bestTimes[stopIndex]=time;
state.transferStop[stopIndex]=-1;
markPatternsForStop(stopIndex);
}
}
advanceToNextRound();
while (doOneRound(scheduleState.get(round - 1),scheduleState.get(round),false,null) && round < req.maxRides) {
advanceToNextRound();
}
scheduledRounds=Math.max(round + 1,scheduledRounds);
while (round < scheduleState.size() - 1) {
scheduleState.get(round + 1).min(scheduleState.get(round));
round++;
}
scheduledSearchTime+=System.currentTimeMillis() - startClockTime;
}
| Run a raptor search on all scheduled routes, ignoring any frequency-based routes. The output of this process will be stored in the scheduleState field. |
public static boolean isSameLength(byte[] array1,byte[] array2){
if ((array1 == null && array2 != null && array2.length > 0) || (array2 == null && array1 != null && array1.length > 0) || (array1 != null && array2 != null && array1.length != array2.length)) {
return false;
}
return true;
}
| <p>Checks whether two arrays are the same length, treating <code>null</code> arrays as length <code>0</code>.</p> |
public ArrayBackedByteBuffer(final byte[] buf,final int ofs,final int pos,final int siz){
this.buf=buf;
this.ofs=ofs;
this.pos=pos;
this.siz=siz;
}
| Create a new ByteBuffer from an existing array |
private void startInvalidGrid(String name){
try {
startGrid(name);
assert false : "Exception should have been thrown.";
}
catch ( Exception e) {
info("Caught expected exception: " + e);
}
}
| Starts grid that will fail to start due to invalid configuration. |
static float interpolate(final float x,final float xmin,final float xmax,final float ymin,final float ymax){
return ((x - xmin) * (ymax - ymin) / (xmax - xmin)) + ymin;
}
| Preform interpolation on the given values. |
void pointToCellRounded(int x,int y,int[] result){
pointToCellExact(x + (mCellWidth / 2),y + (mCellHeight / 2),result);
}
| Given a point, return the cell that most closely encloses that point |
public static String findPath(Class<?> context) throws IllegalStateException {
if (context == null) {
context=DynamicJarPathFinder.class;
}
String rawName=context.getName();
String classFileName;
{
int idx=rawName.lastIndexOf('.');
classFileName=(idx == -1 ? rawName : rawName.substring(idx + 1)) + ".class";
}
String uri=context.getResource(classFileName).toString();
if (uri.startsWith("file:")) {
LOG.warn("This class has been loaded from a directory and not from a jar file: {}",uri);
String fileName=null;
try {
fileName=URLDecoder.decode(uri.substring("file:".length(),uri.length()),Charset.defaultCharset().name());
return new File(fileName).getAbsolutePath();
}
catch ( UnsupportedEncodingException e) {
throw new InternalError("default charset doesn't exist. Your VM is borked.");
}
}
if (!uri.startsWith("jar:file:")) {
int idx=uri.indexOf(':');
String protocol=idx == -1 ? "(unknown)" : uri.substring(0,idx);
throw new IllegalStateException("This class has been loaded remotely via the " + protocol + " protocol. Only loading from a jar on the local file system is supported.");
}
int idx=uri.indexOf('!');
if (idx == -1) {
throw new IllegalStateException("You appear to have loaded this class from a local jar file, but I can't make sense of the URL!");
}
try {
String fileName=URLDecoder.decode(uri.substring("jar:file:".length(),idx),Charset.defaultCharset().name());
return new File(fileName).getAbsolutePath();
}
catch ( UnsupportedEncodingException e) {
throw new InternalError("default charset doesn't exist. Your VM is borked.");
}
}
| Similar to JarPathFinder, but not make sure the path must valid jar. |
public ISourceViewer publicGetSourceViewer(){
return this.getSourceViewer();
}
| Simon put OpenDeclarationHandler as a subclass of TLAEditor because that handler needed to use AbstractTextEditor's getSourceViewer method, inherited by TLAEditor, but that's a private method. To avoid having to put ShowUsesHandler and all other classes that might want to use getSourceViewer() in TLAEditor, LL defined the following method that provides it to the public at large. |
protected double computeRandomProjection(int rpIndex,int classIndex,Instance instance){
double sum=0.0;
for (int i=0; i < instance.numValues(); i++) {
int index=instance.index(i);
if (index != classIndex) {
double value=instance.valueSparse(i);
if (!Utils.isMissingValue(value)) {
sum+=m_rmatrix[rpIndex][index] * value;
}
}
}
return sum;
}
| computes one random projection for a given instance (skip missing values) |
protected static void addStreamsOptions(ContextMenu m,int numStreams,boolean join){
String count="";
String s="";
if (numStreams > 1) {
s="s";
count=String.valueOf(numStreams) + " ";
}
String streamSubmenu="Twitch Stream" + s;
String miscSubmenu="Miscellaneous";
m.setSubMenuIcon(streamSubmenu,ICON_SPACING);
m.addSubItem("stream","Normal",streamSubmenu);
m.addSubItem("streamPopout","Popout",streamSubmenu);
m.addSeparator(streamSubmenu);
m.addSubItem("streamsMultitwitchtv","Multitwitch.tv",streamSubmenu);
m.addSubItem("streamsSpeedruntv","Speedrun.tv",streamSubmenu);
m.addSubItem("streamsKadgar","Kadgar.net",streamSubmenu);
addLivestreamerOptions(m);
if (join) {
m.addSeparator();
m.addItem("join","Join " + count + "channel"+ s);
m.addSeparator();
m.addSubItem("hostchannel","Host Channel",miscSubmenu);
m.addSeparator(miscSubmenu);
m.addSubItem("copy","Copy Stream Name",miscSubmenu);
m.addSeparator(miscSubmenu);
m.addSubItem("follow","Follow Channel",miscSubmenu);
m.addSubItem("unfollow","Unfollow Channel",miscSubmenu);
}
}
| Adds menu items to the given ContextMenu that provide ways to do stream related stuff. |
private MessagingUseBehavior(String publicMessage,String privateMessage){
this.publicMessage=publicMessage;
this.privateMessage=privateMessage;
if ((publicMessage == null) && (privateMessage == null)) {
LOGGER.warn("MessagingUseBehavior with no messages");
}
}
| Create a new MessagingUseBehavior with specified public and private messages. Either of those can be <code>null</code>, but a warning is logged if neither is specified. |
@Override public void addMouseListener(MouseListener l){
}
| No one may add mouse listeners, not even Swing! |
public LocatorDUnitTest(){
super();
}
| Creates a new <code>LocatorDUnitTest</code> |
public Bundler putParcelableArray(String key,Parcelable[] value){
bundle.putParcelableArray(key,value);
return this;
}
| Inserts an array of Parcelable values into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. |
public boolean isMtuMismatch(){
return mtuMismatch;
}
| Gets the value of the mtuMismatch property. |
public RawByteCache(File cacheDir,long maxCacheBytes,long maxObjectBytes,int maxOpenFiles){
this.cacheDir=cacheDir;
this.maxCacheBytes=maxCacheBytes;
this.maxObjectBytes=maxObjectBytes;
this.maxOpenFiles=maxOpenFiles;
}
| Instantiates a new cache. |
protected final void CAST_Encipher(int L0,int R0,int result[]){
int Lp=L0;
int Rp=R0;
int Li=L0, Ri=R0;
for (int i=1; i <= _rounds; i++) {
Lp=Li;
Rp=Ri;
Li=Rp;
switch (i) {
case 1:
case 4:
case 7:
case 10:
case 13:
case 16:
Ri=Lp ^ F1(Rp,_Km[i],_Kr[i]);
break;
case 2:
case 5:
case 8:
case 11:
case 14:
Ri=Lp ^ F2(Rp,_Km[i],_Kr[i]);
break;
case 3:
case 6:
case 9:
case 12:
case 15:
Ri=Lp ^ F3(Rp,_Km[i],_Kr[i]);
break;
}
}
result[0]=Ri;
result[1]=Li;
return;
}
| Does the 16 rounds to encrypt the block. |
public final float determinant(){
float det;
det=m00 * (m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33);
det-=m01 * (m10 * m22 * m33 + m12 * m23 * m30 + m13 * m20 * m32 - m13 * m22 * m30 - m10 * m23 * m32 - m12 * m20 * m33);
det+=m02 * (m10 * m21 * m33 + m11 * m23 * m30 + m13 * m20 * m31 - m13 * m21 * m30 - m10 * m23 * m31 - m11 * m20 * m33);
det-=m03 * (m10 * m21 * m32 + m11 * m22 * m30 + m12 * m20 * m31 - m12 * m21 * m30 - m10 * m22 * m31 - m11 * m20 * m32);
return (det);
}
| Computes the determinate of this matrix. |
public int addBarPlot(String name,Color color,double[][] XY){
return ((Plot2DCanvas)plotCanvas).addBarPlot(name,color,XY);
}
| Adds a bar plot (each data point is shown as a dot marker connected to the horizontal axis by a vertical line) to the current plot panel. |
public static double L_RankLoss(int y[],int r[]){
int L=y.length;
ArrayList<Integer> tI=new ArrayList<Integer>();
ArrayList<Integer> fI=new ArrayList<Integer>();
for (int j=0; j < L; j++) {
if (y[j] == 1) {
tI.add(j);
}
else {
fI.add(j);
}
}
if (!tI.isEmpty() && !fI.isEmpty()) {
int c=0;
for ( int k : tI) {
for ( int l : fI) {
if (position(k,r) < position(l,r)) {
c++;
}
}
}
return (double)c / (double)(tI.size() * fI.size());
}
else {
return 0.0;
}
}
| Rank Loss - the average fraction of labels which are not correctly ordered. Thanks to Noureddine Yacine NAIR BENREKIA for providing bug fix for this. |
public Headers responseHeaders(){
return mResponseHeaders;
}
| Get response headers. |
@Override protected void applyEditorTo(WeaveConfiguration runnerConfiguration) throws ConfigurationException {
runnerConfiguration.setWeaveOutput(this.configurationPanel.getOutput().getText());
runnerConfiguration.setWeaveFile(this.configurationPanel.getWeaveFile().getText());
runnerConfiguration.setMuleHome(this.configurationPanel.getWeaveHome().getText());
final Module selectedModule=this.configurationPanel.getModuleCombo().getSelectedModule();
if (selectedModule != null) {
runnerConfiguration.setModule(selectedModule);
}
runnerConfiguration.setWeaveInputs(this.configurationPanel.getWeaveInputs().getItems());
}
| This is invoked when the user fills the form and pushes apply/ok |
@Override protected void internalAdd(final TemplatePersistenceData data){
if (!data.isCustom()) {
final String id=getNewIdFromId(data.getId());
final TemplatePersistenceData d2=new TemplatePersistenceData(data.getTemplate(),true,id);
super.internalAdd(d2);
}
}
| Adds a template to the internal store. The added templates must have a unique id. |
@Override public void run2(){
try {
boolean warningLogged=false;
while (this.allBucketsRecoveredFromDisk.getCount() > 0) {
int sleepMillis=SLEEP_PERIOD;
if (!warningLogged) {
sleepMillis=SLEEP_PERIOD / 2;
}
Thread.sleep(sleepMillis);
if (this.membershipChanged) {
this.membershipChanged=false;
for ( RegionStatus region : regions) {
region.logWaitingForMembers();
}
warningLogged=true;
}
}
}
catch ( InterruptedException e) {
logger.error(e.getMessage(),e);
}
finally {
removeListeners();
for ( RegionStatus region : regions) {
if (!region.loggedDoneMessage) {
region.logDoneMessage();
}
}
}
}
| Writes a consolidated log entry every SLEEP_PERIOD that summarizes which buckets are still waiting on persistent members for the region. |
public Vector4d negate(){
x=-x;
y=-y;
z=-z;
w=-w;
return this;
}
| Negate this vector. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
private void initializeLiveAttributes(){
externalResourcesRequired=createLiveAnimatedBoolean(null,SVG_EXTERNAL_RESOURCES_REQUIRED_ATTRIBUTE,false);
}
| Initializes the live attribute values of this element. |
private String replaceReservedChars(boolean isTableResponseType,String str){
if (str == null) {
return EMPTY_COLUMN_VALUE;
}
return (!isTableResponseType) ? str : str.replace(TAB,WHITESPACE).replace(NEWLINE,WHITESPACE);
}
| For %table response replace Tab and Newline characters from the content. |
public double metersToPixels(){
double screenCenterLat=screenTopLeft.latitude - screenSize.latitude / 2;
double metersToLon=1 / (Util.LON_TO_METERS_AT_EQUATOR * Math.cos(screenCenterLat / 180 * Math.PI));
return screenSize.longitude / windowWidth * metersToLon;
}
| Returns the ratio of meters to pixels at the center of the screen |
public static boolean isAssignable(Type lhsType,Type rhsType){
Assert.notNull(lhsType,"Left-hand side type must not be null");
Assert.notNull(rhsType,"Right-hand side type must not be null");
if (lhsType.equals(rhsType) || lhsType.equals(Object.class)) {
return true;
}
if (lhsType instanceof Class<?>) {
Class<?> lhsClass=(Class<?>)lhsType;
if (rhsType instanceof Class<?>) {
return ClassUtils.isAssignable(lhsClass,(Class<?>)rhsType);
}
if (rhsType instanceof ParameterizedType) {
Type rhsRaw=((ParameterizedType)rhsType).getRawType();
if (rhsRaw instanceof Class<?>) {
return ClassUtils.isAssignable(lhsClass,(Class<?>)rhsRaw);
}
}
else if (lhsClass.isArray() && rhsType instanceof GenericArrayType) {
Type rhsComponent=((GenericArrayType)rhsType).getGenericComponentType();
return isAssignable(lhsClass.getComponentType(),rhsComponent);
}
}
if (lhsType instanceof ParameterizedType) {
if (rhsType instanceof Class<?>) {
Type lhsRaw=((ParameterizedType)lhsType).getRawType();
if (lhsRaw instanceof Class<?>) {
return ClassUtils.isAssignable((Class<?>)lhsRaw,(Class<?>)rhsType);
}
}
else if (rhsType instanceof ParameterizedType) {
return isAssignable((ParameterizedType)lhsType,(ParameterizedType)rhsType);
}
}
if (lhsType instanceof GenericArrayType) {
Type lhsComponent=((GenericArrayType)lhsType).getGenericComponentType();
if (rhsType instanceof Class<?>) {
Class<?> rhsClass=(Class<?>)rhsType;
if (rhsClass.isArray()) {
return isAssignable(lhsComponent,rhsClass.getComponentType());
}
}
else if (rhsType instanceof GenericArrayType) {
Type rhsComponent=((GenericArrayType)rhsType).getGenericComponentType();
return isAssignable(lhsComponent,rhsComponent);
}
}
if (lhsType instanceof WildcardType) {
return isAssignable((WildcardType)lhsType,rhsType);
}
return false;
}
| Check if the right-hand side type may be assigned to the left-hand side type following the Java generics rules. |
private Algorithm instantiateAlgorithm(AlgorithmProvider provider,String name,Properties properties,Problem problem){
try {
return provider.getAlgorithm(name,properties,problem);
}
catch ( ServiceConfigurationError e) {
System.err.println(e.getMessage());
}
return null;
}
| Attempts to instantiate the given algorithm using the given provider. |
public void adapt(){
double[] zmin=new double[numberOfObjectives];
double[] zmax=new double[numberOfObjectives];
Arrays.fill(zmin,Double.POSITIVE_INFINITY);
Arrays.fill(zmax,Double.NEGATIVE_INFINITY);
for ( Solution solution : this) {
for (int i=0; i < numberOfObjectives; i++) {
zmin[i]=Math.min(zmin[i],solution.getObjective(i));
zmax[i]=Math.max(zmax[i],solution.getObjective(i));
}
}
weights.clear();
for ( double[] weight : originalWeights) {
double[] newWeight=weight.clone();
for (int i=0; i < numberOfObjectives; i++) {
newWeight[i]*=Math.max(0.01,zmax[i] - zmin[i]);
}
weights.add(Vector.normalize(newWeight));
}
minAngles=new double[weights.size()];
for (int i=0; i < weights.size(); i++) {
minAngles[i]=smallestAngleBetweenWeights(i);
}
}
| Normalize the reference vectors. |
public static String stringFilterStrict(String searchText){
return searchText.replaceAll("[^ a-zA-Z0-9\\u4e00-\\u9fa5]","");
}
| Remove useless and unsafe characters. Only Chinese, numbers, English characters and space are allowed. |
public void loadByteData(int[] data,int[] dims){
this.dims=dims;
byte[] byteData=new byte[data.length];
for (int i=0; i < data.length; i++) {
byteData[i]=(byte)data[i];
}
this.data=ByteBuffer.wrap(byteData);
}
| Need to have method signature for int or octave can't match it |
protected boolean arePrimeAnnosEqual(final AnnotatedTypeMirror type1,final AnnotatedTypeMirror type2){
if (currentTop != null) {
return AnnotationUtils.areSame(type1.getAnnotationInHierarchy(currentTop),type2.getAnnotationInHierarchy(currentTop));
}
return AnnotationUtils.areSame(type1.getAnnotations(),type2.getAnnotations());
}
| Return true if type1 and type2 have the same set of annotations. |
protected void writeImageDesc() throws IOException {
out.write(0x2c);
writeShort(0);
writeShort(0);
writeShort(width);
writeShort(height);
if (firstFrame) {
out.write(0);
}
else {
out.write(0x80 | 0 | 0| 0| palSize);
}
}
| Writes Image Descriptor |
public StreamResult(String systemId){
this.systemId=systemId;
}
| Construct a StreamResult from a URL. |
private void updatePhysicalInterval(Register p,BasicInterval i){
CompoundInterval physInterval=regAllocState.getInterval(p);
if (physInterval == null) {
regAllocState.setInterval(p,new CompoundInterval(i,p));
}
else {
CompoundInterval ci=new CompoundInterval(i,p);
if (VM.VerifyAssertions) VM._assert(!ci.intersects(physInterval));
physInterval.addAll(ci);
}
}
| Updates the interval representing the allocations of a physical register p to include a new interval i. |
@Override public String toString(){
StringBuffer result=new StringBuffer();
for (int i=0; i < data.length; i++) {
result.append((i == 0 ? "" : ",") + data[i]);
}
return result.toString();
}
| Returns a string representation of the data row. |
public BoolLiteralItemProvider(AdapterFactory adapterFactory){
super(adapterFactory);
}
| This constructs an instance from a factory and a notifier. <!-- begin-user-doc --> <!-- end-user-doc --> |
private static void initGameFolder(){
String defaultFolder=System.getProperty("user.home") + STENDHAL_FOLDER;
String unixLikes="AIX|Digital Unix|FreeBSD|HP UX|Irix|Linux|Mac OS X|Solaris";
String system=System.getProperty("os.name");
if (system.matches(unixLikes)) {
File f=new File(defaultFolder + "user.dat");
if (!f.exists()) {
gameFolder=System.getProperty("user.home") + separator + ".config"+ separator+ STENDHAL_FOLDER;
return;
}
}
gameFolder=defaultFolder;
}
| Initialize the client game directory. <p> NOTE: IF YOU CHANGE THIS, CHANGE ALSO CORRESPONDING CODE IN Bootstrap.java |
public void addCMap(short platformID,short platformSpecificID,CMap cMap){
CmapSubtable key=new CmapSubtable(platformID,platformSpecificID);
subtables.put(key,cMap);
}
| Add a CMap |
public static void incrementalWeightedUpdate(DoubleArrayList data,DoubleArrayList weights,int from,int to,double[] inOut){
int dataSize=data.size();
checkRangeFromTo(from,to,dataSize);
if (dataSize != weights.size()) throw new IllegalArgumentException("from=" + from + ", to="+ to+ ", data.size()="+ dataSize+ ", weights.size()="+ weights.size());
double sum=inOut[0];
double sumOfSquares=inOut[1];
double[] elements=data.elements();
double[] w=weights.elements();
for (int i=from - 1; ++i <= to; ) {
double element=elements[i];
double weight=w[i];
double prod=element * weight;
sum+=prod;
sumOfSquares+=element * prod;
}
inOut[0]=sum;
inOut[1]=sumOfSquares;
}
| Incrementally maintains and updates sum and sum of squares of a <i>weighted</i> data sequence. Assume we have already recorded some data sequence elements and know their sum and sum of squares. Assume further, we are to record some more elements and to derive updated values of sum and sum of squares. <p> This method computes those updated values without needing to know the already recorded elements. This is interesting for interactive online monitoring and/or applications that cannot keep the entire huge data sequence in memory. <p> <br>Definition of sum: <tt>sum = Sum ( data[i] * weights[i] )</tt>. <br>Definition of sumOfSquares: <tt>sumOfSquares = Sum ( data[i] * data[i] * weights[i])</tt>. |
public static UpdateSettingsRequest updateSettingsRequest(String... indices){
return new UpdateSettingsRequest(indices);
}
| A request to update indices settings. |
public SQLTransientException(String reason,Throwable cause){
super(reason,cause);
}
| Creates an SQLTransientException object. The Reason string is set to the given and the cause Throwable object is set to the given cause Throwable object. |
public static boolean isCompareOperator(BinaryOperator bOp){
return (bOp.fn instanceof LessThan || bOp.fn instanceof LessThanEquals || bOp.fn instanceof GreaterThan|| bOp.fn instanceof GreaterThanEquals|| bOp.fn instanceof Equals|| bOp.fn instanceof NotEquals);
}
| This will return if uaggOp is of type RowIndexMin |
@Override protected EClass eStaticClass(){
return DatatypePackage.Literals.ENUM_LITERAL_PROPERTY_ATTRIBUTE;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public void contextCreated(ELContextEvent ece){
FacesContext context=FacesContext.getCurrentInstance();
if (context == null) {
return;
}
ELContext source=(ELContext)ece.getSource();
source.putContext(FacesContext.class,context);
ExpressionFactory exFactory=ELUtils.getDefaultExpressionFactory(context);
if (null != exFactory) {
source.putContext(ExpressionFactory.class,exFactory);
}
ELContextListener[] listeners=context.getApplication().getELContextListeners();
if (listeners == null) {
return;
}
for (int i=0; i < listeners.length; ++i) {
ELContextListener elcl=listeners[i];
elcl.contextCreated(new ELContextEvent(source));
}
}
| Invoked when a new <code>ELContext</code> has been created. |
public static void launchActivity(Activity context,Class<? extends Activity> activity,boolean closeCurrentActivity,Map<String,String> params){
Intent intent=new Intent(context,activity);
if (params != null) {
Bundle bundle=new Bundle();
for ( Entry<String,String> param : params.entrySet()) {
bundle.putString(param.getKey(),param.getValue());
}
intent.putExtras(bundle);
}
context.startActivity(intent);
if (closeCurrentActivity) {
context.finish();
}
}
| Launch an Activity. |
static XPath rewriteChildToExpression(ElemTemplateElement varElem) throws TransformerException {
ElemTemplateElement t=varElem.getFirstChildElem();
if (null != t && null == t.getNextSiblingElem()) {
int etype=t.getXSLToken();
if (Constants.ELEMNAME_VALUEOF == etype) {
ElemValueOf valueof=(ElemValueOf)t;
if (valueof.getDisableOutputEscaping() == false && valueof.getDOMBackPointer() == null) {
varElem.m_firstChild=null;
return new XPath(new XRTreeFragSelectWrapper(valueof.getSelect().getExpression()));
}
}
else if (Constants.ELEMNAME_TEXTLITERALRESULT == etype) {
ElemTextLiteral lit=(ElemTextLiteral)t;
if (lit.getDisableOutputEscaping() == false && lit.getDOMBackPointer() == null) {
String str=lit.getNodeValue();
XString xstr=new XString(str);
varElem.m_firstChild=null;
return new XPath(new XRTreeFragSelectWrapper(xstr));
}
}
}
return null;
}
| If the children of a variable is a single xsl:value-of or text literal, it is cheaper to evaluate this as an expression, so try and adapt the child an an expression. |
public final void testParsesFuzz(){
StringBuilder testCases=new StringBuilder();
String randomJs="";
boolean failed=false;
for (int testCaseCount=0; testCaseCount < MAX_NUMBER_OF_TESTS; testCaseCount++) {
try {
randomJs=fudgeroonify();
js(fromString(randomJs));
}
catch ( ParseException e) {
}
catch ( Throwable e) {
failed=true;
testCases.append(generateTestCase(randomJs,testCaseCount,e.getMessage()));
}
}
System.err.print(testCases.toString());
if (failed) {
fail();
}
}
| Test parser against a snippet of fuzzed javascript Fail if the parser throws anything other than a ParseException. Formats and prints the failing case to stderr for pasting in to JUnit tests |
public SVMExamples(int size,double b){
this.train_size=size;
this.b=b;
atts=new double[train_size][];
index=new int[train_size][];
ys=new double[train_size];
alphas=new double[train_size];
ids=new String[size];
}
| Creates an empty example set of the given size. |
public static KeyInfo generateKey(String tokenId) throws Exception {
LOG.trace("Generating key for token '{}'",tokenId);
KeyInfo keyInfo=execute(new GenerateKey(tokenId));
LOG.trace("Received response with keyId '{}' and public key '{}'",keyInfo.getId(),keyInfo.getPublicKey());
return keyInfo;
}
| Generate a new key for the token with the given ID. |
private void badIndex(int index) throws ArrayIndexOutOfBoundsException {
String msg="Attempt to modify attribute at illegal index: " + index;
throw new ArrayIndexOutOfBoundsException(msg);
}
| Report a bad array index in a manipulator. |
@Override public void load(Element element,Object o){
log.error("Unexpected call of load(Element, Object)");
}
| Update static data from XML file |
public V put(String text,V value){
return put(text.toCharArray(),value);
}
| Add the given mapping. |
public static boolean isLandscape(Context context){
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
}
| is landscape |
public boolean queueSurfaceDataReplacing(Component c,Runnable r){
return false;
}
| This method is invoked from the toolkit thread when the surface data of the component needs to be replaced. The method run() of the Runnable argument performs surface data replacing, run() should be invoked on the EDT of this component's AppContext. Returns true if the Runnable has been enqueued to be invoked on the EDT. (Fix 6255371.) |
private static String parseContent(XmlPullParser parser) throws XmlPullParserException, IOException {
int parserDepth=parser.getDepth();
return parseContentDepth(parser,parserDepth);
}
| Returns the content of a tag as string regardless of any tags included. |
public final void deleteTables(SQL[] tables) throws AdeException {
if (tables == null) {
return;
}
for ( SQL table : tables) {
TableGeneralUtils.deleteTable(table.toString());
}
}
| Deletes a table |
public long length(){
return getBestPath().length();
}
| Returns the length of the best path. |
public static void waitForCondition(String condition){
BValue cond=getCond(condition);
synchronized (cond) {
if (!cond.v) {
try {
cond.wait();
}
catch ( InterruptedException e) {
}
}
}
}
| If the named condition does not exist, then it is created and initialized to false. If the condition exists or has just been created and its value is false, then the thread blocks until another thread sets the condition. If the condition exists and is already set to true, then this call returns immediately without blocking. |
@Override public float estimateFutureCost(Rule rule,DPState state,Sentence sentence){
return 0.0f;
}
| We don't compute a future cost. |
public static <T>T[] subarray(T[] buffer,int offset,int length){
Class<T> componentType=(Class<T>)buffer.getClass().getComponentType();
return subarray(buffer,offset,length,componentType);
}
| Returns subarray. |
@Override public boolean job(){
if (currentQuery == null && querystack != null && querystack.size() > 0) {
currentQuery=querystack.iterator().next();
querystack.remove(currentQuery);
initPeerList();
}
if (currentQuery != null && !currentQuery.isEmpty()) {
if (currentTargets != null && !currentTargets.isEmpty()) {
while (currentTargets.size() > 0) {
String peerhash=currentTargets.iterator().next();
currentTargets.remove(peerhash);
Seed seed=Switchboard.getSwitchboard().peers.getConnected(peerhash);
if (seed != null) {
processSingleTarget(seed);
return true;
}
}
}
currentQuery=null;
}
checkBookmarkDB();
ConcurrentLog.fine(AutoSearch.class.getName(),"nothing to do");
return this.querystack.size() > 0;
}
| Process query queue, select one query and peer to ask next |
public Iterator<AnalysisPass> passIterator(){
return passList.iterator();
}
| Get an Iterator over the AnalysisPasses. |
private static InetAddress[] lookupHostByName(String host) throws UnknownHostException {
BlockGuard.getThreadPolicy().onNetwork();
Object cachedResult=addressCache.get(host);
if (cachedResult != null) {
if (cachedResult instanceof InetAddress[]) {
return (InetAddress[])cachedResult;
}
else {
throw new UnknownHostException((String)cachedResult);
}
}
try {
StructAddrinfo hints=new StructAddrinfo();
hints.ai_flags=AI_ADDRCONFIG;
hints.ai_family=AF_UNSPEC;
hints.ai_socktype=SOCK_STREAM;
InetAddress[] addresses=Libcore.os.getaddrinfo(host,hints);
for ( InetAddress address : addresses) {
address.hostName=host;
}
addressCache.put(host,addresses);
return addresses;
}
catch ( GaiException gaiException) {
if (gaiException.getCause() instanceof ErrnoException) {
if (((ErrnoException)gaiException.getCause()).errno == EACCES) {
throw new SecurityException("Permission denied (missing INTERNET permission?)",gaiException);
}
}
String detailMessage="Unable to resolve host \"" + host + "\": "+ Libcore.os.gai_strerror(gaiException.error);
addressCache.putUnknownHost(host,detailMessage);
throw gaiException.rethrowAsUnknownHostException(detailMessage);
}
}
| Resolves a hostname to its IP addresses using a cache. |
public static void sort(AbstractList array){
Object temp;
int j, n=array.size();
for (j=n / 2; j > 0; j--) {
adjust(array,j,n);
}
for (j=n - 1; j > 0; j--) {
temp=array.get(0);
array.set(0,array.get(j));
array.set(j,temp);
adjust(array,1,j);
}
}
| Sorts a vector of comparable objects into increasing order. |
private void initLabelsAndModels(ArrayList<GeneratorInterface> generators,ClassLabel[] labels,Model[] models,Pattern reassign){
int existingclusters=0;
if (reassign != null) {
for (int i=0; i < labels.length; i++) {
final GeneratorInterface curclus=generators.get(i);
if (!reassign.matcher(curclus.getName()).find()) {
labels[i]=new SimpleClassLabel(curclus.getName());
models[i]=curclus.makeModel();
++existingclusters;
}
}
if (existingclusters == 0) {
LOG.warning("All clusters matched the 'reassign' pattern. Ignoring.");
}
if (existingclusters == 1) {
for (int i=0; i < labels.length; i++) {
if (labels[i] != null) {
Arrays.fill(labels,labels[i]);
Arrays.fill(models,models[i]);
break;
}
}
}
if (existingclusters == labels.length) {
LOG.warning("No clusters matched the 'reassign' pattern.");
}
}
if (existingclusters == 0) {
for (int i=0; i < labels.length; i++) {
final GeneratorInterface curclus=generators.get(i);
labels[i]=new SimpleClassLabel(curclus.getName());
models[i]=curclus.makeModel();
}
}
}
| Initialize cluster labels and models. Clusters that are set to "reassign" will have their labels set to null, or if there is only one possible reassignment, to this target label. |
public Directory<T> addFolder(Directory<T> subDirectory){
return folder.put(subDirectory.getName(),subDirectory);
}
| Adds a sub directory |
@Override protected EClass eStaticClass(){
return TypesPackage.Literals.TGETTER;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
protected void init_actions(){
action_obj=new CUP$actions();
}
| action encapsulation object initializer |
public boolean newMessage(List<Object> cmds){
if (!isBlocked && failoverHandler != null) {
if (unprocessedCount() != 0) {
processPendingMessages();
}
failoverHandler.accept(cmds);
return true;
}
else {
synchronized (this) {
notProcessedTransactions.add(cmds);
}
return false;
}
}
| Must always be called by single thread only. |
public CNodeChooserTable(final ZyGraph graph,final CGraphSearchField searchField){
m_graph=Preconditions.checkNotNull(graph,"IE01773: Graph argument can't be null.");
m_searchField=Preconditions.checkNotNull(searchField,"IE01774: Search field argument can not be null");
m_model=new CNodeChooserModel(graph);
setModel(m_model);
final TableRowSorter<CNodeChooserModel> tableSorter=new TableRowSorter<CNodeChooserModel>(m_model);
setRowSorter(tableSorter);
tableSorter.setComparator(CNodeChooserModel.COLUMN_IN,new IntComparator());
tableSorter.setComparator(CNodeChooserModel.COLUMN_OUT,new IntComparator());
tableSorter.setComparator(CNodeChooserModel.COLUMN_ADDRESS,new LexicalComparator());
tableSorter.setComparator(CNodeChooserModel.COLUMN_COLOR,new IntComparator());
final CNodeChooserRenderer renderer=new CNodeChooserRenderer(this,m_graph,m_searchField.getGraphSearcher());
setRowSelectionAllowed(true);
setColumnSelectionAllowed(false);
setCellSelectionEnabled(false);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
getTableHeader().setReorderingAllowed(false);
getColumnModel().getColumn(0).setCellRenderer(renderer);
getColumnModel().getColumn(1).setCellRenderer(renderer);
getColumnModel().getColumn(2).setCellRenderer(renderer);
getColumnModel().getColumn(3).setCellRenderer(renderer);
getColumnModel().getColumn(0).setPreferredWidth(35);
getColumnModel().getColumn(1).setPreferredWidth(35);
getColumnModel().getColumn(3).setPreferredWidth(50);
getColumnModel().getColumn(0).setMaxWidth(50);
getColumnModel().getColumn(1).setMaxWidth(50);
getColumnModel().getColumn(3).setMaxWidth(50);
m_searchField.addListener(m_searchFieldListener);
m_mouselistener=new CNodeChooserMouseListener(this,graph);
addMouseListener(m_mouselistener);
m_graph.addListener((INaviGraphListener)m_viewListener);
m_graph.addListener((IZyGraphSelectionListener)m_viewListener);
initializeViewListeners(m_graph.getRawView());
}
| Creates a new node chooser table. |
protected JsonDeserializer<Object> _findRootDeserializer(DeserializationConfig cfg,JavaType valueType) throws JsonMappingException {
if (valueType == null) {
throw new JsonMappingException("No value type configured for ObjectReader");
}
JsonDeserializer<Object> deser=_rootDeserializers.get(valueType);
if (deser != null) {
return deser;
}
deser=_provider.findTypedValueDeserializer(cfg,valueType,null);
if (deser == null) {
throw new JsonMappingException("Can not find a deserializer for type " + valueType);
}
_rootDeserializers.put(valueType,deser);
return deser;
}
| Method called to locate deserializer for the passed root-level value. |
public void write(BufferedImage bimg,OutputStream os) throws IOException {
ImageWriter writer=null;
ImageOutputStream ios=null;
try {
writer=lookupImageWriterForFormat(imageFormat);
ios=ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam iwparam=getImageWriteParameters(writer);
writer.write(null,new IIOImage(bimg,null,null),iwparam);
}
finally {
if (ios != null) {
try {
ios.flush();
}
catch ( IOException e) {
}
try {
ios.close();
}
catch ( IOException e) {
}
}
if (writer != null) {
writer.dispose();
}
}
}
| Writes the image out to the target file, creating the file if necessary, or overwriting if it already exists. |
static void createNetwork2(final MutableScenario scenario){
Network network=(Network)scenario.getNetwork();
network.setCapacityPeriod(Time.parseTime("01:00:00"));
Node node0=NetworkUtils.createAndAddNode(network,Id.create("0",Node.class),new Coord((double)0,(double)10));
Node node1=NetworkUtils.createAndAddNode(network,Id.create("1",Node.class),new Coord((double)0,(double)100));
Node node2=NetworkUtils.createAndAddNode(network,Id.create("2",Node.class),new Coord((double)100,(double)100));
Node node3=NetworkUtils.createAndAddNode(network,Id.create("3",Node.class),new Coord((double)150,(double)150));
Node node4=NetworkUtils.createAndAddNode(network,Id.create("4",Node.class),new Coord((double)200,(double)100));
Node node5=NetworkUtils.createAndAddNode(network,Id.create("5",Node.class),new Coord((double)300,(double)100));
final double y5=-100;
Node node6=NetworkUtils.createAndAddNode(network,Id.create("6",Node.class),new Coord((double)300,y5));
final double y4=-100;
Node node7=NetworkUtils.createAndAddNode(network,Id.create("7",Node.class),new Coord((double)200,y4));
final double y3=-150;
Node node8=NetworkUtils.createAndAddNode(network,Id.create("8",Node.class),new Coord((double)150,y3));
final double y2=-100;
Node node9=NetworkUtils.createAndAddNode(network,Id.create("9",Node.class),new Coord((double)100,y2));
final double y1=-100;
Node node10=NetworkUtils.createAndAddNode(network,Id.create("10",Node.class),new Coord((double)0,y1));
final double y=-10;
Node node11=NetworkUtils.createAndAddNode(network,Id.create("11",Node.class),new Coord((double)0,y));
final Node fromNode=node0;
final Node toNode=node1;
NetworkUtils.createAndAddLink(network,Id.create("1",Link.class),fromNode,toNode,(double)100,(double)5,(double)100,(double)1);
final Node fromNode1=node1;
final Node toNode1=node2;
NetworkUtils.createAndAddLink(network,Id.create("2",Link.class),fromNode1,toNode1,(double)100,(double)5,(double)100,(double)1);
final Node fromNode2=node2;
final Node toNode2=node3;
NetworkUtils.createAndAddLink(network,Id.create("3",Link.class),fromNode2,toNode2,(double)100,(double)5,(double)100,(double)1);
final Node fromNode3=node3;
final Node toNode3=node4;
NetworkUtils.createAndAddLink(network,Id.create("4",Link.class),fromNode3,toNode3,(double)100,(double)5,(double)100,(double)1);
final Node fromNode4=node2;
final Node toNode4=node4;
NetworkUtils.createAndAddLink(network,Id.create("5",Link.class),fromNode4,toNode4,(double)100,(double)5,(double)100,(double)1);
final Node fromNode5=node4;
final Node toNode5=node5;
NetworkUtils.createAndAddLink(network,Id.create("6",Link.class),fromNode5,toNode5,(double)100,(double)5,(double)100,(double)1);
final Node fromNode6=node5;
final Node toNode6=node6;
NetworkUtils.createAndAddLink(network,Id.create("7",Link.class),fromNode6,toNode6,(double)100,(double)5,(double)100,(double)1);
final Node fromNode7=node6;
final Node toNode7=node7;
NetworkUtils.createAndAddLink(network,Id.create("8",Link.class),fromNode7,toNode7,(double)100,(double)5,(double)100,(double)1);
final Node fromNode8=node7;
final Node toNode8=node8;
NetworkUtils.createAndAddLink(network,Id.create("9",Link.class),fromNode8,toNode8,(double)100,(double)5,(double)100,(double)1);
final Node fromNode9=node8;
final Node toNode9=node9;
NetworkUtils.createAndAddLink(network,Id.create("10",Link.class),fromNode9,toNode9,(double)100,(double)5,(double)100,(double)1);
final Node fromNode10=node7;
final Node toNode10=node9;
NetworkUtils.createAndAddLink(network,Id.create("11",Link.class),fromNode10,toNode10,(double)100,(double)5,(double)100,(double)1);
final Node fromNode11=node9;
final Node toNode11=node10;
NetworkUtils.createAndAddLink(network,Id.create("12",Link.class),fromNode11,toNode11,(double)100,(double)5,(double)100,(double)1);
final Node fromNode12=node10;
final Node toNode12=node11;
NetworkUtils.createAndAddLink(network,Id.create("13",Link.class),fromNode12,toNode12,(double)100,(double)5,(double)100,(double)1);
}
| Creates a simple network with route alternatives in 2 places. |
@Override public void onStart(){
if (!didStartApp) {
didStartApp=true;
InstallOptions pendingInstall=this.codePushPackageManager.getPendingInstall();
if (pendingInstall == null) {
handleUnconfirmedInstall(false);
}
handleAppStart();
if (pendingInstall != null && (InstallMode.ON_NEXT_RESUME.equals(pendingInstall.installMode) || InstallMode.ON_NEXT_RESTART.equals(pendingInstall.installMode))) {
this.markUpdate();
this.codePushPackageManager.clearPendingInstall();
}
}
else {
InstallOptions pendingInstall=this.codePushPackageManager.getPendingInstall();
long durationInBackground=(new Date().getTime() - lastPausedTimeMs) / 1000;
if (pendingInstall != null && InstallMode.ON_NEXT_RESUME.equals(pendingInstall.installMode) && durationInBackground >= pendingInstall.minimumBackgroundDuration) {
handleAppStart();
this.markUpdate();
this.codePushPackageManager.clearPendingInstall();
}
}
}
| Called when the activity is becoming visible to the user. |
public static List<HostAddress> resolveXMPPServerDomain(String domain){
return resolveDomain(domain,'s');
}
| Returns a list of HostAddresses under which the specified XMPP server can be reached at for server-to-server communication. A DNS lookup for a SRV record in the form "_xmpp-server._tcp.example.com" is attempted, according to section 14.4 of RFC 3920. If that lookup fails, a lookup in the older form of "_jabber._tcp.example.com" is attempted since servers that implement an older version of the protocol may be listed using that notation. If that lookup fails as well, it's assumed that the XMPP server lives at the host resolved by a DNS lookup at the specified domain on the default port of 5269.<p> As an example, a lookup for "example.com" may return "im.example.com:5269". |
public void xtestTransactionRollbackOnSessionClose() throws Exception {
Destination destination=createDestination(getClass().getName());
Connection connection=createConnection();
connection.setClientID(idGen.generateId());
connection.start();
Session consumerSession=connection.createSession(true,Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer=null;
if (topic) {
consumer=consumerSession.createDurableSubscriber((Topic)destination,"TESTRED");
}
else {
consumer=consumerSession.createConsumer(destination);
}
Session producerSession=connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
MessageProducer producer=producerSession.createProducer(destination);
producer.setDeliveryMode(deliveryMode);
TextMessage sentMsg=producerSession.createTextMessage();
sentMsg.setText("msg1");
producer.send(sentMsg);
producerSession.commit();
Message recMsg=consumer.receive(RECEIVE_TIMEOUT);
assertFalse(recMsg.getJMSRedelivered());
consumerSession.close();
consumerSession=connection.createSession(true,Session.CLIENT_ACKNOWLEDGE);
consumer=consumerSession.createConsumer(destination);
recMsg=consumer.receive(RECEIVE_TIMEOUT);
consumerSession.commit();
assertTrue(recMsg.equals(sentMsg));
connection.close();
}
| Check a session is rollbacked on a Session close(); |
public SnmpNull(String dummy){
this();
}
| Constructs a new <CODE>SnmpNull</CODE>. <BR>For mibgen private use only. |
public SQLTransientException(String reason,String sqlState){
super(reason,sqlState,0);
}
| Creates an SQLTransientException object. The Reason string is set to the given reason string, the SQLState string is set to the given SQLState string and the Error Code is set to 0. |
public static void main(String[] args){
try {
PluginManager.loadPlugins();
if (args.length == 0) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch ( Exception e) {
}
new OpenStegoUI().setVisible(true);
}
else {
OpenStegoCmd.execute(args);
}
}
catch ( OpenStegoException osEx) {
if (osEx.getErrorCode() == OpenStegoException.UNHANDLED_EXCEPTION) {
osEx.printStackTrace();
}
else {
System.err.println(osEx.getMessage());
}
}
catch ( Exception ex) {
ex.printStackTrace();
}
}
| Main method for calling openstego from command line. |
public AmqpReceiver createDurableReceiver(String address,String subscriptionName) throws Exception {
return createDurableReceiver(address,subscriptionName,null,false);
}
| Create a receiver instance using the given address that creates a durable subscription. |
public static RuntimeException codeBug(String msg) throws RuntimeException {
msg="FAILED ASSERTION: " + msg;
RuntimeException ex=new IllegalStateException(msg);
ex.printStackTrace(System.err);
throw ex;
}
| Throws RuntimeException to indicate failed assertion. The function never returns and its return type is RuntimeException only to be able to write <tt>throw Kit.codeBug()</tt> if plain <tt>Kit.codeBug()</tt> triggers unreachable code error. |
@Override protected void register(DeployerFactory deployerFactory){
deployerFactory.registerDeployer("tomcat4x",DeployerType.INSTALLED,TomcatCopyingInstalledLocalDeployer.class);
deployerFactory.registerDeployer("tomcat4x",DeployerType.REMOTE,Tomcat4xRemoteDeployer.class);
deployerFactory.registerDeployer("tomcat5x",DeployerType.INSTALLED,TomcatCopyingInstalledLocalDeployer.class);
deployerFactory.registerDeployer("tomcat5x",DeployerType.REMOTE,Tomcat5xRemoteDeployer.class);
deployerFactory.registerDeployer("tomcat5x",DeployerType.EMBEDDED,TomcatEmbeddedLocalDeployer.class);
deployerFactory.registerDeployer("tomcat6x",DeployerType.INSTALLED,TomcatCopyingInstalledLocalDeployer.class);
deployerFactory.registerDeployer("tomcat6x",DeployerType.REMOTE,Tomcat6xRemoteDeployer.class);
deployerFactory.registerDeployer("tomcat6x",DeployerType.EMBEDDED,TomcatEmbeddedLocalDeployer.class);
deployerFactory.registerDeployer("tomcat7x",DeployerType.INSTALLED,TomcatCopyingInstalledLocalDeployer.class);
deployerFactory.registerDeployer("tomcat7x",DeployerType.REMOTE,Tomcat7xRemoteDeployer.class);
deployerFactory.registerDeployer("tomcat7x",DeployerType.EMBEDDED,TomcatEmbeddedLocalDeployer.class);
deployerFactory.registerDeployer("tomcat8x",DeployerType.INSTALLED,TomcatCopyingInstalledLocalDeployer.class);
deployerFactory.registerDeployer("tomcat8x",DeployerType.REMOTE,Tomcat8xRemoteDeployer.class);
deployerFactory.registerDeployer("tomcat8x",DeployerType.EMBEDDED,TomcatEmbeddedLocalDeployer.class);
deployerFactory.registerDeployer("tomcat9x",DeployerType.INSTALLED,TomcatCopyingInstalledLocalDeployer.class);
deployerFactory.registerDeployer("tomcat9x",DeployerType.REMOTE,Tomcat9xRemoteDeployer.class);
deployerFactory.registerDeployer("tomcat9x",DeployerType.EMBEDDED,TomcatEmbeddedLocalDeployer.class);
}
| Register deployer. |
protected void putInQueue(Object val) throws InterruptedException {
if (val instanceof HAEventWrapper && ((HAEventWrapper)val).getClientUpdateMessage() == null) {
if (logger.isDebugEnabled()) {
logger.debug("HARegionQueue.putGIIDataInRegion(): key={} was removed at sender side, so not putting it into the ha queue.",((HAEventWrapper)val).getKeyToConflate());
}
}
else {
this.put(val);
}
}
| Puts the GII'd entry into the ha region, if it was GII'd along with its ClientUpdateMessageImpl instance. |
protected EventException createEventException(short code,String key,Object[] args){
try {
AbstractDocument doc=(AbstractDocument)node.getOwnerDocument();
return new EventException(code,doc.formatMessage(key,args));
}
catch ( Exception e) {
return new EventException(code,key);
}
}
| Creates an EventException. Overrides this method if you need to create your own RangeException subclass. |
private void fetchKey(){
if (this.flowLevel == 0) {
if (!this.allowSimpleKey) {
throw new ScannerException(null,null,"mapping keys are not allowed here",reader.getMark());
}
if (addIndent(this.reader.getColumn())) {
Mark mark=reader.getMark();
this.tokens.add(new BlockMappingStartToken(mark,mark));
}
}
this.allowSimpleKey=this.flowLevel == 0;
removePossibleSimpleKey();
Mark startMark=reader.getMark();
reader.forward();
Mark endMark=reader.getMark();
Token token=new KeyToken(startMark,endMark);
this.tokens.add(token);
}
| Fetch a key in a block-style mapping. |
@Deprecated protected ActionListener createKeyboardEndListener(){
return new KeyboardEndHandler();
}
| As of Java 2 platform v1.3 this method is no longer used. Subclassers previously using this method should instead create an Action wrapping the ActionListener, and register that Action by overriding <code>installKeyboardActions</code> and placing the Action in the SplitPane's ActionMap. Please refer to the key bindings specification for further details. <p> Creates a ActionListener for the JSplitPane UI that listens for specific key presses. |
public FisheyeTreeFilter(String group){
this(group,1);
}
| Create a new FisheyeTreeFilter that processes the given group. |
public BufferedSageFile(SageFileSource sageFileSource,int readBufferSize,int writeBufferSize){
this.sageFileSource=sageFileSource;
realFilePosition=sageFileSource.position();
readonly=sageFileSource.isReadOnly();
readBuffer=new byte[readBufferSize];
readWrap=null;
if (readonly) {
writeBuffer=empty;
}
else {
if (writeBufferSize == 0) writeBufferSize=8192;
int remainder=writeBufferSize % 8192;
if (remainder != 0) writeBufferSize=writeBufferSize + 8192 - remainder;
writeOptimizerLimit=writeBufferSize / 2;
writeBuffer=new byte[writeBufferSize];
writeWrap=null;
}
}
| Create a buffered <code>SageFileSource</code> with custom read and write buffer sizes. <p/> Do not attempt to use the underlying <code>SageFileSource</code> after writing without first calling <code>flush()</code> since otherwise the state of writing will be unknown. |
public static boolean isVplexDistributedVolume(UnManagedVolume unManagedVolume){
if (isVplexVolume(unManagedVolume)) {
String locality=PropertySetterUtil.extractValueFromStringSet(SupportedVolumeInformation.VPLEX_LOCALITY.toString(),unManagedVolume.getVolumeInformation());
if (VPlexApiConstants.DISTRIBUTED_VIRTUAL_VOLUME.equalsIgnoreCase(locality)) {
return true;
}
}
return false;
}
| Returns true if the given UnManagedVolume is a VPLEX distributed volume. |
public static void registerMetadata(MetadataRegistry registry){
if (registry.isRegistered(KEY)) {
return;
}
registry.build(KEY);
}
| Registers the metadata for this element. |
private boolean filterStaticColumns(OneRowChange orc) throws ReplicatorException {
boolean transformed=false;
if (orc.getAction() != ActionType.UPDATE) return transformed;
if (tungstenSchema != null && orc.getSchemaName().compareToIgnoreCase(tungstenSchema) == 0) {
if (logger.isDebugEnabled()) logger.debug("Ignoring " + tungstenSchema + " schema");
return transformed;
}
ArrayList<ColumnSpec> keys=orc.getKeySpec();
ArrayList<ColumnSpec> columns=orc.getColumnSpec();
ArrayList<ArrayList<ColumnVal>> keyValues=orc.getKeyValues();
ArrayList<ArrayList<ColumnVal>> columnValues=orc.getColumnValues();
ArrayList<ColumnSpec> columnsToRemove=new ArrayList<ColumnSpec>();
if (columns.size() != keys.size() && logger.isDebugEnabled()) {
logger.debug("Column and key counts are different. Checking only columns matching present keys.");
}
for (int k=0; k < keys.size(); k++) {
ColumnSpec keySpec=keys.get(k);
boolean valueExists=false;
int valIndex;
ColumnSpec colSpec=null;
for (valIndex=0; valIndex < columns.size(); valIndex++) {
colSpec=columns.get(valIndex);
if (colSpec.getIndex() == keySpec.getIndex()) {
valueExists=true;
break;
}
}
if (!valueExists) continue;
boolean columnStatic=true;
for (int row=0; row < keyValues.size(); row++) {
ColumnVal keyValue=keyValues.get(row).get(k);
ColumnVal colValue=columnValues.get(row).get(valIndex);
if (!(keySpec.getType() == colSpec.getType() && keySpec.getIndex() == colSpec.getIndex() && ((keyValue.getValue() == null && colValue.getValue() == null) || (keyValue.getValue() != null && keyValue.getValue().equals(colValue.getValue()))))) {
columnStatic=false;
}
else {
logger.debug("Col " + colSpec.getIndex() + " @ Row "+ row+ " is static: "+ keyValue.getValue()+ " = "+ colValue.getValue());
}
}
if (columnStatic) columnsToRemove.add(colSpec);
}
if (columnsToRemove.size() == columns.size()) {
if (logger.isDebugEnabled()) logger.debug("All " + columnsToRemove.size() + " of "+ columns.size()+ " columns where static - leaving them as is to have a valid transaction");
return transformed;
}
for (Iterator<ColumnSpec> iterator=columnsToRemove.iterator(); iterator.hasNext(); ) {
ColumnSpec columnToRemoveSpec=iterator.next();
int idx=columns.indexOf(columnToRemoveSpec);
for (Iterator<ArrayList<ColumnVal>> iterator2=columnValues.iterator(); iterator2.hasNext(); ) {
ArrayList<ColumnVal> values=iterator2.next();
values.remove(idx);
}
columns.remove(idx);
logger.debug("Col " + columnToRemoveSpec.getIndex() + " removed");
transformed=true;
}
return transformed;
}
| Find out which columns' values didn't change by comparing them to the key values. Remove columns, that didn't change, from the UPDATE.<br/> NOTE: we depend on keys containing the same items as columns for this to work, which is generally true for MySQL binary log, if it is not filtered before (eg. with a PrimaryKeyFilter.java). |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.