code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public void arc(double x,double y,double w,double h,double startAngle,double sweepAngle,boolean joinPath){
arc((float)x,(float)y,(float)w,(float)h,(float)startAngle,(float)sweepAngle,joinPath);
}
| Draws an elliptical arc on the path given the provided bounds. |
public DefaultWordsScanner(final Lexer lexer,final TokenSet identifierTokenSet,final TokenSet commentTokenSet,final TokenSet literalTokenSet){
this(lexer,identifierTokenSet,commentTokenSet,literalTokenSet,TokenSet.EMPTY);
}
| Creates a new instance of the words scanner. |
public static void dropTable(SQLiteDatabase db,boolean ifExists){
String sql="DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'GROUP_REMOVE_DEVICE_DB'";
db.execSQL(sql);
}
| Drops the underlying database table. |
public static <T>List<T> readNullableCollection(BinaryRawReaderEx reader,@Nullable PlatformReaderClosure<T> readClo){
if (!reader.readBoolean()) return null;
return readCollection(reader,readClo);
}
| Read nullable collection. |
LinkedList computeOrder(DirectedGraph g){
stmtToColor=new HashMap();
order=new LinkedList();
graph=g;
PseudoTopologicalReverseOrderer orderer=new PseudoTopologicalReverseOrderer();
reverseOrder=orderer.newList(g);
{
Iterator stmtIt=g.iterator();
while (stmtIt.hasNext()) {
Object s=stmtIt.next();
stmtToColor.put(s,new Integer(WHITE));
}
}
{
Iterator stmtIt=g.iterator();
while (stmtIt.hasNext()) {
Object s=stmtIt.next();
if (stmtToColor.get(s).intValue() == WHITE) visitNode(s);
}
}
return order;
}
| Orders in pseudo-topological order. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:00:30.802 -0500",hash_original_method="939347762BF1A6E9C475E2B54A6ADF35",hash_generated_method="60127D7162D992757C5B241F8DE55F4B") public KeyGenerationParameters(SecureRandom random,int strength){
this.random=random;
this.strength=strength;
}
| initialise the generator with a source of randomness and a strength (in bits). |
private void scanAndLoadDictionaries() throws IOException {
if (Files.isDirectory(hunspellDir)) {
try (DirectoryStream<Path> stream=Files.newDirectoryStream(hunspellDir)){
for ( Path file : stream) {
if (Files.isDirectory(file)) {
try (DirectoryStream<Path> inner=Files.newDirectoryStream(hunspellDir.resolve(file),"*.dic")){
if (inner.iterator().hasNext()) {
try {
dictionaries.getUnchecked(file.getFileName().toString());
}
catch ( UncheckedExecutionException e) {
logger.error("exception while loading dictionary {}",file.getFileName(),e);
}
}
}
}
}
}
}
}
| Scans the hunspell directory and loads all found dictionaries |
public void sendResponse(int rCode,String rTag) throws IOException {
OutputStream os=new TestHttpServer.NioOutputStream(channel());
PrintStream ps=new PrintStream(os);
ps.print("HTTP/1.1 " + rCode + " "+ rTag+ "\r\n");
if (rspheaders != null) {
rspheaders.print(ps);
}
else {
ps.print("\r\n");
}
ps.flush();
if (rspbody != null) {
os.write(rspbody,0,rspbodylen);
os.flush();
}
if (rsptrailers != null) {
rsptrailers.print(ps);
}
else if (rspchunked) {
ps.print("\r\n");
}
ps.flush();
}
| Send the response with the current set of response parameters but using the response code and string tag line as specified |
public void saveDomain(File fileToWrite){
String curText=editorTab.getText();
if (fileToWrite != null) {
try {
Files.write(Paths.get(fileToWrite.toURI()),curText.getBytes());
}
catch ( IOException e) {
log.severe("Cannot save domain: " + e);
e.printStackTrace();
editorTab.rereadFile();
}
setSavedFlag(true);
refresh();
}
}
| Saves the dialogue domain in the editor tab to the file given as argument |
public JSONWriter key(String string) throws JSONException {
if (string == null) {
throw new JSONException("Null key.");
}
if (this.mode == 'k') {
try {
this.stack[this.top - 1].putOnce(string,Boolean.TRUE);
if (this.comma) {
this.writer.write(',');
}
this.writer.write(JSONObject.quote(string));
this.writer.write(':');
this.comma=false;
this.mode='o';
return this;
}
catch ( IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
}
| Append a key. The key will be associated with the next value. In an object, every value must be preceded by a key. |
public static String parseIdentifier(FXGNode node,String value,String name,String defaultValue){
Matcher m;
m=idPattern.matcher(value);
if (m.matches()) {
return value;
}
else {
if (((AbstractFXGNode)node).isVersionGreaterThanCompiler()) {
FXGLog.getLogger().log(FXGLogger.WARN,"DefaultAttributeValue",null,((AbstractFXGNode)node).getDocumentName(),node.getStartLine(),node.getStartColumn(),defaultValue,name);
return defaultValue;
}
else {
throw new FXGException(node.getStartLine(),node.getStartColumn(),"InvalidIdentifierFormat",value);
}
}
}
| Convert an FXG String value to a Identifier matching pattern [a-zA-Z_][a-zA-Z_0-9]*. |
@Override public boolean equals(Object object){
if (object == null) {
return false;
}
if (this == object) {
return true;
}
if (!(object instanceof ConjunctiveRuleModel)) {
return false;
}
ConjunctiveRuleModel rule=(ConjunctiveRuleModel)object;
if (this.getRuleLength() != rule.getRuleLength() || this.getConclusion() != rule.getConclusion()) {
return false;
}
for (int i=0; i < this.getRuleLength(); i++) {
Attribute att=this.getAttributeOfLiteral(i);
int pos;
if ((pos=rule.getPositionOfAttributeInRule(att)) == -1 || this.getTestedValueAtLiteral(i) != rule.getTestedValueAtLiteral(pos)) {
return false;
}
}
return true;
}
| Two rules are equal, if they are both permutations of the same set of literals and predict the same label. |
public synchronized void sync(long position) throws IOException {
if (position + SYNC_SIZE >= end) {
seek(end);
return;
}
if (position < headerEnd) {
in.seek(headerEnd);
syncSeen=true;
return;
}
try {
seek(position + 4);
in.readFully(syncCheck);
int syncLen=sync.length;
for (int i=0; in.getPos() < end; i++) {
int j=0;
for (; j < syncLen; j++) {
if (sync[j] != syncCheck[(i + j) % syncLen]) {
break;
}
}
if (j == syncLen) {
in.seek(in.getPos() - SYNC_SIZE);
return;
}
syncCheck[i % syncLen]=in.readByte();
}
}
catch ( ChecksumException e) {
handleChecksumException(e);
}
}
| Seek to the next sync mark past a given position. |
public String toStringSummary(){
String result;
String titles;
int resultsetLength;
int i;
int j;
String content;
if (m_NonSigWins == null) return "-summary data not set-";
result="<table border=\"1\" cellpadding=\"3\" cellspacing=\"0\">\n";
titles=" <tr>";
resultsetLength=1 + Math.max((int)(Math.log(getColCount()) / Math.log(10)),(int)(Math.log(getRowCount()) / Math.log(10)));
for (i=0; i < getColCount(); i++) {
if (getColHidden(i)) continue;
titles+="<td align=\"center\"><b>" + getSummaryTitle(i) + "</b></td>";
}
result+=titles + "<td><b>(No. of datasets where [col] >> [row])</b></td></tr>\n";
for (i=0; i < getColCount(); i++) {
if (getColHidden(i)) continue;
result+=" <tr>";
for (j=0; j < getColCount(); j++) {
if (getColHidden(j)) continue;
if (j == i) content=Utils.padLeft("-",resultsetLength * 2 + 3);
else content=Utils.padLeft("" + m_NonSigWins[i][j] + " ("+ m_Wins[i][j]+ ")",resultsetLength * 2 + 3);
result+="<td>" + content.replaceAll(" "," ") + "</td>";
}
result+="<td><b>" + getSummaryTitle(i) + "</b> = "+ removeFilterName(m_ColNames[i])+ "</td></tr>\n";
}
result+="</table>\n";
return result;
}
| returns the summary as string. |
private static String codegenCompiledResourceBundleNames(SortedSet<String> bundleNames){
if (bundleNames == null) return "[]";
StringJoiner.ItemStringer itemStringer=new StringJoiner.ItemQuoter();
return "[ " + StringJoiner.join(bundleNames,", ",itemStringer) + " ]";
}
| Returns a string like [ "core", "controls", "MyApp" ] |
public synchronized void request(long n){
System.out.println("requested " + n);
numRequested+=n;
if (!marble.isEmpty()) {
parseLatch.countDown();
}
if (n > 0) sendLatch.countDown();
}
| This method is synchronized because we only want to process one request at one time. Calling this method unblocks the sendLatch as well as the parseLatch if we have more requests, as it allows both emitted and non-emitted symbols to be sent, |
public SendAgentThread(IAgent a,Address to,boolean destroy){
super("SendAgent");
if (!(a.getClass().getClassLoader() instanceof JobClassLoader)) throw new IllegalArgumentException("Agent must have a JobClassLoader");
this.a=a;
this.to=to;
this.destroy=destroy;
startTime=System.currentTimeMillis();
}
| Creates a thread that sends an agent to another host. |
public final boolean executeCommand(AbsSender absSender,Message message){
if (message.hasText()) {
String text=message.getText();
if (text.startsWith(BotCommand.COMMAND_INIT_CHARACTER)) {
String commandMessage=text.substring(1);
String[] commandSplit=commandMessage.split(BotCommand.COMMAND_PARAMETER_SEPARATOR);
String command=removeUsernameFromCommandIfNeeded(commandSplit[0]);
if (commandRegistryMap.containsKey(command)) {
String[] parameters=Arrays.copyOfRange(commandSplit,1,commandSplit.length);
commandRegistryMap.get(command).execute(absSender,message.getFrom(),message.getChat(),parameters);
return true;
}
else if (defaultConsumer != null) {
defaultConsumer.accept(absSender,message);
return true;
}
}
}
return false;
}
| Executes a command action if the command is registered. |
@MediumTest public void testPeriodics() throws Exception {
final Account account1=new Account("[email protected]","example.type");
final Account account2=new Account("[email protected]","example.type.2");
final String authority="testprovider";
final Bundle extras1=new Bundle();
extras1.putString("a","1");
final Bundle extras2=new Bundle();
extras2.putString("a","2");
final int period1=200;
final int period2=1000;
PeriodicSync sync1=new PeriodicSync(account1,authority,extras1,period1);
PeriodicSync sync2=new PeriodicSync(account1,authority,extras2,period1);
PeriodicSync sync3=new PeriodicSync(account1,authority,extras2,period2);
PeriodicSync sync4=new PeriodicSync(account2,authority,extras2,period2);
MockContentResolver mockResolver=new MockContentResolver();
SyncStorageEngine engine=SyncStorageEngine.newTestInstance(new TestContext(mockResolver,getContext()));
removePeriodicSyncs(engine,account1,0,authority);
removePeriodicSyncs(engine,account2,0,authority);
removePeriodicSyncs(engine,account1,1,authority);
engine.addPeriodicSync(sync1.account,0,sync1.authority,sync1.extras,sync1.period);
engine.addPeriodicSync(sync2.account,0,sync2.authority,sync2.extras,sync2.period);
engine.addPeriodicSync(sync3.account,0,sync3.authority,sync3.extras,sync3.period);
engine.addPeriodicSync(sync4.account,0,sync4.authority,sync4.extras,sync4.period);
engine.addPeriodicSync(sync2.account,1,sync2.authority,sync2.extras,sync2.period);
List<PeriodicSync> syncs=engine.getPeriodicSyncs(account1,0,authority);
assertEquals(2,syncs.size());
assertEquals(sync1,syncs.get(0));
assertEquals(sync3,syncs.get(1));
engine.removePeriodicSync(sync1.account,0,sync1.authority,sync1.extras);
syncs=engine.getPeriodicSyncs(account1,0,authority);
assertEquals(1,syncs.size());
assertEquals(sync3,syncs.get(0));
syncs=engine.getPeriodicSyncs(account2,0,authority);
assertEquals(1,syncs.size());
assertEquals(sync4,syncs.get(0));
syncs=engine.getPeriodicSyncs(sync2.account,1,sync2.authority);
assertEquals(1,syncs.size());
assertEquals(sync2,syncs.get(0));
}
| Test that we can create, remove and retrieve periodic syncs |
public List<ExportGroupRestRep> findContainingCluster(URI clusterId){
return search().byCluster(clusterId).run();
}
| Finds the exports associated with a cluster. |
private void writeObject(ObjectOutputStream out) throws IOException {
maybeParse();
out.defaultWriteObject();
}
| Ensure object is fully parsed before invoking java serialization. The backing byte array is transient so if the object has parseLazy = true and hasn't invoked checkParse yet then data will be lost during serialization. |
public AddTableChange(Table newTable){
_newTable=newTable;
}
| Creates a new change object. |
public int length(){
return length;
}
| Returns the length of this BitArray. |
private void createSceneSSBO(){
this.ssbo=glGenBuffers();
glBindBuffer(GL_SHADER_STORAGE_BUFFER,ssbo);
ByteBuffer ssboData=BufferUtils.createByteBuffer(4 * (4 + 4) * boxes.length / 2);
FloatBuffer fv=ssboData.asFloatBuffer();
for (int i=0; i < boxes.length; i+=2) {
Vector3f min=boxes[i];
Vector3f max=boxes[i + 1];
fv.put(min.x).put(min.y).put(min.z).put(0.0f);
fv.put(max.x).put(max.y).put(max.z).put(0.0f);
}
glBufferData(GL_SHADER_STORAGE_BUFFER,ssboData,GL_STATIC_DRAW);
glBindBuffer(GL_SHADER_STORAGE_BUFFER,0);
}
| Create a Shader Storage Buffer Object which will hold our boxes to be read by our Compute Shader. |
public boolean hasStartIndex(){
return getStartIndex() != null;
}
| Returns whether it has the index of the first row of the data section (inclusive). |
public static <T>String toString(Class<T> cls,T obj,String name0,Object val0,String name1,Object val1,String name2,Object val2,String name3,Object val3,String name4,Object val4){
assert cls != null;
assert obj != null;
assert name0 != null;
assert name1 != null;
assert name2 != null;
assert name3 != null;
assert name4 != null;
Queue<GridToStringThreadLocal> queue=threadCache.get();
assert queue != null;
GridToStringThreadLocal tmp=queue.isEmpty() ? new GridToStringThreadLocal() : queue.remove();
Object[] addNames=tmp.getAdditionalNames();
Object[] addVals=tmp.getAdditionalValues();
addNames[0]=name0;
addVals[0]=val0;
addNames[1]=name1;
addVals[1]=val1;
addNames[2]=name2;
addVals[2]=val2;
addNames[3]=name3;
addVals[3]=val3;
addNames[4]=name4;
addVals[4]=val4;
try {
return toStringImpl(cls,tmp.getStringBuilder(),obj,addNames,addVals,5);
}
finally {
queue.offer(tmp);
}
}
| Produces auto-generated output of string presentation for given object and its declaration class. |
public int compareTo(FifteenPuzzleNode n){
return toString().compareTo(n.toString());
}
| Offer rudimentary compareTo method by comparing boards. <p> based on String representation since we must be careful to ensure that a.compareTo(b) is the opposite of b.compareTo(a). |
private void restore(Bundle savedInstanceState){
if (savedInstanceState != null) {
player=(IPlayer)savedInstanceState.get(KEY_PLAYER);
videoEntry=(DownloadEntry)savedInstanceState.get(KEY_VIDEO);
isPrepared=savedInstanceState.getBoolean(KEY_PREPARED);
isAutoPlayDone=savedInstanceState.getBoolean(KEY_AUTOPLAY_DONE);
transcript=(TranscriptModel)savedInstanceState.get(KEY_TRANSCRIPT);
if (savedInstanceState.getBoolean(KEY_MESSAGE_DISPLAYED)) {
showVideoNotAvailable(VideoNotPlayMessageType.IS_VIDEO_MESSAGE_DISPLAYED);
}
}
else {
if (player == null) player=new Player();
}
}
| Restores the saved instance of the player. |
private boolean isTimeout(){
int allowedMin=4 + level * 2;
if (level <= 2) {
allowedMin=2;
}
long diff=System.currentTimeMillis() - levelStart;
return diff / 1000 > allowedMin * 60;
}
| is the timeout reached |
public void removeSection(Section s){
sections.remove(s);
ccl.remove(s);
}
| Removes the specified Section. |
public S2Polygon assemblePolygon(){
S2Polygon polygon=new S2Polygon();
List<S2Edge> unusedEdges=Lists.newArrayList();
assemblePolygon(polygon,unusedEdges);
return polygon;
}
| Convenience method for when you don't care about unused edges. |
@Override public boolean supportsAlterTableWithAddColumn(){
debugCodeCall("supportsAlterTableWithAddColumn");
return true;
}
| Returns whether alter table with add column is supported. |
public IntegrateAndFireRulePanel(){
super();
this.add(tabbedPane);
tfTimeConstant=createTextField(null,null);
tfThreshold=createTextField(null,null);
tfReset=createTextField(null,null);
tfResistance=createTextField(null,null);
tfRestingPotential=createTextField(null,null);
tfBackgroundCurrent=createTextField(null,null);
mainTab.addItem("Threshold (mV)",tfThreshold);
mainTab.addItem("Resting potential (mV)",tfRestingPotential);
mainTab.addItem("Reset potential (mV)",tfReset);
mainTab.addItem("Resistance (M\u03A9)",tfResistance);
mainTab.addItem("Background Current (nA)",tfBackgroundCurrent);
mainTab.addItem("Time constant (ms)",tfTimeConstant);
mainTab.addItem("Add noise",getAddNoise());
tabbedPane.add(mainTab,"Main");
tabbedPane.add(getNoisePanel(),"Noise");
}
| Creates a new instance of the integrate and fire neuron panel. |
private static Response failure(final Throwable err,final int code) throws IOException {
final ByteArrayOutputStream baos=new ByteArrayOutputStream();
final PrintStream stream=new Utf8PrintStream(baos,false);
try {
err.printStackTrace(stream);
}
finally {
stream.close();
}
return new RsWithStatus(new RsText(new ByteArrayInputStream(baos.toByteArray())),code);
}
| Make a failure response. |
private boolean existsFdrs(String entidad) throws Exception {
ArchivesTable table=new ArchivesTable();
boolean exists=false;
String tblName;
int count;
DbConnection dbConn=new DbConnection();
try {
dbConn.open(DBSessionManager.getSession(entidad));
tblName=DaoUtil.getFdrHdrTblName(_tblPrefix);
count=DbSelectFns.selectCount(dbConn,tblName,null);
if (count > 0) exists=true;
dbConn.open(DBSessionManager.getSession(entidad));
}
catch ( Exception e) {
_logger.error(e);
throw e;
}
finally {
dbConn.close();
}
return exists;
}
| Obtiene si existen carpetas en el archivador. |
boolean defineChar2StringMapping(String outputString,char inputChar){
CharKey character=new CharKey(inputChar);
m_charToString.put(character,outputString);
set(inputChar);
boolean extraMapping=extraEntity(outputString,inputChar);
return extraMapping;
}
| Call this method to register a char to String mapping, for example to map '<' to "<". |
public void addScrollingListener(OnWheelScrollListener listener){
scrollingListeners.add(listener);
}
| Adds wheel scrolling listener |
public void addLast(Object o){
addBefore(o,header);
}
| Appends the given element to the end of this list. (Identical in function to the <tt>add</tt> method; included only for consistency.) |
public void draw(Graphics2D g2d){
syncLayout();
gv.draw(g2d,aci);
}
| Paints the text layout using the specified Graphics2D and rendering context. |
public void load(SimState state){
super.load(state);
setupPortrayals();
}
| Loads a game. This is unlikely to occur. |
public boolean isStrictJSR107(){
return strictJSR107;
}
| Returns whether the Cache behaves strictly JSR107 compliant |
public void addItem(Artist a){
synchronized (mArtists) {
mArtists.add(a);
sortList();
}
}
| Adds an item to the adapter |
protected void assertInventory(final long warehouseId,final String skuCode,final String expectedAvailable,final String expectedReserved){
ProductSku sku=productSkuService.getProductSkuBySkuCode(skuCode);
Pair<BigDecimal,BigDecimal> qty=skuWarehouseService.findQuantity(new ArrayList<Warehouse>(){
{
add(warehouseService.findById(warehouseId));
}
}
,sku.getCode());
assertEquals(new BigDecimal(expectedAvailable),qty.getFirst());
assertEquals(new BigDecimal(expectedReserved),qty.getSecond());
}
| Assert inventory state. |
public org.fife.ui.rsyntaxtextarea.Token yylex() throws java.io.IOException {
int zzInput;
int zzAction;
int zzCurrentPosL;
int zzMarkedPosL;
int zzEndReadL=zzEndRead;
char[] zzBufferL=zzBuffer;
char[] zzCMapL=ZZ_CMAP;
int[] zzTransL=ZZ_TRANS;
int[] zzRowMapL=ZZ_ROWMAP;
int[] zzAttrL=ZZ_ATTRIBUTE;
while (true) {
zzMarkedPosL=zzMarkedPos;
zzAction=-1;
zzCurrentPosL=zzCurrentPos=zzStartRead=zzMarkedPosL;
zzState=zzLexicalState;
zzForAction: {
while (true) {
if (zzCurrentPosL < zzEndReadL) zzInput=zzBufferL[zzCurrentPosL++];
else if (zzAtEOF) {
zzInput=YYEOF;
break zzForAction;
}
else {
zzCurrentPos=zzCurrentPosL;
zzMarkedPos=zzMarkedPosL;
boolean eof=zzRefill();
zzCurrentPosL=zzCurrentPos;
zzMarkedPosL=zzMarkedPos;
zzBufferL=zzBuffer;
zzEndReadL=zzEndRead;
if (eof) {
zzInput=YYEOF;
break zzForAction;
}
else {
zzInput=zzBufferL[zzCurrentPosL++];
}
}
int zzNext=zzTransL[zzRowMapL[zzState] + zzCMapL[zzInput]];
if (zzNext == -1) break zzForAction;
zzState=zzNext;
int zzAttributes=zzAttrL[zzState];
if ((zzAttributes & 1) == 1) {
zzAction=zzState;
zzMarkedPosL=zzCurrentPosL;
if ((zzAttributes & 8) == 8) break zzForAction;
}
}
}
zzMarkedPos=zzMarkedPosL;
switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
case 1:
{
addToken(Token.IDENTIFIER);
}
case 11:
break;
case 9:
{
addToken(Token.MARKUP_TAG_DELIMITER);
}
case 12:
break;
case 2:
{
addToken(Token.WHITESPACE);
}
case 13:
break;
case 10:
{
addToken(Token.OPERATOR);
}
case 14:
break;
case 8:
{
addToken(Token.MARKUP_TAG_NAME);
}
case 15:
break;
case 4:
{
addToken(Token.MARKUP_TAG_DELIMITER);
yybegin(INTAG);
}
case 16:
break;
case 6:
{
addToken(Token.IDENTIFIER);
}
case 17:
break;
case 5:
{
addToken(Token.MARKUP_TAG_ATTRIBUTE);
}
case 18:
break;
case 3:
{
addNullToken();
return firstToken;
}
case 19:
break;
case 7:
{
yybegin(YYINITIAL);
addToken(Token.MARKUP_TAG_DELIMITER);
}
case 20:
break;
default :
if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
zzAtEOF=true;
switch (zzLexicalState) {
case INTAG:
{
addToken(zzMarkedPos,zzMarkedPos,INTERNAL_INTAG);
return firstToken;
}
case 42:
break;
case YYINITIAL:
{
addNullToken();
return firstToken;
}
case 43:
break;
default :
return null;
}
}
else {
zzScanError(ZZ_NO_MATCH);
}
}
}
}
| Resumes scanning until the next regular expression is matched, the end of input is encountered or an I/O-Error occurs. |
public static void main(String... a) throws Exception {
TestImmutableArray test=(TestImmutableArray)TestBase.createCaller().init();
test.test();
testPerformance();
}
| Run just this test. |
protected Entry<K,V> nextEntry(){
if (modCount != expectedModCount) throw new ConcurrentModificationException();
if (nextKey == null && !hasNext()) throw new NoSuchElementException();
lastReturned=entry;
entry=entry.next;
currentKey=nextKey;
nextKey=null;
return lastReturned;
}
| The common parts of next() across different types of iterators |
public jMatrix solve(jMatrix B){
return (m == n ? (new Jama.LUDecomposition(this)).solve(B) : (new Jama.QRDecomposition(this)).solve(B));
}
| Solve A*X = B |
public void close() throws IOException {
internalIn.close();
}
| Closes this reader. |
public FontType(int textureAtlas,File fontFile){
this.textureAtlas=textureAtlas;
this.loader=new TextMeshCreator(fontFile);
}
| Creates a new font and loads up the data about each character from the font file. |
public void recordVolumeOperation(DbClient dbClient,OperationTypeEnum opType,Operation.Status status,Object... extParam){
try {
boolean opStatus=(Operation.Status.ready == status) ? true : false;
String evType;
evType=opType.getEvType(opStatus);
String evDesc=opType.getDescription();
String opStage=AuditLogManager.AUDITOP_END;
_logger.info("opType: {} detail: {}",opType.toString(),evType.toString() + ':' + evDesc);
URI uri=(URI)extParam[0];
recordBourneVolumeEvent(dbClient,evType,status,evDesc,uri);
String id=uri.toString();
AuditBlockUtil.auditBlock(dbClient,opType,opStatus,opStage,id);
}
catch ( Exception e) {
_logger.error("Failed to record volume operation {}, err:",opType.toString(),e);
}
}
| Record volume related event and audit |
private boolean isBetterLocation(final Location location){
if (location == null) {
return false;
}
if (currentBestLocation == null) {
return true;
}
long timeDelta=location.getTime() - currentBestLocation.getTime();
boolean isNewer=timeDelta > 0;
if (timeDelta > TWO_MINUTES_IN_MILLISECONDS) {
return true;
}
if (timeDelta < -TWO_MINUTES_IN_MILLISECONDS) {
return false;
}
int accuracyDelta=(int)(location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isMoreAccurate=accuracyDelta < 0;
boolean isEquallyAccurate=accuracyDelta == 0;
boolean isSlightlyLessAccurate=(accuracyDelta > 0) && (accuracyDelta <= LOCATION_ACCURACY);
boolean isFromSameProvider=isSameProvider(location.getProvider(),currentBestLocation.getProvider());
return (isMoreAccurate || (isNewer && (isEquallyAccurate || (isFromSameProvider && isSlightlyLessAccurate))));
}
| Determines whether a new location is "better" that then current best location, taking into account when the location was retrieved and its accuracy. |
public static double SSPNmaxFitness(GEPIndividual ind){
return (1000.0);
}
| The max value for this type of fitness is always 1000. |
public void testResourcesAvailable(){
new JapaneseAnalyzer().close();
}
| This test fails with NPE when the stopwords file is missing in classpath |
public boolean visit(TypeParameter node){
return true;
}
| Visits the given type-specific AST node. <p> The default implementation does nothing and return true. Subclasses may reimplement. </p> |
protected JSRInlinerAdapter(final int api,final MethodVisitor mv,final int access,final String name,final String desc,final String signature,final String[] exceptions){
super(api,access,name,desc,signature,exceptions);
this.mv=mv;
}
| Creates a new JSRInliner. |
boolean waitForFileDone(){
synchronized (waitFileSync) {
try {
while (!fileDone) waitFileSync.wait();
}
catch ( Exception e) {
}
}
return fileSuccess;
}
| Block until file writing is done. |
public static String format(String property,Object... args){
String text=ResourceBundle.getBundle(Messages.class.getName()).getString(property);
return MessageFormat.format(text,args);
}
| Loads a string resource and formats it with specified arguments. |
AlarmManager(IAlarmManager service){
mService=service;
}
| package private on purpose |
public static <E extends Comparable<E>>BinaryNode<E> leastCommonAncestor(BinaryNode<E> node,E value1,E value2){
if (node == null || value1.compareTo(value2) > 0) throw new NoSuchElementException();
if (value1.compareTo(node.value) <= 0 && value2.compareTo(node.value) >= 0) {
return node;
}
else if (value1.compareTo(node.value) > 0 && value2.compareTo(node.value) > 0) {
return leastCommonAncestor(node.right,value1,value2);
}
else {
return leastCommonAncestor(node.left,value1,value2);
}
}
| Determines the LCA for a BST <p/> DEFINITION OF LCA: Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself). |
public void provideCapacity(final int capacity){
if (c.length >= capacity) {
return;
}
int newcapacity=((capacity * 3) >> 1) + 1;
char[] newc=new char[newcapacity];
System.arraycopy(c,0,newc,0,length);
c=newc;
}
| Copies the data into a new array of at least <code>capacity</code> size. |
protected final void addImpl(Component comp,Object constraints,int index){
if (comp instanceof Layer) {
super.addImpl(comp,constraints,index);
}
else {
throw new IllegalArgumentException("only Layers can be added to a MapBean");
}
}
| Adds additional constraints on possible children components. The new component must be a Layer. This method included as a good container citizen, and should not be called directly. Use the add() methods inherited from java.awt.Container instead. |
public static double lngamma(double xx){
if (xx <= 0) return Double.NaN;
double x, y, tmp, ser;
int j;
y=x=xx;
tmp=x + 5.5;
tmp-=(x + 0.5) * Math.log(tmp);
ser=1.000000000190015;
for (j=0; j <= 5; j++) {
ser+=cof[j] / ++y;
}
return -tmp + Math.log(2.5066282746310005 * ser / x);
}
| This is a more literal (that is, exact) copy of the log gamma method from Numerical Recipes than the following one. It was created by cutting and pasting from the PDF version of the book and then converting C syntax to Java. </p> The static double array above goes with this. </p> Converted to Java by Frank Wimberly |
@Override public int compareTo(HaplotypePlayback that){
final int position=this.templatePosition() - that.templatePosition();
if (position != 0) {
return position;
}
if (this.mNextVariant == null) {
if (that.mNextVariant == null) {
return 0;
}
return -1;
}
if (that.mNextVariant == null) {
return 1;
}
final int current=this.mNextVariant.compareTo(that.mNextVariant);
if (current != 0) {
return current;
}
final int varPos=this.mPositionInVariant - that.mPositionInVariant;
if (varPos != 0) {
return varPos;
}
final Iterator<OrientedVariant> thisIt=this.mVariants.iterator();
final Iterator<OrientedVariant> thatIt=that.mVariants.iterator();
while (thisIt.hasNext()) {
if (!thatIt.hasNext()) {
return 1;
}
final int future=thisIt.next().compareTo(thatIt.next());
if (future != 0) {
return future;
}
}
if (thatIt.hasNext()) {
return -1;
}
return 0;
}
| Performs a comparison of the variants in this path that aren't yet resolved. |
public PropertyChangeListener(IPreferenceStore preferenceStore){
setPreferenceStore(preferenceStore);
}
| Initialize with the given preference store. |
public void writePopulation(String outputfolder){
if (this.sc.getPopulation().getPersons().size() == 0 || this.personAttributes == null) {
throw new RuntimeException("Either no persons or person attributes to write.");
}
else {
LOG.info("Writing population to file...");
PopulationWriter pw=new PopulationWriter(this.sc.getPopulation(),this.sc.getNetwork());
pw.writeV5(outputfolder + "Population.xml");
LOG.info("Writing person attributes to file...");
ObjectAttributesXmlWriter oaw=new ObjectAttributesXmlWriter(this.personAttributes);
oaw.putAttributeConverter(IncomeImpl.class,new SAIncomeConverter());
oaw.setPrettyPrint(true);
oaw.writeFile(outputfolder + "PersonAttributes.xml");
}
}
| Writes the population and their attributes to file. |
public static String formatPixel(int pixel){
return String.format("0x%8s",Integer.toHexString(pixel)).replace(' ','0');
}
| Standard parsing of ARCG pixel (int) value to String |
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.shadowPaint,stream);
}
| Provides serialization support. |
public final void print(char[] buffer,int offset,int length) throws IOException {
if (_source == null) return;
printLatin1(buffer,offset,length);
}
| Prints the character buffer to the stream. |
public void write(String string){
int caretPosition=getCaretPosition();
if (caretPosition + string.length() > maxLength) {
string=string.substring(0,maxLength - caretPosition + 1);
}
int start=caretPosition;
int end=caretPosition + string.length();
setSelectionStart(start);
setSelectionEnd(end);
replaceSelection(string);
setSelectionStart(getCaretPosition());
color(start,end,getForeground());
}
| Write text to screen with current foregound color |
public SHA512(){
super();
}
| Create the engine. |
public PutResponseMessage(PutResponseMessage other){
if (other.isSetHeader()) {
this.header=new AsyncMessageHeader(other.header);
}
}
| Performs a deep copy on <i>other</i>. |
public void notifyThrottleDisposed(){
log.debug("notifyThrottleDisposed");
dispatchButton.setEnabled(false);
releaseButton.setEnabled(false);
progButton.setEnabled(false);
setButton.setEnabled(true);
addrSelector.setEnabled(true);
getRosterEntrySelector().setEnabled(true);
conRosterBox.setEnabled(true);
if (throttle != null) {
throttle.removePropertyChangeListener(this);
}
throttle=null;
rosterEntry=null;
notifyListenersOfThrottleRelease();
}
| Receive notification that an address has been release or dispatched. |
public boolean hasMappingAccessor(String attributeName){
return getMappingAccessor(attributeName,false) != null;
}
| INTERNAL: Returns true if we already have (processed) an accessor for the given attribute name. |
public boolean onKeyUp(int keyCode,KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK && mSlidingMenu.isMenuShowing()) {
showContent();
return true;
}
return false;
}
| On key up. |
public ColoredDataSeries(final HistogramBin[] bins){
this.data=bins;
}
| Create the data series. |
public DoubleMatrix2D solve(DoubleMatrix2D A,DoubleMatrix2D B){
return (A.rows() == A.columns() ? (lu(A).solve(B)) : (qr(A).solve(B)));
}
| Solves A*X = B. |
private ObjID(long objNum,UID space){
this.objNum=objNum;
this.space=space;
}
| Constructs an object identifier given data read from a stream. |
protected void inorder(TreeNode<E> root){
if (root == null) return;
inorder(root.left);
System.out.print(root.element + " ");
inorder(root.right);
}
| Inorder traversal from a subtree |
public static String rtrimWildcardTokens(String input){
return rtrimWildcardTokens(input,DEFAULT_PATH_SEPARATOR);
}
| removes from a pattern all tokens to the right containing wildcards |
public void notifySecondBitConflict(String conflict,int bitNum){
javax.swing.JOptionPane.showMessageDialog(null,"The second output bit, " + bitNum + ", is currently assigned to "+ conflict+ ". Turnout cannot be created as "+ "you specified.","C/MRI Assignment Conflict",javax.swing.JOptionPane.INFORMATION_MESSAGE,null);
}
| Public method to notify user when the second bit of a proposed two output bit turnout has a conflict with another assigned bit |
public void moveOrigin(int dx,int dy){
log.trace("Move origin to: " + origin);
origin.translate(handler.realignToGrid(false,dx),handler.realignToGrid(false,dy));
}
| AB: Moves the origin around the given delta x and delta y This method is mainly used by updatePanelAndScrollBars() to keep track of the panels size changes. |
static CodecReader filter(CodecReader reader) throws IOException {
reader=VersionFieldUpgrader.wrap(reader);
return reader;
}
| Return an "upgraded" view of the reader. |
public Object value(InternalContextAdapter context) throws MethodInvocationException {
Object left=jjtGetChild(0).value(context);
Object right=jjtGetChild(1).value(context);
if (left == null || right == null) {
rsvc.error((left == null ? "Left" : "Right") + " side (" + jjtGetChild((left == null ? 0 : 1)).literal()+ ") of subtraction operation has null value."+ " Operation not possible. "+ context.getCurrentTemplateName()+ " [line "+ getLine()+ ", column "+ getColumn()+ "]");
return null;
}
if (!(left instanceof Integer) || !(right instanceof Integer)) {
rsvc.error((!(left instanceof Integer) ? "Left" : "Right") + " side of subtraction operation is not a valid type. " + "Currently only integers (1,2,3...) and Integer type is supported. "+ context.getCurrentTemplateName()+ " [line "+ getLine()+ ", column "+ getColumn()+ "]");
return null;
}
return new Integer(((Integer)left).intValue() - ((Integer)right).intValue());
}
| computes the value of the subtraction. Currently limited to integers |
private void track(final String event,final JSONObject props){
if (props != null) {
trackOpt(event,props);
}
}
| Track an event with a set of properties |
public void notifyConsistThrottleFound(DccThrottle t){
this.consistThrottle=t;
for (int i=0; i < listeners.size(); i++) {
AddressListener l=listeners.get(i);
if (log.isDebugEnabled()) {
log.debug("Notify address listener of address change " + l.getClass());
}
l.notifyConsistAddressThrottleFound(t);
}
}
| Get notification that a consist throttle has been found as we requested. |
private void updateProgress(int progress){
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress=progress;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
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 void writeGolomb(int divisor,int value) throws IOException {
int q=value / divisor;
for (int i=0; i < q; i++) {
writeBit(true,MAX_PROBABILITY / 2);
}
writeBit(false,MAX_PROBABILITY / 2);
int r=value - q * divisor;
int bit=31 - Integer.numberOfLeadingZeros(divisor - 1);
if (r < ((2 << bit) - divisor)) {
bit--;
}
else {
r+=(2 << bit) - divisor;
}
for (; bit >= 0; bit--) {
writeBit(((r >>> bit) & 1) == 1,MAX_PROBABILITY / 2);
}
}
| Write the Golomb code of a value. |
public void testCloseStrategy() throws Throwable {
RecoveryStrategy strategy=RecoveryStrategies.CLOSE;
CopycatClient client=mock(CopycatClient.class);
strategy.recover(client);
verify(client).close();
}
| Tests the CLOSE recovery strategy. |
public static void removeSecondaryObjective(SecondaryObjective<?> objective){
secondaryObjectives.remove(objective);
}
| Remove secondary objective from list, if it is there |
public static CrusherRecipesOld smelting(){
return smeltingBase;
}
| Used to call methods addSmelting and getSmeltingResult. |
public X509Name(String dirName,X509NameEntryConverter converter){
this(DefaultReverse,DefaultLookUp,dirName,converter);
}
| Takes an X509 dir name as a string of the format "C=AU, ST=Victoria", or some such, converting it into an ordered set of name attributes with each string value being converted to its associated ASN.1 type using the passed in converter. |
protected void sequence_BindingIdentifierAsFormalParameter(ISerializationContext context,FormalParameter semanticObject){
if (errorAcceptor != null) {
if (transientValues.isValueTransient(semanticObject,TypesPackage.Literals.IDENTIFIABLE_ELEMENT__NAME) == ValueTransient.YES) errorAcceptor.accept(diagnosticProvider.createFeatureValueMissing(semanticObject,TypesPackage.Literals.IDENTIFIABLE_ELEMENT__NAME));
}
SequenceFeeder feeder=createSequencerFeeder(context,semanticObject);
feeder.accept(grammarAccess.getBindingIdentifierAsFormalParameterAccess().getNameBindingIdentifierParserRuleCall_0(),semanticObject.getName());
feeder.finish();
}
| Contexts: BindingIdentifierAsFormalParameter<Yield> returns FormalParameter BindingIdentifierAsFormalParameter returns FormalParameter Constraint: name=BindingIdentifier |
private void putPixel(WritableRaster raster,int x,int y,Color color){
raster.setPixel(x,y,new int[]{color.getRed(),color.getGreen(),color.getBlue()});
}
| put pixel |
public MyTableRowSorter(){
this(null);
}
| Creates a <code>TableRowSorter</code> with an empty model. |
private void showProgressPanel(){
m_panel.setEnabled(false);
}
| Shows the progress panel to the user. |
protected static void copyBoardInto(IHex[] dest,int destWidth,int x,int y,IBoard copied){
for (int i=0; i < copied.getHeight(); i++) {
for (int j=0; j < copied.getWidth(); j++) {
dest[(i + y) * destWidth + j + x]=copied.getHex(j,i);
}
}
}
| Copies the data of another board into given array of Hexes, offset by the specified x and y. |
private static boolean isTableFieldNode(Element node){
return (node.getAttributeValue(null,ATTRIBUTE_OPENMRS_ATTRIBUTE) != null && node.getAttributeValue(null,ATTRIBUTE_OPENMRS_TABLE) != null);
}
| Check whether a node is an openmrs table field node These are the ones with the attributes: openmrs_table and openmrs_attribute e.g. patient_unique_number openmrs_table="PATIENT_IDENTIFIER" openmrs_attribute="IDENTIFIER" |
public void launch(View view){
WebMediumConfig config=null;
if (launchType == LaunchType.Bot) {
config=new InstanceConfig();
}
else if (launchType == LaunchType.Forum) {
config=new ForumConfig();
}
else if (launchType == LaunchType.Channel) {
config=new ChannelConfig();
}
config.id=launchInstanceId;
config.name=launchInstanceName;
HttpAction action=new HttpFetchAction(this,config,true);
action.execute();
}
| Start a chat session with the hard coded instance. |
@Override public void filter(ClientRequestContext requestContext,ClientResponseContext responseContext) throws IOException {
long time=new Date().getTime();
TraceEvent traceEvent=(TraceEvent)requestContext.getProperty(TRACE_EVENT_ATTRIBUTE);
if (traceEvent != null) {
TraceEvent endTraceEvent=new TraceEvent(TracingConstants.CLIENT_TRACE_END,traceEvent.getTraceId(),traceEvent.getOriginId(),time);
endTraceEvent.setStatusCode(responseContext.getStatus());
TracingUtil.pushToDAS(endTraceEvent,dasUrl);
}
}
| Intercepts the client response flow and extract response information to be published to the DAS server for tracing. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.