code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public default void artifactPreAdd(final PreAddContext context) throws Exception {
}
| Process a request to add an artifact <p> In general it is possible to check an incoming (not stored yet) artifact and veto its creation. </p> |
public static Container encloseIn(Layout l,Component cmp,Object cons){
Container cnt=new Container(l);
if (cons instanceof Component) {
return cnt.add(cmp).add((Component)cons);
}
if (cons != null) {
cnt.addComponent(cons,cmp);
}
else {
cnt.addComponent(cmp);
}
return cnt;
}
| Short-hand for enclosing a component within a Container |
public void resetTask(){
this.theOwner=null;
this.petPathfinder.clearPathEntity();
}
| Resets the task |
public double[] computeLocalJointEntropyOfPreviousObservations() throws Exception {
return computeLocalJointEntropyUsingPreviousObservations(sourceObservations,destObservations,true);
}
| Compute the local joint entropy values of the previously provided observations. |
private void fillComboReport(int AD_PrintFormat_ID){
comboReport.removeActionListener(this);
comboReport.removeAllItems();
KeyNamePair selectValue=null;
String sql=MRole.getDefault().addAccessSQL("SELECT AD_PrintFormat_ID, Name, Description " + "FROM AD_PrintFormat " + "WHERE AD_Table_ID=? "+ "AND IsActive='Y' "+ "ORDER BY Name","AD_PrintFormat",MRole.SQL_NOTQUALIFIED,MRole.SQL_RO);
int AD_Table_ID=m_reportEngine.getPrintFormat().getAD_Table_ID();
try {
PreparedStatement pstmt=DB.prepareStatement(sql,null);
pstmt.setInt(1,AD_Table_ID);
ResultSet rs=pstmt.executeQuery();
while (rs.next()) {
KeyNamePair pp=new KeyNamePair(rs.getInt(1),rs.getString(2));
comboReport.addItem(pp);
if (rs.getInt(1) == AD_PrintFormat_ID) selectValue=pp;
}
rs.close();
pstmt.close();
}
catch ( SQLException e) {
log.log(Level.SEVERE,sql,e);
}
StringBuffer sb=new StringBuffer("** ").append(Msg.getMsg(m_ctx,"NewReport")).append(" **");
KeyNamePair pp=new KeyNamePair(-1,sb.toString());
comboReport.addItem(pp);
sb=new StringBuffer("** ").append(Msg.getMsg(m_ctx,"CopyReport")).append(" **");
pp=new KeyNamePair(-2,sb.toString());
comboReport.addItem(pp);
if (selectValue != null) comboReport.setSelectedItem(selectValue);
comboReport.addActionListener(this);
}
| Fill ComboBox comboReport (report options) |
public static CodeArray createStub(int[] sigIds,RVMMethod[] targets){
int numEntries=sigIds.length;
Assembler asm=new Assembler(numEntries);
if (VM.VerifyAssertions) {
for (int i=1; i < sigIds.length; i++) {
VM._assert(sigIds[i - 1] < sigIds[i]);
}
}
int[] bcIndices=new int[numEntries];
assignBytecodeIndices(0,bcIndices,0,numEntries - 1);
insertStubPrologue(asm);
insertStubCase(asm,sigIds,targets,bcIndices,0,numEntries - 1);
CodeArray stub=asm.getMachineCodes();
if (VM.runningVM) Memory.sync(Magic.objectAsAddress(stub),stub.length() << LG_INSTRUCTION_WIDTH);
return stub;
}
| Create a conflict resolution stub for the set of interface method signatures l. |
public NodeSorter(XPathContext p){
m_execContext=p;
}
| Construct a NodeSorter, passing in the XSL TransformerFactory so it can know how to get the node data according to the proper whitespace rules. |
public static String[] readStrings(String filename){
return new In(filename).readAllStrings();
}
| Reads all strings from a file |
@Override public String toString(){
StringBuilder sb=new StringBuilder();
sb.append('[');
sb.append("checksum=0x");
sb.append(Long.toHexString(checksum));
sb.append(']');
return sb.toString();
}
| Returns text |
public CopySubgraphAction(GraphEditable graphEditor){
super("Copy Selected Graph");
if (graphEditor == null) {
throw new NullPointerException("Desktop must not be null.");
}
this.graphEditor=graphEditor;
}
| Creates a new copy subsession action for the given desktop and clipboard. |
public boolean addToActiveList(DownloadInfoRunnable downloadInfoRunnable){
return activeListHasRoom() && mActiveList.add(downloadInfoRunnable);
}
| Tries to add a download object to the active list. Will not work if the max number of downloads is already reached. |
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. |
public boolean equals(Object o){
if (o == null) return false;
if (this == o) return true;
if (!(o instanceof NTSid)) return false;
NTSid that=(NTSid)o;
if (sid.equals(that.sid)) {
return true;
}
return false;
}
| Compares the specified Object with this <code>NTSid</code> for equality. Returns true if the given object is also a <code>NTSid</code> and the two NTSids have the same String representation. <p> |
public void add(SchemaObject obj){
if (SysProperties.CHECK && obj.getSchema() != this) {
DbException.throwInternalError("wrong schema");
}
String name=obj.getName();
Map<String,SchemaObject> map=getMap(obj.getType());
if (SysProperties.CHECK && map.get(name) != null) {
DbException.throwInternalError("object already exists: " + name);
}
map.put(name,obj);
freeUniqueName(name);
}
| Add an object to this schema. This method must not be called within CreateSchemaObject; use Database.addSchemaObject() instead |
public MemoryIndex(boolean storeOffsets,boolean storePayloads){
this(storeOffsets,storePayloads,0);
}
| Constructs an empty instance with the option of storing offsets and payloads. |
void delete(int index){
if (num == 0 || index >= num) {
return;
}
while (++index < num) {
if (index - 1 >= 0) {
minRange[index - 1]=minRange[index];
maxRange[index - 1]=maxRange[index];
}
}
num--;
}
| Deletes the range at a given index from the range lists |
private void updateSelection(Mode mode,SVGPoint p1,SVGPoint p2){
DBIDSelection selContext=context.getSelection();
final HashSetModifiableDBIDs selection;
if (selContext == null || mode == Mode.REPLACE) {
selection=DBIDUtil.newHashSet();
}
else {
selection=DBIDUtil.newHashSet(selContext.getSelectedIds());
}
int[] axisrange=getAxisRange(Math.min(p1.getX(),p2.getX()),Math.max(p1.getX(),p2.getX()));
DBIDs ids=ResultUtil.getSamplingResult(relation).getSample();
for (DBIDIter iter=ids.iter(); iter.valid(); iter.advance()) {
double[] yPos=proj.fastProjectDataToRenderSpace(relation.get(iter));
if (checkSelected(axisrange,yPos,Math.max(p1.getX(),p2.getX()),Math.min(p1.getX(),p2.getX()),Math.max(p1.getY(),p2.getY()),Math.min(p1.getY(),p2.getY()))) {
if (mode == Mode.INVERT) {
if (!selection.contains(iter)) {
selection.add(iter);
}
else {
selection.remove(iter);
}
}
else {
selection.add(iter);
}
}
}
context.setSelection(new DBIDSelection(selection));
}
| Updates the selection in the context.<br> |
public T caseLogicalAndExpression(LogicalAndExpression object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Logical And Expression</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
protected void init(int rows,int cols){
rowData.clear();
for (int i=0; i < rows; i++) {
rowData.add(createNewRow(" ",cols));
}
fireTableStructureChanged();
}
| Initialize the table. |
@Override public void runSingleIteration(){
for ( long rightNode : salsaInternalState.getCurrentRightNodes().keySet()) {
int numWalks=salsaInternalState.getCurrentRightNodes().get(rightNode);
EdgeIterator sampledLeftNodes=salsaInternalState.getBipartiteGraph().getRandomRightNodeEdges(rightNode,numWalks,random);
if (sampledLeftNodes != null) {
while (sampledLeftNodes.hasNext()) {
salsaInternalState.addNodeToCurrentLeftNodes(sampledLeftNodes.nextLong());
}
}
}
salsaInternalState.clearCurrentRightNodes();
}
| Runs a single right-to-left SALSA iteration. |
public static Matrix parseMatlab(String matlab) throws Exception {
return new Matrix(weka.core.matrix.Matrix.parseMatlab(matlab).getArray());
}
| creates a matrix from the given Matlab string. |
public static void handleCommandLineArgs(final String[] args,final String[] availableProperties,GameMode gameMode){
if (args.length == 1 && !args[0].contains("=")) {
args[0]=GameRunner.TRIPLEA_GAME_PROPERTY + "=" + args[0];
}
boolean usagePrinted=false;
for ( final String arg : args) {
String key;
final int indexOf=arg.indexOf('=');
if (indexOf > 0) {
key=arg.substring(0,indexOf);
}
else {
throw new IllegalArgumentException("Argument " + arg + " doesn't match pattern 'key=value'");
}
if (!setSystemProperty(key,getValue(arg),availableProperties)) {
System.out.println("Unrecogized:" + arg);
if (!usagePrinted) {
usagePrinted=true;
usage(gameMode);
}
}
}
if (gameMode == GameMode.HEADLESS_BOT) {
System.getProperties().setProperty(TRIPLEA_HEADLESS,"true");
boolean printUsage=false;
final String playerName=System.getProperty(GameRunner.TRIPLEA_NAME_PROPERTY,"");
final String hostName=System.getProperty(GameRunner.LOBBY_GAME_HOSTED_BY,"");
if (playerName.length() < 7 || hostName.length() < 7 || !hostName.equals(playerName) || !playerName.startsWith("Bot") || !hostName.startsWith("Bot")) {
System.out.println("Invalid argument: " + GameRunner.TRIPLEA_NAME_PROPERTY + " and "+ GameRunner.LOBBY_GAME_HOSTED_BY+ " must start with \"Bot\" and be at least 7 characters long and be the same.");
printUsage=true;
}
final String comments=System.getProperty(GameRunner.LOBBY_GAME_COMMENTS,"");
if (!comments.contains("automated_host")) {
System.out.println("Invalid argument: " + GameRunner.LOBBY_GAME_COMMENTS + " must contain the string \"automated_host\".");
printUsage=true;
}
final String email=System.getProperty(GameRunner.LOBBY_GAME_SUPPORT_EMAIL,"");
if (email.length() < 3 || !Util.isMailValid(email)) {
System.out.println("Invalid argument: " + GameRunner.LOBBY_GAME_SUPPORT_EMAIL + " must contain a valid email address.");
printUsage=true;
}
final String reconnection=System.getProperty(GameRunner.LOBBY_GAME_RECONNECTION,"" + LOBBY_RECONNECTION_REFRESH_SECONDS_DEFAULT);
try {
final int reconnect=Integer.parseInt(reconnection);
if (reconnect < LOBBY_RECONNECTION_REFRESH_SECONDS_MINIMUM) {
System.out.println("Invalid argument: " + GameRunner.LOBBY_GAME_RECONNECTION + " must be an integer equal to or greater than "+ LOBBY_RECONNECTION_REFRESH_SECONDS_MINIMUM+ " seconds, and should normally be either "+ LOBBY_RECONNECTION_REFRESH_SECONDS_DEFAULT+ " or "+ (2 * LOBBY_RECONNECTION_REFRESH_SECONDS_DEFAULT)+ " seconds.");
printUsage=true;
}
}
catch ( final NumberFormatException e) {
System.out.println("Invalid argument: " + GameRunner.LOBBY_GAME_RECONNECTION + " must be an integer equal to or greater than "+ LOBBY_RECONNECTION_REFRESH_SECONDS_MINIMUM+ " seconds, and should normally be either "+ LOBBY_RECONNECTION_REFRESH_SECONDS_DEFAULT+ " or "+ (2 * LOBBY_RECONNECTION_REFRESH_SECONDS_DEFAULT)+ " seconds.");
printUsage=true;
}
final String clientWait=System.getProperty(GameRunner.TRIPLEA_SERVER_START_GAME_SYNC_WAIT_TIME,"");
final String observerWait=System.getProperty(GameRunner.TRIPLEA_SERVER_OBSERVER_JOIN_WAIT_TIME,"");
if (clientWait.length() > 0) {
try {
final int wait=Integer.parseInt(clientWait);
GameRunner.setServerStartGameSyncWaitTime(wait);
}
catch ( final NumberFormatException e) {
System.out.println("Invalid argument: " + GameRunner.TRIPLEA_SERVER_START_GAME_SYNC_WAIT_TIME + " must be an integer.");
printUsage=true;
}
}
if (observerWait.length() > 0) {
try {
final int wait=Integer.parseInt(observerWait);
GameRunner.setServerObserverJoinWaitTime(wait);
}
catch ( final NumberFormatException e) {
System.out.println("Invalid argument: " + GameRunner.TRIPLEA_SERVER_START_GAME_SYNC_WAIT_TIME + " must be an integer.");
printUsage=true;
}
}
if (printUsage || usagePrinted) {
usage(gameMode);
System.exit(-1);
}
}
else {
final String version=System.getProperty(TRIPLEA_ENGINE_VERSION_BIN);
if (version != null && version.length() > 0) {
final Version testVersion;
try {
testVersion=new Version(version);
System.out.println(TRIPLEA_ENGINE_VERSION_BIN + ":" + version);
if (!ClientContext.engineVersion().getVersion().equals(testVersion,false)) {
System.out.println("Current Engine version in use: " + ClientContext.engineVersion());
}
}
catch ( final Exception e) {
System.getProperties().setProperty(TRIPLEA_ENGINE_VERSION_BIN,ClientContext.engineVersion().toString());
System.out.println(TRIPLEA_ENGINE_VERSION_BIN + ":" + ClientContext.engineVersion());
}
}
else {
System.getProperties().setProperty(TRIPLEA_ENGINE_VERSION_BIN,ClientContext.engineVersion().toString());
System.out.println(TRIPLEA_ENGINE_VERSION_BIN + ":" + ClientContext.engineVersion());
}
}
}
| Move command line arguments to System.properties |
@Deprecated public void expungeNotebook(String guid,OnClientCallback<Integer> callback){
AsyncReflector.execute(mClient,callback,"expungeNotebook",mAuthenticationToken,guid);
}
| Asynchronous wrapper. |
protected Object deserialize(byte[] payload,Schema readerSchema) throws SerializationException {
return deserialize(false,null,null,payload,readerSchema);
}
| Just like single-parameter version but accepts an Avro schema to use for reading |
public PTQuery parse(String queryName,String queryString) throws PTQueryParserException, PTQueryException {
return new Parser(this).parse(queryName,queryString);
}
| Parses and adds a query |
public String peekElement(){
return peekElement(0);
}
| Get the last path element from the stack. |
public String checkWriteProtected(int resIdAction,final File... filesToBeModified){
if (filesToBeModified != null) {
for ( File file : filesToBeModified) {
if ((file != null) && (file.exists()) && (!file.canWrite())) {
String action=(resIdAction == 0) ? "" : mContext.getString(resIdAction);
return mContext.getString(R.string.file_err_writeprotected,file.getAbsolutePath(),action);
}
}
}
return null;
}
| Check if all files in selectedFileNamesToBeModified are not write protected. |
public IntegerConstant(ConstantPool pool,int index,int value){
super(pool,index);
_value=value;
}
| Creates a new integer constant. |
public static String generateRandomName(String prefix){
StringBuilder sb=new StringBuilder();
Random random=new Random();
sb.append(prefix);
for (int i=0; i < 5; i++) {
sb.append('a' + random.nextInt(26));
}
return sb.toString();
}
| Generate a random name with the specified prefix. |
public boolean isEvenInvoiceWeek(){
Object oo=get_Value(COLUMNNAME_EvenInvoiceWeek);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Invoice on even weeks. |
public void deOp(UserHostmask user){
if (user == null) throw new IllegalArgumentException("Can't remove op on null user");
setMode("-o " + user.getNick());
}
| Removes operator privileges from a user on a channel. Successful use of this method may require the bot to have operator status itself. |
public static String[] makeBucketLabels(int numBuckets,double min,double max,boolean logScale){
String[] s=new String[numBuckets];
if (min > max) {
double tmp=min;
min=max;
max=tmp;
}
if (min == max) {
s[0]="[" + min + "..."+ max+ "]";
for (int x=1; x < s.length; x++) s[x]="";
return s;
}
else if (logScale) {
min=Math.log(min);
max=Math.log(max);
for (int x=0; x < s.length; x++) s[x]="[" + Math.exp((x / (double)numBuckets) * (max - min) + min) + "..."+ Math.exp(((x + 1) / (double)numBuckets) * (max - min) + min)+ (x == s.length - 1 ? "]" : ")");
}
else for (int x=0; x < s.length; x++) s[x]="[" + ((x / (double)numBuckets) * (max - min) + min) + "..."+ (((x + 1) / (double)numBuckets) * (max - min) + min)+ (x == s.length - 1 ? "]" : ")");
return s;
}
| Generates a set of <i>numBuckets</i> bucket labels appropriate for use in a histogram. The values <i>numBuckets</i>, <i>min</i>, and <i>max</i> should be the same values you had provided to makeBuckets(...). Pass the resulting array into the setBuckets(...) function. |
@DSComment("Private Method") @DSBan(DSCat.PRIVATE_METHOD) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:46.634 -0500",hash_original_method="D3DDD15A13BA6EC1D9CD48C2CCCFE0B4",hash_generated_method="BDAD5B72FB8DC237D351054ED50949FF") private Event(){
}
| This utility class cannot be instantiated |
public void putDouble(String key,double value){
putString(key,String.valueOf(value));
}
| Put double value into SharedPreferences with 'key' and save |
@DSComment("OS Bundle data structure") @DSSafe(DSCat.DATA_STRUCTURE) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:36.476 -0500",hash_original_method="23A8E01E039C76712F2C134222EAC45B",hash_generated_method="EA68455D0713862A2AE3E437A935F177") public void putCharSequence(String key,CharSequence value){
unparcel();
mMap.put(key,value);
}
| Inserts a CharSequence value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. |
public Memory(final com.google.security.zynamics.zylib.general.memmanager.Memory memory){
m_memory=memory;
memory.addMemoryListener(m_listener);
}
| Creates a new memory object |
public LinkedIdentityHashMap(int initialCapacity,float loadFactor){
super(initialCapacity,loadFactor);
accessOrder=false;
}
| Constructs an empty insertion-ordered <tt>LinkedIdentityHashMap</tt> instance with the specified initial capacity and load factor. |
private void addMitreJoin(Coordinate p,LineSegment offset0,LineSegment offset1,double distance){
boolean isMitreWithinLimit=true;
Coordinate intPt=null;
try {
intPt=HCoordinate.intersection(offset0.p0,offset0.p1,offset1.p0,offset1.p1);
double mitreRatio=distance <= 0.0 ? 1.0 : intPt.distance(p) / Math.abs(distance);
if (mitreRatio > bufParams.getMitreLimit()) isMitreWithinLimit=false;
}
catch ( NotRepresentableException ex) {
intPt=new Coordinate(0,0);
isMitreWithinLimit=false;
}
if (isMitreWithinLimit) {
segList.addPt(intPt);
}
else {
addLimitedMitreJoin(offset0,offset1,distance,bufParams.getMitreLimit());
}
}
| Adds a mitre join connecting the two reflex offset segments. The mitre will be beveled if it exceeds the mitre ratio limit. |
public void drawResultBitmap(Bitmap barcode){
resultBitmap=barcode;
invalidate();
}
| Draw a bitmap with the result points highlighted instead of the live scanning display. |
synchronized protected void timeout(){
Runnable r=null;
javax.swing.SwingUtilities.invokeLater(r);
}
| Internal routine to handle a timeout |
protected void initializeAllLiveAttributes(){
super.initializeAllLiveAttributes();
initializeLiveAttributes();
}
| Initializes all live attributes for this element. |
protected void onSingleClick(){
stackTrace.setText("");
final ISelection selection=testTreeViewer.getSelection();
if (selection.isEmpty()) {
return;
}
if (selection instanceof IStructuredSelection) {
final Object element=((IStructuredSelection)selection).getFirstElement();
if (element instanceof ResultNode) {
final ResultNode resultNode=(ResultNode)element;
final TestElement testElement=resultNode.getElement();
if (testElement instanceof TestCase) {
final TestCase testCase=(TestCase)testElement;
final TestResult result=testCase.getResult();
if (result != null) {
if (result.getTrace() != null && !result.getTrace().isEmpty()) {
final List<String> trace=newArrayList(result.getTrace());
final String firstLine=trace.get(0);
if ("Error".equals(firstLine) && !isNullOrEmpty(result.getMessage())) {
trace.set(0,result.getMessage());
}
final StringBuilder sb=new StringBuilder();
trace.forEach(null);
stackTrace.setText(sb.toString());
stackTrace.setSelection(0);
}
else if ((SKIPPED_IGNORE.equals(result.getTestStatus()) || SKIPPED_FIXME.equals(result.getTestStatus())) && !isNullOrEmpty(result.getMessage())) {
stackTrace.setText(result.getMessage());
stackTrace.setSelection(0);
}
}
}
}
}
}
| Invoked when user double-clicks a result node in the UI. On invocation clears stack trace text are. If selection is a test case with stack trace, trace is shown in the trace area. |
public RecordsMatcher<T> atLeastNOfThem(int n){
return new RecordsMatcher<>(MatcherCombiner.atLeast(matchers,n));
}
| Expect the record to fulfill at least a number of the specified asserts. |
private static int upperIndex(int ch){
int index=-1;
if (ch >= 0xdf) {
if (ch <= 0x587) {
switch (ch) {
case 0xdf:
return 0;
case 0x149:
return 1;
case 0x1f0:
return 2;
case 0x390:
return 3;
case 0x3b0:
return 4;
case 0x587:
return 5;
}
}
else if (ch >= 0x1e96) {
if (ch <= 0x1e9a) {
index=6 + ch - 0x1e96;
}
else if (ch >= 0x1f50 && ch <= 0x1ffc) {
index=upperValues2[ch - 0x1f50];
if (index == 0) {
index=-1;
}
}
else if (ch >= 0xfb00) {
if (ch <= 0xfb06) {
index=90 + ch - 0xfb00;
}
else if (ch >= 0xfb13 && ch <= 0xfb17) {
index=97 + ch - 0xfb13;
}
}
}
}
return index;
}
| Return the index of the specified character into the upperValues table. The upperValues table contains three entries at each position. These three characters are the upper case conversion. If only two characters are used, the third character in the table is \u0000. |
public static String toStringAccessValue(short accessValue) throws SecurityException {
switch (accessValue) {
case VALUE_NONE:
return "none";
case VALUE_YES:
return "yes";
case VALUE_LOCAL:
return "local";
case VALUE_1:
return "1";
case VALUE_2:
return "2";
case VALUE_3:
return "3";
case VALUE_4:
return "4";
case VALUE_5:
return "5";
case VALUE_6:
return "6";
case VALUE_7:
return "7";
case VALUE_8:
return "8";
case VALUE_9:
return "9";
case VALUE_10:
return "10";
}
throw new SecurityException("invalid access value","valid access values are [all,local,no,none,yes,1,...,10]");
}
| translate a short access value (all,local,none,no,yes) to String type |
private void performCalibrationCheckin(){
PowerManager pm=(PowerManager)getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl=pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"NSDownload");
wl.acquire();
try {
Log.i("CALIBRATION-CHECK-IN: ","Wake Lock Acquired");
if (acquireSerialDevice()) {
try {
ReadData readData=new ReadData(mSerialDevice,mConnection,dexcom);
CalRecord[] calRecords=readData.getRecentCalRecords();
Log.i("CALIBRATION-CHECK-IN: ","Found " + calRecords.length + " Records!");
save_most_recent_cal_record(calRecords);
}
catch ( Exception e) {
Log.wtf("Unhandled exception caught",e);
}
finally {
try {
mSerialDevice.getPorts().get(0).close();
}
catch ( IOException e) {
Log.e(TAG,"Unable to close",e);
}
}
}
else {
Log.w("CALIBRATION-CHECK-IN: ","Failed to acquire serial device");
}
}
finally {
wl.release();
}
}
| Handle action Sync in the provided background thread with the provided parameters. |
void open() throws ReplicatorException, InterruptedException {
try {
if (getFileName() == null) {
throw new MySQLExtractException("No binlog file specified");
}
if (bfdi != null) {
throw new MySQLExtractException("Attempt to open binlog twice: " + this.fileName);
}
File file=new File(getDirectory() + File.separator + getFileName());
int tryCnt=0;
while (file.exists() == false && tryCnt++ < 500) {
Thread.sleep(10);
}
if (logger.isDebugEnabled()) logger.debug("Opening file " + file.getName() + " with buffer = "+ bufferSize);
bfdi=new BufferedFileDataInput(file,bufferSize);
byte magic[]=new byte[MysqlBinlog.BIN_LOG_HEADER_SIZE];
try {
waitAvailable(magic.length,binlogFlushDelayMillis);
if (available() < magic.length) {
throw new MySQLExtractException("Failed reading header; Probably an empty file or very slow file system: " + getBaseName());
}
read(magic);
if (!Arrays.equals(magic,MysqlBinlog.BINLOG_MAGIC)) {
throw new MySQLExtractException("File is not a binary log file - found : " + LogEvent.hexdump(magic) + " / expected : "+ LogEvent.hexdump(MysqlBinlog.BINLOG_MAGIC));
}
}
catch ( IOException e) {
throw new MySQLExtractException("Failed reading binlog file header: " + getBaseName(),e);
}
mark(2048);
byte[] header=new byte[MysqlBinlog.PROBE_HEADER_LEN];
waitAvailable(header.length,binlogFlushDelayMillis);
if (available() < header.length) {
throw new MySQLExtractException("Failed reading header; You may have an incomplete log file or a very slow file system: " + getBaseName());
}
bfdi.readFully(header);
int typeCode=header[4];
int eventLength=(int)LittleEndianConversion.convert4BytesToLong(header,MysqlBinlog.EVENT_LEN_OFFSET);
if (typeCode == MysqlBinlog.START_EVENT_V3) {
if (eventLength == 69) {
version=MysqlBinlog.BINLOG_V1;
if (logger.isDebugEnabled()) logger.debug("Binlog format is V1");
}
else if (eventLength == 75) {
version=MysqlBinlog.BINLOG_V3;
if (logger.isDebugEnabled()) logger.debug("Binlog format is V3");
}
else {
throw new MySQLExtractException("Unexpected start event length: file=" + this.fileName + " length="+ eventLength);
}
}
else if (typeCode == MysqlBinlog.FORMAT_DESCRIPTION_EVENT) {
version=MysqlBinlog.BINLOG_V4;
if (logger.isDebugEnabled()) logger.debug("Binlog format is V4");
}
else if (typeCode == MysqlBinlog.ROTATE_EVENT) {
version=MysqlBinlog.BINLOG_V3;
if (logger.isDebugEnabled()) logger.debug("Binlog format is V3 (special case w/ rotate event)");
}
else {
throw new MySQLExtractException("Unexpected start event type code: file=" + this.fileName + " type code="+ typeCode);
}
if (startPosition >= bfdi.getOffset()) {
bfdi.seek(startPosition);
}
else {
bfdi.reset();
}
}
catch ( FileNotFoundException e) {
throw new MySQLExtractException("Unable to open binlog file",e);
}
catch ( IOException e) {
throw new MySQLExtractException("Unable to scan binlog file",e);
}
}
| Opens up the binlog file, validates the magic number, and checks the header for the binlog version. If this call succeeds the binlog is ready for reading. |
public static FlightStick logitechExtreme3D(int port){
Joystick joystick=new Joystick(port);
return FlightStick.create(null,null,null,null,null,null,null,null,null);
}
| Create a Logitech Extreme 3D flight stick controlled by the Driver Station. |
boolean run(File baseDir,String... args){
if (args.length == 0) {
usage(System.out);
return true;
}
List<File> files=new ArrayList<File>();
for (int i=0; i < args.length; i++) {
String arg=args[i];
if (arg.equals("-encoding") && i + 1 < args.length) encoding=args[++i];
else if (arg.equals("-gui")) gui=true;
else if (arg.equals("-q")) quiet=true;
else if (arg.equals("-v")) verbose=true;
else if (arg.equals("-t") && i + 1 < args.length) tags.add(args[++i]);
else if (arg.equals("-ef") && i + 1 < args.length) excludeFiles.add(new File(baseDir,args[++i]));
else if (arg.equals("-et") && i + 1 < args.length) excludeTags.add(args[++i]);
else if (arg.equals("-r")) {
if (excludeFiles.size() > 0) throw new Error("-r must be used before -ef");
File d=baseDir;
while (!new File(d,"TEST.ROOT").exists()) {
d=d.getParentFile();
if (d == null) throw new Error("cannot find TEST.ROOT");
}
baseDir=d;
}
else if (arg.startsWith("-")) throw new Error("unknown option: " + arg);
else {
while (i < args.length) files.add(new File(baseDir,args[i++]));
}
}
for ( File file : files) {
if (file.exists()) test(file);
else error("File not found: " + file);
}
if (fileCount != 1) System.err.println(fileCount + " files read");
if (errors > 0) System.err.println(errors + " errors");
return (gui || errors == 0);
}
| Run the program. A base directory can be provided for file arguments. In jtreg mode, the -r option can be given to change the default base directory to the test root directory. For other options, see usage(). |
public static Value SelectInSeq(Value s,Value test){
TupleValue seq=TupleValue.convert(s);
if (seq == null) {
throw new EvalException(EC.TLC_MODULE_ARGUMENT_ERROR,new String[]{"first","SelectInSeq","sequence",Value.ppr(s.toString())});
}
if (!(test instanceof Applicable)) {
throw new EvalException(EC.TLC_MODULE_ARGUMENT_ERROR,new String[]{"second","SelectInSeq","function",Value.ppr(test.toString())});
}
int len=seq.size();
Applicable ftest=(Applicable)test;
Value[] args=new Value[1];
for (int i=0; i < len; i++) {
args[0]=seq.elems[i];
Value val=ftest.apply(args,EvalControl.Clear);
if (!(val instanceof BoolValue)) {
throw new EvalException(EC.TLC_MODULE_ARGUMENT_ERROR,new String[]{"second","SelectInSeq","boolean-valued function",Value.ppr(test.toString())});
}
if (((BoolValue)val).val) return IntValue.gen(i + 1);
}
return ValZero;
}
| Returns the index (starting from 1) of the first element to match. If no match, return 0. |
private GCActivitySet gcActivitySet(int series){
assert 0 <= series && series < checkpoint.gcTraceSize();
return gcTrace.get(series);
}
| It returns the GC activity set for a given series (e.g., the index of the GC activity set within the current GC trace). |
public void goToNextColor(){
mColorIndex=(mColorIndex + 1) % (mColors.length);
}
| Proceed to the next available ring color. This will automatically wrap back to the beginning of colors. |
public void mouseEntered(MouseEvent evt){
}
| Method mouseEntered. |
public FixedParentMemorySubjectData(PermissionService service,Subject parent){
super(service);
this.forcedParent=parent;
}
| Creates a new subject data instance, using the provided service to request instances of permission subjects. |
public static BigInteger[] transformRawSignature(byte[] raw) throws IOException {
BigInteger[] output=new BigInteger[2];
output[0]=new BigInteger(1,Arrays.copyOfRange(raw,0,32));
output[1]=new BigInteger(1,Arrays.copyOfRange(raw,32,64));
return output;
}
| From byte[] to Big Integers r,s UAF_ALG_SIGN_SECP256K1_ECDSA_SHA256_RAW 0x05 An ECDSA signature on the secp256k1 curve which must have raw R and S buffers, encoded in big-endian order. I.e.[R (32 bytes), S (32 bytes)] |
public final static void debug(String s){
if (DEBUG) debug.println("// Debug: " + s);
}
| Print a debug message on debug stream associated with this interpreter only if debugging is turned on. |
public void addNewFeatureTree(FeaturesObjectTypesEnum type,FeatureTreeNode root){
FeaturesStructure list=this.collection.get(type);
if (list == null) {
list=new FeaturesStructure();
this.collection.put(type,list);
}
if (list.list == null) {
list.list=new ArrayList<>();
}
list.list.add(root);
}
| Add new feature tree for a type |
public DecoderPro3Window(){
super(Application.getApplicationName());
}
| Loads Decoder Pro 3 with the default set of menus and toolbars |
long trueDataSize(){
if (!isValidHeader()) {
return 0L;
}
int naxis=getIntValue(NAXIS,0);
if (naxis == 0) {
return 0L;
}
getIntValue(BITPIX);
int[] axes=new int[naxis];
for (int axis=1; axis <= naxis; axis+=1) {
axes[axis - 1]=getIntValue(NAXISn.n(axis),0);
}
boolean isGroup=getBooleanValue(GROUPS,false);
int pcount=getIntValue(PCOUNT,0);
int gcount=getIntValue(GCOUNT,1);
int startAxis=0;
if (isGroup && naxis > 1 && axes[0] == 0) {
startAxis=1;
}
long size=1;
for (int i=startAxis; i < naxis; i+=1) {
size*=axes[i];
}
size+=pcount;
size*=gcount;
size*=Math.abs(getIntValue(BITPIX,0)) / FitsIO.BITS_OF_1_BYTE;
return size;
}
| Calculate the unpadded size of the data segment from the header information. |
public Object evaluate(File file) throws CompilationFailedException, IOException {
return evaluate(new GroovyCodeSource(file,config.getSourceEncoding()));
}
| Evaluates some script against the current Binding and returns the result |
public boolean remove(final String label){
if ((label == null) || (label.equals(""))) {
logger.debug("will not remove transitions with empty label");
return false;
}
boolean res=false;
Iterator<Transition> itr=stateTransitionTable.iterator();
while (itr.hasNext()) {
Transition transition=itr.next();
if (transition.checkLabel(label)) {
itr.remove();
res=true;
}
}
return res;
}
| remove matches transition |
public FloatMatrix(int newRows,int newColumns){
this(newRows,newColumns,new float[newRows * newColumns]);
}
| Creates a new <i>n</i> times <i>m</i> <tt>FloatMatrix</tt>. |
public void printAttlistEnd(char[] space) throws IOException {
if (space != null) {
printSpaces(space,false);
}
writer.write('>');
}
| Prints an attribute list declaration end. |
protected void buildSuccessful(Notification notification,String successMessage,String prefixConsole){
notification.setMessage(successMessage);
notification.setStatus(FINISHED);
console.print(prefixConsole + "::" + successMessage);
}
| A build has been successful, change notification message. |
void nativeObject(Tree.NamedArgumentList argList){
final List<Tree.NamedArgument> nargs=argList.getNamedArguments();
if (argList.getSequencedArgument() == null) {
ArrayList<Tree.NamedArgument> getters=null;
for ( Tree.NamedArgument arg : nargs) {
if (arg instanceof Tree.AttributeArgument) {
if (getters == null) {
getters=new ArrayList<>(nargs.size());
}
getters.add(arg);
}
}
final String tmpobjvar=getters == null ? null : gen.createRetainedTempVar();
if (getters != null) {
gen.out("(",tmpobjvar,"=");
}
gen.out("{");
boolean first=true;
for ( Tree.NamedArgument arg : nargs) {
if (arg instanceof Tree.AttributeArgument == false) {
if (first) {
first=false;
}
else {
gen.out(",");
}
String argName=arg.getIdentifier().getText();
if (JsIdentifierNames.isReservedWord(argName)) {
gen.out("$_");
}
gen.out(argName,":");
arg.visit(gen);
}
}
gen.out("}");
if (getters != null) {
for ( Tree.NamedArgument arg : getters) {
if (first) {
first=false;
}
else {
gen.out(",");
}
gen.out("Object.defineProperty(",tmpobjvar,",'");
if (arg instanceof Tree.AttributeArgument) {
String argName=arg.getIdentifier().getText();
if (JsIdentifierNames.isReservedWord(argName)) {
gen.out("$_");
}
gen.out(argName,"',{get:function(){ return ");
gen.visitSingleExpression(((Tree.AttributeArgument)arg).getSpecifierExpression().getExpression());
gen.out("},configurable:true,enumerable:true})");
}
}
gen.out(",",tmpobjvar,")");
}
}
else {
String arr=null;
boolean isComp=false;
boolean isSpread=argList.getSequencedArgument() != null && !argList.getSequencedArgument().getPositionalArguments().isEmpty() && argList.getSequencedArgument().getPositionalArguments().get(argList.getSequencedArgument().getPositionalArguments().size() - 1) instanceof Tree.SpreadArgument;
if (nargs.size() > 0) {
gen.out("function()");
gen.beginBlock();
arr=names.createTempVariable();
gen.out("var ",arr,"=");
}
else {
isComp=argList.getSequencedArgument().getPositionalArguments().size() == 1 && argList.getSequencedArgument().getPositionalArguments().get(0) instanceof Tree.Comprehension;
}
if (isComp) {
gen.out(gen.getClAlias(),"nfor$(");
}
else if (isSpread) {
gen.out(gen.getClAlias(),"tpl$([");
}
else {
gen.out("[");
}
boolean first=true;
for ( Tree.PositionalArgument arg : argList.getSequencedArgument().getPositionalArguments()) {
if (arg instanceof Tree.SpreadArgument) {
gen.out("],");
arg.visit(gen);
gen.out(").nativeArray()");
}
else {
if (first) {
first=false;
}
else {
gen.out(",");
}
arg.visit(gen);
}
}
if (isComp) {
gen.out(")");
}
else if (!isSpread) {
gen.out("]");
}
if (nargs.size() > 0) {
gen.endLine(true);
for ( Tree.NamedArgument arg : nargs) {
gen.out(arr,".",arg.getIdentifier().getText(),"=");
arg.visit(gen);
gen.endLine(true);
}
gen.out("return ",arr,";");
gen.endBlock();
gen.out("()");
}
}
}
| Generate the code to create a native js object. |
public CustomerWishListServiceImpl(final GenericDAO<CustomerWishList,Long> genericDao){
super(genericDao);
}
| Construct service. |
public boolean isCreateGetterSetter(){
return JavaRefactoringDescriptorUtil.getBoolean(fArguments,CREATE_GETTER_SETTER,false);
}
| Returns <code>true</code> if getters and setters are generated for fields. Default is <code>false</code>. |
public static void main(final String[] args){
DOMTestCase.doMain(nodeattributenodevalue.class,args);
}
| Runs this test from the command line. |
public Random(byte[] randomBytes){
if (randomBytes == null) {
throw new NullPointerException("Random bytes must not be null");
}
else if (randomBytes.length != 32) {
throw new IllegalArgumentException("Random bytes array's length must be 32");
}
else {
this.randomBytes=Arrays.copyOf(randomBytes,randomBytes.length);
}
}
| Sets the random bytes explicitly. |
static boolean promptForYes(String promptText){
return Ascii.toUpperCase(System.console().readLine(promptText + " (y/N): ")).startsWith("Y");
}
| Prompts for yes/no input using promptText, defaulting to no. |
public HAVING HAVING(String having){
return new HAVING(this,having);
}
| Adds a SQL HAVING |
public static LiquidNetwork initNetwork(){
Random random=new Random(System.currentTimeMillis());
int id=random.nextInt();
while (usedIds.contains(id)) {
id=random.nextInt();
}
;
LiquidNetwork net=new LiquidNetwork();
usedIds.add(id);
net.networkID=id;
return net;
}
| Create a new network and get an ID |
public WidgetProposalComputer(String text,int offset,Element rootElement,Element parentElement,IJavaProject javaProject) throws JavaModelException, UiBinderException {
super(javaProject,text,offset,text.length());
this.rootElement=rootElement;
this.parentElement=parentElement;
packageManager.readFromElement(rootElement);
}
| Constructs a widget completion proposal computer. |
public boolean checkAndAdd(int length){
int turn=SingletonRepository.getRuleProcessor().getTurn();
boolean res=check(turn);
if (res) {
add(turn,length);
}
return res;
}
| checks that the bucket is not full, yet and adds the turn in case there is still room. |
private Atom processCommands(String command) throws ParseException {
MacroInfo mac=MacroInfo.Commands.get(command);
int opts=0;
if (mac.hasOptions) opts=mac.posOpts;
String[] args=getOptsArgs(mac.nbArgs,opts);
args[0]=command;
if (NewCommandMacro.isMacro(command)) {
String ret=(String)mac.invoke(this,args);
insert(spos,pos,ret);
return null;
}
return (Atom)mac.invoke(this,args);
}
| Processes the given TeX command (by parsing following command arguments in the parse string). |
public static String toLowerString(String s){
int len=s.length();
int idx=0;
for (; idx < len; idx++) {
if (isUpper(s.charAt(idx))) {
break;
}
}
if (idx == len) {
return s;
}
char[] buf=new char[len];
for (int i=0; i < len; i++) {
char c=s.charAt(i);
buf[i]=(i < idx) ? c : toLower(c);
}
return new String(buf);
}
| Converts the given ASCII String to lower-case. |
protected Criteria createCriteriaInternal(){
Criteria criteria=new Criteria();
return criteria;
}
| This method was generated by MyBatis Generator. This method corresponds to the database table notification |
protected void doRenderGraphic(DrawContext dc){
this.circle.render(dc);
}
| Render the polygon. |
public int findReferencePosition(int offset,boolean danglingElse,boolean matchBrace,boolean matchParen,boolean matchCase){
fIndent=0;
fAlign=JavaHeuristicScanner.NOT_FOUND;
fPosition=offset;
if (matchBrace) {
if (skipScope(Symbols.TokenLBRACE,Symbols.TokenRBRACE)) {
try {
int lineOffset=fDocument.getLineOffset(fLine);
if (lineOffset <= fPosition && fDocument.get(lineOffset,fPosition - lineOffset).trim().length() == 0) return fPosition;
}
catch ( BadLocationException e) {
}
int pos=skipToStatementStart(true,true);
fIndent=0;
return pos;
}
else {
int pos=findReferencePosition(offset,danglingElse,false,matchParen,matchCase);
fIndent--;
return pos;
}
}
if (matchParen) {
if (skipScope(Symbols.TokenLPAREN,Symbols.TokenRPAREN)) return fPosition;
else {
int pos=findReferencePosition(offset,danglingElse,matchBrace,false,matchCase);
fIndent--;
return pos;
}
}
if (matchCase) {
return matchCaseAlignment();
}
nextToken();
switch (fToken) {
case Symbols.TokenGREATERTHAN:
case Symbols.TokenRBRACKET:
case Symbols.TokenRBRACE:
int pos=fPosition;
if (!skipScope()) fPosition=pos;
case Symbols.TokenSEMICOLON:
return skipToStatementStart(danglingElse,false);
case Symbols.TokenLPAREN:
case Symbols.TokenLBRACE:
case Symbols.TokenLBRACKET:
return handleScopeIntroduction(offset + 1);
case Symbols.TokenEOF:
return JavaHeuristicScanner.NOT_FOUND;
case Symbols.TokenEQUAL:
fIndent=fPrefs.prefAssignmentIndent;
return fPosition;
case Symbols.TokenCOLON:
fIndent=fPrefs.prefCaseBlockIndent;
return fPosition;
case Symbols.TokenQUESTIONMARK:
if (fPrefs.prefTernaryDeepAlign) {
setFirstElementAlignment(fPosition,offset + 1);
return fPosition;
}
else {
fIndent=fPrefs.prefTernaryIndent;
return fPosition;
}
case Symbols.TokenDO:
case Symbols.TokenWHILE:
case Symbols.TokenELSE:
fIndent=fPrefs.prefSimpleIndent;
return fPosition;
case Symbols.TokenTRY:
return skipToStatementStart(danglingElse,false);
case Symbols.TokenRPAREN:
int line=fLine;
if (skipScope(Symbols.TokenLPAREN,Symbols.TokenRPAREN)) {
int scope=fPosition;
nextToken();
if (fToken == Symbols.TokenIF || fToken == Symbols.TokenWHILE || fToken == Symbols.TokenFOR) {
fIndent=fPrefs.prefSimpleIndent;
return fPosition;
}
fPosition=scope;
if (looksLikeMethodDecl()) {
return skipToStatementStart(danglingElse,false);
}
if (fToken == Symbols.TokenCATCH) {
return skipToStatementStart(danglingElse,false);
}
fPosition=scope;
if (looksLikeAnonymousTypeDecl()) {
return skipToStatementStart(danglingElse,false);
}
}
fPosition=offset;
fLine=line;
case Symbols.TokenCOMMA:
default :
return skipToPreviousListItemOrListStart();
}
}
| Returns the reference position regarding to indentation for <code>position</code>, or <code>NOT_FOUND</code>.<code>fIndent</code> will contain the relative indentation (in indentation units, not characters) after the call. If there is a special alignment (e.g. for a method declaration where parameters should be aligned), <code>fAlign</code> will contain the absolute position of the alignment reference in <code>fDocument</code>, otherwise <code>fAlign</code> is set to <code>JavaHeuristicScanner.NOT_FOUND</code>. |
public void add(ObjectType type,boolean explicit){
int index=factory.getIndexOfType(type);
if (!exceptionSet.get(index)) {
++size;
}
exceptionSet.set(index);
if (explicit) {
explicitSet.set(index);
}
commonSupertype=null;
}
| Add an exception. |
public final boolean isForwardable(){
return flags[FORWARDABLE_TICKET_FLAG];
}
| Determines if this ticket is forwardable. |
public void mouseMoved(MouseEvent e){
}
| Resets the cursor based on the orientation. |
private void correctErrors(byte[] codewordBytes,int numDataCodewords) throws ChecksumException {
int numCodewords=codewordBytes.length;
int[] codewordsInts=new int[numCodewords];
for (int i=0; i < numCodewords; i++) {
codewordsInts[i]=codewordBytes[i] & 0xFF;
}
int numECCodewords=codewordBytes.length - numDataCodewords;
try {
rsDecoder.decode(codewordsInts,numECCodewords);
}
catch ( ReedSolomonException ignored) {
throw ChecksumException.getChecksumInstance();
}
for (int i=0; i < numDataCodewords; i++) {
codewordBytes[i]=(byte)codewordsInts[i];
}
}
| <p>Given data and error-correction codewords received, possibly corrupted by errors, attempts to correct the errors in-place using Reed-Solomon error correction.</p> |
@SuppressWarnings("deprecation") @TargetApi(Build.VERSION_CODES.ECLAIR) @SuppressLint("NewApi") private void dumpEvent(MotionEvent event){
String names[]={"DOWN","UP","MOVE","CANCEL","OUTSIDE","POINTER_DOWN","POINTER_UP","7?","8?","9?"};
@SuppressWarnings("MismatchedQueryAndUpdateOfStringBuilder") StringBuilder sb=new StringBuilder();
int action=event.getAction();
int actionCode=action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i=0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int)event.getX(i));
sb.append(",").append((int)event.getY(i));
if (i + 1 < event.getPointerCount()) sb.append(";");
}
sb.append("]");
}
| Show an event in the LogCat view, for debugging |
final private void cycle(IntGrid2D d,IntGrid2D buffer){
buffer.setTo(d);
int x;
int y;
int w=d.getWidth();
int h=d.getHeight();
for (y=0; y < h; y++) {
for (x=0; x < w; x++) computeNextState(d,buffer,x,y);
}
for (y=0; y < h; y+=2) {
for (x=0; x < w; x+=2) turn22(d,x,y);
}
for (y=1; y < h; y+=2) {
for (x=1; x < w; x+=2) turn22(d,x,y);
}
}
| A single cycle in the life of the cellular automaton. Compute for every cell the next state and also apply the Toffoli & Margolus diffusion. |
public StringKernel(Instances data,int cacheSize,int subsequenceLength,double lambda,boolean debug) throws Exception {
setDebug(debug);
setCacheSize(cacheSize);
setInternalCacheSize(200003);
setSubsequenceLength(subsequenceLength);
setMaxSubsequenceLength(-1);
setLambda(lambda);
buildKernel(data);
}
| creates a new StringKernel object. Initializes the kernel cache and the 'lambda cache', i.e. the precalculated powers of lambda from lambda^2 to lambda^MAX_POWER_OF_LAMBDA |
public void doBucketChecks(long now){
boolean survival=isInSurvivalMode();
if (survival && now - timeOfLastPingCheck > DHTConstants.BOOTSTRAP_MIN_INTERVAL) return;
timeOfLastPingCheck=now;
mergeBuckets();
int newEntryCount=0;
Map<InetAddress,KBucket> addressDedup=new HashMap<>(num_entries);
for ( RoutingTableEntry e : routingTableCOW.entries) {
KBucket b=e.bucket;
List<KBucketEntry> entries=b.getEntries();
Set<Key> localIds=usedIDs.snapshot();
boolean wasFull=b.getNumEntries() >= DHTConstants.MAX_ENTRIES_PER_BUCKET;
for ( KBucketEntry entry : entries) {
if (localIds.contains(entry.getID()) || (wasFull && dht.getBootStrapNodes().contains(entry.getAddress()))) {
b.removeEntryIfBad(entry,true);
continue;
}
addressDedup.compute(entry.getAddress().getAddress(),null);
}
boolean refreshNeeded=b.needsToBeRefreshed();
boolean replacementNeeded=b.needsReplacementPing();
if (refreshNeeded || replacementNeeded) tryPingMaintenance(b,"Refreshing Bucket #" + e.prefix,null,null);
if (!survival) {
b.promoteVerifiedReplacement();
}
newEntryCount+=e.bucket.getNumEntries();
}
num_entries=newEntryCount;
rebuildAddressCache();
decayThrottle();
}
| Check if a buckets needs to be refreshed, and refresh if necessary. |
public void begin(){
this.zkClient.start();
this.lastEmittedBeginTxPosition=openReplicatorClient.initialize(this.spoutConfig.getMysqlConfig(),this.spoutConfig.getZkBinLogStateConfig(),this.txQueue);
openReplicatorClient.start();
}
| Start all clients. |
public void rotateLog(){
initialize(m_adempiereHome,true,Ini.isClient());
}
| Rotate Log Called after Initialization |
@Override protected void initViews(Bundle savedInstanceState){
this.startBT=this.findView(R.id.start_bt);
}
| Initialize the view in the layout |
@Override public int delete(String key){
checkKey(key);
return database.delete(TABLE_NAME,COLUMN_KEY + " = ?",new String[]{key});
}
| Delete data. |
public BillingAdapterConnectionException(String message,Throwable cause){
super(message,cause);
}
| Constructs a new exception with the specified detail message and cause. |
private void registerListener(final String requestUrl,final String target,String[] methods,Integer expireTime){
registerListener(requestUrl,target,methods,expireTime,null);
}
| Registers a listener. |
public void addTransaction(SIPClientTransaction clientTransaction){
if (isLoggingEnabled()) stackLogger.logDebug("added transaction " + clientTransaction);
addTransactionHash(clientTransaction);
}
| Add a new client transaction to the set of existing transactions. Add it to the top of the list so an incoming response has less work to do in order to find the transaction. |
public int indexOfSegment(Segment segment){
return selectedSegments.indexOf(segment);
}
| Get the index of a selected segment. |
public CstString(ByteArray bytes){
if (bytes == null) {
throw new NullPointerException("bytes == null");
}
this.bytes=bytes;
this.string=utf8BytesToString(bytes).intern();
}
| Constructs an instance from some UTF-8 bytes. |
@Override protected EClass eStaticClass(){
return N4JSPackage.Literals.PARAMETERIZED_PROPERTY_ACCESS_EXPRESSION;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
protected ExportedVariableStatementImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public PostLogProfilerProcessor(String filename,PrintStream out) throws Exception {
FileReader f=new FileReader(filename);
LineNumberReader l=new LineNumberReader(f);
String line;
boolean blankLine;
StringBuffer sql=new StringBuffer();
do {
line=l.readLine();
if (line != null) {
blankLine=line.length() == 0;
lineNo++;
if (blankLine) {
processSql(sql);
sql=new StringBuffer();
}
else {
sql.append(line);
}
}
}
while (line != null);
out.println("processed " + lineNo + " lines.");
f.close();
out.println("Number of sql statements: " + totalSql);
out.println("Total number of msec : " + totalMsec);
if (totalMsec > 0) {
out.println("Average msec/statement : " + totalSql / totalMsec);
}
int flaggedSqlStmts=flaggedSql.size();
if (flaggedSqlStmts > 0) {
out.println("Sql statements that took more than " + threshold + " msec were flagged.");
out.println("Flagged sql statements : " + flaggedSqlStmts);
out.println("Flagged sql Total number of msec : " + flaggedSqlTotalMsec);
out.println("Flagged sql Average msec/statement : " + flaggedSqlTotalMsec / flaggedSqlStmts);
out.println("sorting...");
Object[] flaggedSqlArray=flaggedSql.toArray();
Arrays.sort(flaggedSqlArray);
int execTimeSize=("" + maxMsec).length();
if (topOffenderCount > flaggedSqlArray.length) {
topOffenderCount=flaggedSqlArray.length;
}
out.println("top " + topOffenderCount + " offender"+ (topOffenderCount == 1 ? "" : "s")+ ":");
ProfiledSql p;
for (int i=0; i < topOffenderCount; i++) {
p=(ProfiledSql)flaggedSqlArray[i];
out.println(Utilities.rightJustify(execTimeSize,"" + p.getExecTime()) + " " + p.getSql());
}
}
}
| Process given filename, and produce sql profiling report to given PrintStream. |
public void loadByteArray(SdfBuffer buffer){
buffer.setAtIndexAndInc(byte1);
buffer.setAtIndexAndInc(byte2);
buffer.setAtIndexAndInc(byte3);
buffer.setAtIndexAndInc(byte4);
super.loadByteArray(buffer);
}
| Store into a buffer. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.