id
int32 0
165k
| repo
stringlengths 7
58
| path
stringlengths 12
218
| func_name
stringlengths 3
140
| original_string
stringlengths 73
34.1k
| language
stringclasses 1
value | code
stringlengths 73
34.1k
| code_tokens
sequence | docstring
stringlengths 3
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 105
339
|
---|---|---|---|---|---|---|---|---|---|---|---|
500 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.startMetricsThread | private void startMetricsThread() {
LOG.info("Starting periodic Metrics Emitter thread, frequency = " + METRICS_POLL_INTERVAL);
this.metricsThread = new DaemonThreadExecutor("tx-metrics") {
@Override
public void doRun() {
txMetricsCollector.gauge("committing.size", committingChangeSets.size());
txMetricsCollector.gauge("committed.size", committedChangeSets.size());
txMetricsCollector.gauge("inprogress.size", inProgress.size());
txMetricsCollector.gauge("invalid.size", invalidArray.length);
}
@Override
protected void onShutdown() {
// perform a final metrics emit
txMetricsCollector.gauge("committing.size", committingChangeSets.size());
txMetricsCollector.gauge("committed.size", committedChangeSets.size());
txMetricsCollector.gauge("inprogress.size", inProgress.size());
txMetricsCollector.gauge("invalid.size", invalidArray.length);
}
@Override
public long getSleepMillis() {
return METRICS_POLL_INTERVAL;
}
};
metricsThread.start();
} | java | private void startMetricsThread() {
LOG.info("Starting periodic Metrics Emitter thread, frequency = " + METRICS_POLL_INTERVAL);
this.metricsThread = new DaemonThreadExecutor("tx-metrics") {
@Override
public void doRun() {
txMetricsCollector.gauge("committing.size", committingChangeSets.size());
txMetricsCollector.gauge("committed.size", committedChangeSets.size());
txMetricsCollector.gauge("inprogress.size", inProgress.size());
txMetricsCollector.gauge("invalid.size", invalidArray.length);
}
@Override
protected void onShutdown() {
// perform a final metrics emit
txMetricsCollector.gauge("committing.size", committingChangeSets.size());
txMetricsCollector.gauge("committed.size", committedChangeSets.size());
txMetricsCollector.gauge("inprogress.size", inProgress.size());
txMetricsCollector.gauge("invalid.size", invalidArray.length);
}
@Override
public long getSleepMillis() {
return METRICS_POLL_INTERVAL;
}
};
metricsThread.start();
} | [
"private",
"void",
"startMetricsThread",
"(",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Starting periodic Metrics Emitter thread, frequency = \"",
"+",
"METRICS_POLL_INTERVAL",
")",
";",
"this",
".",
"metricsThread",
"=",
"new",
"DaemonThreadExecutor",
"(",
"\"tx-metrics\"",
")",
"{",
"@",
"Override",
"public",
"void",
"doRun",
"(",
")",
"{",
"txMetricsCollector",
".",
"gauge",
"(",
"\"committing.size\"",
",",
"committingChangeSets",
".",
"size",
"(",
")",
")",
";",
"txMetricsCollector",
".",
"gauge",
"(",
"\"committed.size\"",
",",
"committedChangeSets",
".",
"size",
"(",
")",
")",
";",
"txMetricsCollector",
".",
"gauge",
"(",
"\"inprogress.size\"",
",",
"inProgress",
".",
"size",
"(",
")",
")",
";",
"txMetricsCollector",
".",
"gauge",
"(",
"\"invalid.size\"",
",",
"invalidArray",
".",
"length",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onShutdown",
"(",
")",
"{",
"// perform a final metrics emit",
"txMetricsCollector",
".",
"gauge",
"(",
"\"committing.size\"",
",",
"committingChangeSets",
".",
"size",
"(",
")",
")",
";",
"txMetricsCollector",
".",
"gauge",
"(",
"\"committed.size\"",
",",
"committedChangeSets",
".",
"size",
"(",
")",
")",
";",
"txMetricsCollector",
".",
"gauge",
"(",
"\"inprogress.size\"",
",",
"inProgress",
".",
"size",
"(",
")",
")",
";",
"txMetricsCollector",
".",
"gauge",
"(",
"\"invalid.size\"",
",",
"invalidArray",
".",
"length",
")",
";",
"}",
"@",
"Override",
"public",
"long",
"getSleepMillis",
"(",
")",
"{",
"return",
"METRICS_POLL_INTERVAL",
";",
"}",
"}",
";",
"metricsThread",
".",
"start",
"(",
")",
";",
"}"
] | Emits Transaction Data structures size as metrics | [
"Emits",
"Transaction",
"Data",
"structures",
"size",
"as",
"metrics"
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L307-L333 |
501 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.takeSnapshot | public boolean takeSnapshot(OutputStream out) throws IOException {
TransactionSnapshot snapshot = getSnapshot();
if (snapshot != null) {
persistor.writeSnapshot(out, snapshot);
return true;
} else {
return false;
}
} | java | public boolean takeSnapshot(OutputStream out) throws IOException {
TransactionSnapshot snapshot = getSnapshot();
if (snapshot != null) {
persistor.writeSnapshot(out, snapshot);
return true;
} else {
return false;
}
} | [
"public",
"boolean",
"takeSnapshot",
"(",
"OutputStream",
"out",
")",
"throws",
"IOException",
"{",
"TransactionSnapshot",
"snapshot",
"=",
"getSnapshot",
"(",
")",
";",
"if",
"(",
"snapshot",
"!=",
"null",
")",
"{",
"persistor",
".",
"writeSnapshot",
"(",
"out",
",",
"snapshot",
")",
";",
"return",
"true",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}"
] | Take a snapshot of the transaction state and serialize it into the given output stream.
@return whether a snapshot was taken. | [
"Take",
"a",
"snapshot",
"of",
"the",
"transaction",
"state",
"and",
"serialize",
"it",
"into",
"the",
"given",
"output",
"stream",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L407-L415 |
502 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.restoreSnapshot | private void restoreSnapshot(TransactionSnapshot snapshot) {
LOG.info("Restoring transaction state from snapshot at " + snapshot.getTimestamp());
Preconditions.checkState(lastSnapshotTime == 0, "lastSnapshotTime has been set!");
Preconditions.checkState(readPointer == 0, "readPointer has been set!");
Preconditions.checkState(lastWritePointer == 0, "lastWritePointer has been set!");
Preconditions.checkState(invalid.isEmpty(), "invalid list should be empty!");
Preconditions.checkState(inProgress.isEmpty(), "inProgress map should be empty!");
Preconditions.checkState(committingChangeSets.isEmpty(), "committingChangeSets should be empty!");
Preconditions.checkState(committedChangeSets.isEmpty(), "committedChangeSets should be empty!");
LOG.info("Restoring snapshot of state: " + snapshot);
lastSnapshotTime = snapshot.getTimestamp();
readPointer = snapshot.getReadPointer();
lastWritePointer = snapshot.getWritePointer();
invalid.addAll(snapshot.getInvalid());
inProgress.putAll(txnBackwardsCompatCheck(defaultLongTimeout, longTimeoutTolerance, snapshot.getInProgress()));
committingChangeSets.putAll(snapshot.getCommittingChangeSets());
committedChangeSets.putAll(snapshot.getCommittedChangeSets());
} | java | private void restoreSnapshot(TransactionSnapshot snapshot) {
LOG.info("Restoring transaction state from snapshot at " + snapshot.getTimestamp());
Preconditions.checkState(lastSnapshotTime == 0, "lastSnapshotTime has been set!");
Preconditions.checkState(readPointer == 0, "readPointer has been set!");
Preconditions.checkState(lastWritePointer == 0, "lastWritePointer has been set!");
Preconditions.checkState(invalid.isEmpty(), "invalid list should be empty!");
Preconditions.checkState(inProgress.isEmpty(), "inProgress map should be empty!");
Preconditions.checkState(committingChangeSets.isEmpty(), "committingChangeSets should be empty!");
Preconditions.checkState(committedChangeSets.isEmpty(), "committedChangeSets should be empty!");
LOG.info("Restoring snapshot of state: " + snapshot);
lastSnapshotTime = snapshot.getTimestamp();
readPointer = snapshot.getReadPointer();
lastWritePointer = snapshot.getWritePointer();
invalid.addAll(snapshot.getInvalid());
inProgress.putAll(txnBackwardsCompatCheck(defaultLongTimeout, longTimeoutTolerance, snapshot.getInProgress()));
committingChangeSets.putAll(snapshot.getCommittingChangeSets());
committedChangeSets.putAll(snapshot.getCommittedChangeSets());
} | [
"private",
"void",
"restoreSnapshot",
"(",
"TransactionSnapshot",
"snapshot",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Restoring transaction state from snapshot at \"",
"+",
"snapshot",
".",
"getTimestamp",
"(",
")",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"lastSnapshotTime",
"==",
"0",
",",
"\"lastSnapshotTime has been set!\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"readPointer",
"==",
"0",
",",
"\"readPointer has been set!\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"lastWritePointer",
"==",
"0",
",",
"\"lastWritePointer has been set!\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"invalid",
".",
"isEmpty",
"(",
")",
",",
"\"invalid list should be empty!\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"inProgress",
".",
"isEmpty",
"(",
")",
",",
"\"inProgress map should be empty!\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"committingChangeSets",
".",
"isEmpty",
"(",
")",
",",
"\"committingChangeSets should be empty!\"",
")",
";",
"Preconditions",
".",
"checkState",
"(",
"committedChangeSets",
".",
"isEmpty",
"(",
")",
",",
"\"committedChangeSets should be empty!\"",
")",
";",
"LOG",
".",
"info",
"(",
"\"Restoring snapshot of state: \"",
"+",
"snapshot",
")",
";",
"lastSnapshotTime",
"=",
"snapshot",
".",
"getTimestamp",
"(",
")",
";",
"readPointer",
"=",
"snapshot",
".",
"getReadPointer",
"(",
")",
";",
"lastWritePointer",
"=",
"snapshot",
".",
"getWritePointer",
"(",
")",
";",
"invalid",
".",
"addAll",
"(",
"snapshot",
".",
"getInvalid",
"(",
")",
")",
";",
"inProgress",
".",
"putAll",
"(",
"txnBackwardsCompatCheck",
"(",
"defaultLongTimeout",
",",
"longTimeoutTolerance",
",",
"snapshot",
".",
"getInProgress",
"(",
")",
")",
")",
";",
"committingChangeSets",
".",
"putAll",
"(",
"snapshot",
".",
"getCommittingChangeSets",
"(",
")",
")",
";",
"committedChangeSets",
".",
"putAll",
"(",
"snapshot",
".",
"getCommittedChangeSets",
"(",
")",
")",
";",
"}"
] | Restore the initial in-memory transaction state from a snapshot. | [
"Restore",
"the",
"initial",
"in",
"-",
"memory",
"transaction",
"state",
"from",
"a",
"snapshot",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L487-L505 |
503 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.txnBackwardsCompatCheck | public static Map<Long, InProgressTx> txnBackwardsCompatCheck(int defaultLongTimeout, long longTimeoutTolerance,
Map<Long, InProgressTx> inProgress) {
for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) {
long writePointer = entry.getKey();
long expiration = entry.getValue().getExpiration();
// LONG transactions will either have a negative expiration or expiration set to the long timeout
// use a fudge factor on the expiration check, since expiraton is set based on system time, not the write pointer
if (entry.getValue().getType() == null &&
(expiration < 0 ||
(getTxExpirationFromWritePointer(writePointer, defaultLongTimeout) - expiration
< longTimeoutTolerance))) {
// handle null expiration
long newExpiration = getTxExpirationFromWritePointer(writePointer, defaultLongTimeout);
InProgressTx compatTx =
new InProgressTx(entry.getValue().getVisibilityUpperBound(), newExpiration, TransactionType.LONG,
entry.getValue().getCheckpointWritePointers());
entry.setValue(compatTx);
} else if (entry.getValue().getType() == null) {
InProgressTx compatTx =
new InProgressTx(entry.getValue().getVisibilityUpperBound(), entry.getValue().getExpiration(),
TransactionType.SHORT, entry.getValue().getCheckpointWritePointers());
entry.setValue(compatTx);
}
}
return inProgress;
} | java | public static Map<Long, InProgressTx> txnBackwardsCompatCheck(int defaultLongTimeout, long longTimeoutTolerance,
Map<Long, InProgressTx> inProgress) {
for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) {
long writePointer = entry.getKey();
long expiration = entry.getValue().getExpiration();
// LONG transactions will either have a negative expiration or expiration set to the long timeout
// use a fudge factor on the expiration check, since expiraton is set based on system time, not the write pointer
if (entry.getValue().getType() == null &&
(expiration < 0 ||
(getTxExpirationFromWritePointer(writePointer, defaultLongTimeout) - expiration
< longTimeoutTolerance))) {
// handle null expiration
long newExpiration = getTxExpirationFromWritePointer(writePointer, defaultLongTimeout);
InProgressTx compatTx =
new InProgressTx(entry.getValue().getVisibilityUpperBound(), newExpiration, TransactionType.LONG,
entry.getValue().getCheckpointWritePointers());
entry.setValue(compatTx);
} else if (entry.getValue().getType() == null) {
InProgressTx compatTx =
new InProgressTx(entry.getValue().getVisibilityUpperBound(), entry.getValue().getExpiration(),
TransactionType.SHORT, entry.getValue().getCheckpointWritePointers());
entry.setValue(compatTx);
}
}
return inProgress;
} | [
"public",
"static",
"Map",
"<",
"Long",
",",
"InProgressTx",
">",
"txnBackwardsCompatCheck",
"(",
"int",
"defaultLongTimeout",
",",
"long",
"longTimeoutTolerance",
",",
"Map",
"<",
"Long",
",",
"InProgressTx",
">",
"inProgress",
")",
"{",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Long",
",",
"InProgressTx",
">",
"entry",
":",
"inProgress",
".",
"entrySet",
"(",
")",
")",
"{",
"long",
"writePointer",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"long",
"expiration",
"=",
"entry",
".",
"getValue",
"(",
")",
".",
"getExpiration",
"(",
")",
";",
"// LONG transactions will either have a negative expiration or expiration set to the long timeout",
"// use a fudge factor on the expiration check, since expiraton is set based on system time, not the write pointer",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
".",
"getType",
"(",
")",
"==",
"null",
"&&",
"(",
"expiration",
"<",
"0",
"||",
"(",
"getTxExpirationFromWritePointer",
"(",
"writePointer",
",",
"defaultLongTimeout",
")",
"-",
"expiration",
"<",
"longTimeoutTolerance",
")",
")",
")",
"{",
"// handle null expiration",
"long",
"newExpiration",
"=",
"getTxExpirationFromWritePointer",
"(",
"writePointer",
",",
"defaultLongTimeout",
")",
";",
"InProgressTx",
"compatTx",
"=",
"new",
"InProgressTx",
"(",
"entry",
".",
"getValue",
"(",
")",
".",
"getVisibilityUpperBound",
"(",
")",
",",
"newExpiration",
",",
"TransactionType",
".",
"LONG",
",",
"entry",
".",
"getValue",
"(",
")",
".",
"getCheckpointWritePointers",
"(",
")",
")",
";",
"entry",
".",
"setValue",
"(",
"compatTx",
")",
";",
"}",
"else",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
".",
"getType",
"(",
")",
"==",
"null",
")",
"{",
"InProgressTx",
"compatTx",
"=",
"new",
"InProgressTx",
"(",
"entry",
".",
"getValue",
"(",
")",
".",
"getVisibilityUpperBound",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
".",
"getExpiration",
"(",
")",
",",
"TransactionType",
".",
"SHORT",
",",
"entry",
".",
"getValue",
"(",
")",
".",
"getCheckpointWritePointers",
"(",
")",
")",
";",
"entry",
".",
"setValue",
"(",
"compatTx",
")",
";",
"}",
"}",
"return",
"inProgress",
";",
"}"
] | Check if in-progress transactions need to be migrated to have expiration time and type, if so do the migration.
This is required for backwards compatibility, when long running transactions were represented
with expiration time -1. This can be removed when we stop supporting SnapshotCodec version 1. | [
"Check",
"if",
"in",
"-",
"progress",
"transactions",
"need",
"to",
"be",
"migrated",
"to",
"have",
"expiration",
"time",
"and",
"type",
"if",
"so",
"do",
"the",
"migration",
".",
"This",
"is",
"required",
"for",
"backwards",
"compatibility",
"when",
"long",
"running",
"transactions",
"were",
"represented",
"with",
"expiration",
"time",
"-",
"1",
".",
"This",
"can",
"be",
"removed",
"when",
"we",
"stop",
"supporting",
"SnapshotCodec",
"version",
"1",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L512-L537 |
504 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.resetState | public void resetState() {
this.logWriteLock.lock();
try {
// Take a snapshot before resetting the state, for debugging purposes
doSnapshot(false);
// Clear the state
clear();
// Take another snapshot: if no snapshot is taken after clearing the state
// and the manager is restarted, we will recover from the snapshot taken
// before resetting the state, which would be really bad
// This call will also init a new WAL
doSnapshot(false);
} catch (IOException e) {
LOG.error("Snapshot failed when resetting state!", e);
e.printStackTrace();
} finally {
this.logWriteLock.unlock();
}
} | java | public void resetState() {
this.logWriteLock.lock();
try {
// Take a snapshot before resetting the state, for debugging purposes
doSnapshot(false);
// Clear the state
clear();
// Take another snapshot: if no snapshot is taken after clearing the state
// and the manager is restarted, we will recover from the snapshot taken
// before resetting the state, which would be really bad
// This call will also init a new WAL
doSnapshot(false);
} catch (IOException e) {
LOG.error("Snapshot failed when resetting state!", e);
e.printStackTrace();
} finally {
this.logWriteLock.unlock();
}
} | [
"public",
"void",
"resetState",
"(",
")",
"{",
"this",
".",
"logWriteLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"// Take a snapshot before resetting the state, for debugging purposes",
"doSnapshot",
"(",
"false",
")",
";",
"// Clear the state",
"clear",
"(",
")",
";",
"// Take another snapshot: if no snapshot is taken after clearing the state",
"// and the manager is restarted, we will recover from the snapshot taken",
"// before resetting the state, which would be really bad",
"// This call will also init a new WAL",
"doSnapshot",
"(",
"false",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Snapshot failed when resetting state!\"",
",",
"e",
")",
";",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"finally",
"{",
"this",
".",
"logWriteLock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Resets the state of the transaction manager. | [
"Resets",
"the",
"state",
"of",
"the",
"transaction",
"manager",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L542-L560 |
505 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.abortService | private void abortService(String message, Throwable error) {
if (isRunning()) {
LOG.error("Aborting transaction manager due to: " + message, error);
notifyFailed(error);
}
} | java | private void abortService(String message, Throwable error) {
if (isRunning()) {
LOG.error("Aborting transaction manager due to: " + message, error);
notifyFailed(error);
}
} | [
"private",
"void",
"abortService",
"(",
"String",
"message",
",",
"Throwable",
"error",
")",
"{",
"if",
"(",
"isRunning",
"(",
")",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Aborting transaction manager due to: \"",
"+",
"message",
",",
"error",
")",
";",
"notifyFailed",
"(",
"error",
")",
";",
"}",
"}"
] | Immediately shuts down the service, without going through the normal close process.
@param message A message describing the source of the failure.
@param error Any exception that caused the failure. | [
"Immediately",
"shuts",
"down",
"the",
"service",
"without",
"going",
"through",
"the",
"normal",
"close",
"process",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L699-L704 |
506 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.startShort | public Transaction startShort(int timeoutInSeconds) {
Preconditions.checkArgument(timeoutInSeconds > 0, "timeout must be positive but is %s", timeoutInSeconds);
txMetricsCollector.rate("start.short");
Stopwatch timer = new Stopwatch().start();
long expiration = getTxExpiration(timeoutInSeconds);
Transaction tx = startTx(expiration, TransactionType.SHORT);
txMetricsCollector.histogram("start.short.latency", (int) timer.elapsedMillis());
return tx;
} | java | public Transaction startShort(int timeoutInSeconds) {
Preconditions.checkArgument(timeoutInSeconds > 0, "timeout must be positive but is %s", timeoutInSeconds);
txMetricsCollector.rate("start.short");
Stopwatch timer = new Stopwatch().start();
long expiration = getTxExpiration(timeoutInSeconds);
Transaction tx = startTx(expiration, TransactionType.SHORT);
txMetricsCollector.histogram("start.short.latency", (int) timer.elapsedMillis());
return tx;
} | [
"public",
"Transaction",
"startShort",
"(",
"int",
"timeoutInSeconds",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"timeoutInSeconds",
">",
"0",
",",
"\"timeout must be positive but is %s\"",
",",
"timeoutInSeconds",
")",
";",
"txMetricsCollector",
".",
"rate",
"(",
"\"start.short\"",
")",
";",
"Stopwatch",
"timer",
"=",
"new",
"Stopwatch",
"(",
")",
".",
"start",
"(",
")",
";",
"long",
"expiration",
"=",
"getTxExpiration",
"(",
"timeoutInSeconds",
")",
";",
"Transaction",
"tx",
"=",
"startTx",
"(",
"expiration",
",",
"TransactionType",
".",
"SHORT",
")",
";",
"txMetricsCollector",
".",
"histogram",
"(",
"\"start.short.latency\"",
",",
"(",
"int",
")",
"timer",
".",
"elapsedMillis",
"(",
")",
")",
";",
"return",
"tx",
";",
"}"
] | Start a short transaction with a given timeout.
@param timeoutInSeconds the time out period in seconds. | [
"Start",
"a",
"short",
"transaction",
"with",
"a",
"given",
"timeout",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L721-L729 |
507 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.startLong | public Transaction startLong() {
txMetricsCollector.rate("start.long");
Stopwatch timer = new Stopwatch().start();
long expiration = getTxExpiration(defaultLongTimeout);
Transaction tx = startTx(expiration, TransactionType.LONG);
txMetricsCollector.histogram("start.long.latency", (int) timer.elapsedMillis());
return tx;
} | java | public Transaction startLong() {
txMetricsCollector.rate("start.long");
Stopwatch timer = new Stopwatch().start();
long expiration = getTxExpiration(defaultLongTimeout);
Transaction tx = startTx(expiration, TransactionType.LONG);
txMetricsCollector.histogram("start.long.latency", (int) timer.elapsedMillis());
return tx;
} | [
"public",
"Transaction",
"startLong",
"(",
")",
"{",
"txMetricsCollector",
".",
"rate",
"(",
"\"start.long\"",
")",
";",
"Stopwatch",
"timer",
"=",
"new",
"Stopwatch",
"(",
")",
".",
"start",
"(",
")",
";",
"long",
"expiration",
"=",
"getTxExpiration",
"(",
"defaultLongTimeout",
")",
";",
"Transaction",
"tx",
"=",
"startTx",
"(",
"expiration",
",",
"TransactionType",
".",
"LONG",
")",
";",
"txMetricsCollector",
".",
"histogram",
"(",
"\"start.long.latency\"",
",",
"(",
"int",
")",
"timer",
".",
"elapsedMillis",
"(",
")",
")",
";",
"return",
"tx",
";",
"}"
] | Start a long transaction. Long transactions and do not participate in conflict detection. Also, aborting a long
transaction moves it to the invalid list because we assume that its writes cannot be rolled back. | [
"Start",
"a",
"long",
"transaction",
".",
"Long",
"transactions",
"and",
"do",
"not",
"participate",
"in",
"conflict",
"detection",
".",
"Also",
"aborting",
"a",
"long",
"transaction",
"moves",
"it",
"to",
"the",
"invalid",
"list",
"because",
"we",
"assume",
"that",
"its",
"writes",
"cannot",
"be",
"rolled",
"back",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L750-L757 |
508 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.truncateInvalidTx | public boolean truncateInvalidTx(Set<Long> invalidTxIds) {
// guard against changes to the transaction log while processing
txMetricsCollector.rate("truncateInvalidTx");
Stopwatch timer = new Stopwatch().start();
this.logReadLock.lock();
try {
boolean success;
synchronized (this) {
ensureAvailable();
success = doTruncateInvalidTx(invalidTxIds);
}
appendToLog(TransactionEdit.createTruncateInvalidTx(invalidTxIds));
txMetricsCollector.histogram("truncateInvalidTx.latency", (int) timer.elapsedMillis());
return success;
} finally {
this.logReadLock.unlock();
}
} | java | public boolean truncateInvalidTx(Set<Long> invalidTxIds) {
// guard against changes to the transaction log while processing
txMetricsCollector.rate("truncateInvalidTx");
Stopwatch timer = new Stopwatch().start();
this.logReadLock.lock();
try {
boolean success;
synchronized (this) {
ensureAvailable();
success = doTruncateInvalidTx(invalidTxIds);
}
appendToLog(TransactionEdit.createTruncateInvalidTx(invalidTxIds));
txMetricsCollector.histogram("truncateInvalidTx.latency", (int) timer.elapsedMillis());
return success;
} finally {
this.logReadLock.unlock();
}
} | [
"public",
"boolean",
"truncateInvalidTx",
"(",
"Set",
"<",
"Long",
">",
"invalidTxIds",
")",
"{",
"// guard against changes to the transaction log while processing",
"txMetricsCollector",
".",
"rate",
"(",
"\"truncateInvalidTx\"",
")",
";",
"Stopwatch",
"timer",
"=",
"new",
"Stopwatch",
"(",
")",
".",
"start",
"(",
")",
";",
"this",
".",
"logReadLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"boolean",
"success",
";",
"synchronized",
"(",
"this",
")",
"{",
"ensureAvailable",
"(",
")",
";",
"success",
"=",
"doTruncateInvalidTx",
"(",
"invalidTxIds",
")",
";",
"}",
"appendToLog",
"(",
"TransactionEdit",
".",
"createTruncateInvalidTx",
"(",
"invalidTxIds",
")",
")",
";",
"txMetricsCollector",
".",
"histogram",
"(",
"\"truncateInvalidTx.latency\"",
",",
"(",
"int",
")",
"timer",
".",
"elapsedMillis",
"(",
")",
")",
";",
"return",
"success",
";",
"}",
"finally",
"{",
"this",
".",
"logReadLock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Removes the given transaction ids from the invalid list.
@param invalidTxIds transaction ids
@return true if invalid list got changed, false otherwise | [
"Removes",
"the",
"given",
"transaction",
"ids",
"from",
"the",
"invalid",
"list",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L1029-L1046 |
509 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.truncateInvalidTxBefore | public boolean truncateInvalidTxBefore(long time) throws InvalidTruncateTimeException {
// guard against changes to the transaction log while processing
txMetricsCollector.rate("truncateInvalidTxBefore");
Stopwatch timer = new Stopwatch().start();
this.logReadLock.lock();
try {
boolean success;
synchronized (this) {
ensureAvailable();
success = doTruncateInvalidTxBefore(time);
}
appendToLog(TransactionEdit.createTruncateInvalidTxBefore(time));
txMetricsCollector.histogram("truncateInvalidTxBefore.latency", (int) timer.elapsedMillis());
return success;
} finally {
this.logReadLock.unlock();
}
} | java | public boolean truncateInvalidTxBefore(long time) throws InvalidTruncateTimeException {
// guard against changes to the transaction log while processing
txMetricsCollector.rate("truncateInvalidTxBefore");
Stopwatch timer = new Stopwatch().start();
this.logReadLock.lock();
try {
boolean success;
synchronized (this) {
ensureAvailable();
success = doTruncateInvalidTxBefore(time);
}
appendToLog(TransactionEdit.createTruncateInvalidTxBefore(time));
txMetricsCollector.histogram("truncateInvalidTxBefore.latency", (int) timer.elapsedMillis());
return success;
} finally {
this.logReadLock.unlock();
}
} | [
"public",
"boolean",
"truncateInvalidTxBefore",
"(",
"long",
"time",
")",
"throws",
"InvalidTruncateTimeException",
"{",
"// guard against changes to the transaction log while processing",
"txMetricsCollector",
".",
"rate",
"(",
"\"truncateInvalidTxBefore\"",
")",
";",
"Stopwatch",
"timer",
"=",
"new",
"Stopwatch",
"(",
")",
".",
"start",
"(",
")",
";",
"this",
".",
"logReadLock",
".",
"lock",
"(",
")",
";",
"try",
"{",
"boolean",
"success",
";",
"synchronized",
"(",
"this",
")",
"{",
"ensureAvailable",
"(",
")",
";",
"success",
"=",
"doTruncateInvalidTxBefore",
"(",
"time",
")",
";",
"}",
"appendToLog",
"(",
"TransactionEdit",
".",
"createTruncateInvalidTxBefore",
"(",
"time",
")",
")",
";",
"txMetricsCollector",
".",
"histogram",
"(",
"\"truncateInvalidTxBefore.latency\"",
",",
"(",
"int",
")",
"timer",
".",
"elapsedMillis",
"(",
")",
")",
";",
"return",
"success",
";",
"}",
"finally",
"{",
"this",
".",
"logReadLock",
".",
"unlock",
"(",
")",
";",
"}",
"}"
] | Removes all transaction ids started before the given time from invalid list.
@param time time in milliseconds
@return true if invalid list got changed, false otherwise
@throws InvalidTruncateTimeException if there are any in-progress transactions started before given time | [
"Removes",
"all",
"transaction",
"ids",
"started",
"before",
"the",
"given",
"time",
"from",
"invalid",
"list",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L1063-L1080 |
510 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.createTransaction | private Transaction createTransaction(long writePointer, TransactionType type) {
// For holding the first in progress short transaction Id (with timeout >= 0).
long firstShortTx = Transaction.NO_TX_IN_PROGRESS;
LongArrayList inProgressIds = new LongArrayList(inProgress.size());
for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) {
long txId = entry.getKey();
inProgressIds.add(txId);
// add any checkpointed write pointers to the in-progress list
LongArrayList childIds = entry.getValue().getCheckpointWritePointers();
if (childIds != null) {
for (int i = 0; i < childIds.size(); i++) {
inProgressIds.add(childIds.get(i));
}
}
if (firstShortTx == Transaction.NO_TX_IN_PROGRESS && !entry.getValue().isLongRunning()) {
firstShortTx = txId;
}
}
return new Transaction(readPointer, writePointer, invalidArray, inProgressIds.toLongArray(), firstShortTx, type);
} | java | private Transaction createTransaction(long writePointer, TransactionType type) {
// For holding the first in progress short transaction Id (with timeout >= 0).
long firstShortTx = Transaction.NO_TX_IN_PROGRESS;
LongArrayList inProgressIds = new LongArrayList(inProgress.size());
for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) {
long txId = entry.getKey();
inProgressIds.add(txId);
// add any checkpointed write pointers to the in-progress list
LongArrayList childIds = entry.getValue().getCheckpointWritePointers();
if (childIds != null) {
for (int i = 0; i < childIds.size(); i++) {
inProgressIds.add(childIds.get(i));
}
}
if (firstShortTx == Transaction.NO_TX_IN_PROGRESS && !entry.getValue().isLongRunning()) {
firstShortTx = txId;
}
}
return new Transaction(readPointer, writePointer, invalidArray, inProgressIds.toLongArray(), firstShortTx, type);
} | [
"private",
"Transaction",
"createTransaction",
"(",
"long",
"writePointer",
",",
"TransactionType",
"type",
")",
"{",
"// For holding the first in progress short transaction Id (with timeout >= 0).",
"long",
"firstShortTx",
"=",
"Transaction",
".",
"NO_TX_IN_PROGRESS",
";",
"LongArrayList",
"inProgressIds",
"=",
"new",
"LongArrayList",
"(",
"inProgress",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Long",
",",
"InProgressTx",
">",
"entry",
":",
"inProgress",
".",
"entrySet",
"(",
")",
")",
"{",
"long",
"txId",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"inProgressIds",
".",
"add",
"(",
"txId",
")",
";",
"// add any checkpointed write pointers to the in-progress list",
"LongArrayList",
"childIds",
"=",
"entry",
".",
"getValue",
"(",
")",
".",
"getCheckpointWritePointers",
"(",
")",
";",
"if",
"(",
"childIds",
"!=",
"null",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"childIds",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"inProgressIds",
".",
"add",
"(",
"childIds",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"}",
"if",
"(",
"firstShortTx",
"==",
"Transaction",
".",
"NO_TX_IN_PROGRESS",
"&&",
"!",
"entry",
".",
"getValue",
"(",
")",
".",
"isLongRunning",
"(",
")",
")",
"{",
"firstShortTx",
"=",
"txId",
";",
"}",
"}",
"return",
"new",
"Transaction",
"(",
"readPointer",
",",
"writePointer",
",",
"invalidArray",
",",
"inProgressIds",
".",
"toLongArray",
"(",
")",
",",
"firstShortTx",
",",
"type",
")",
";",
"}"
] | Creates a new Transaction. This method only get called from start transaction, which is already
synchronized. | [
"Creates",
"a",
"new",
"Transaction",
".",
"This",
"method",
"only",
"get",
"called",
"from",
"start",
"transaction",
"which",
"is",
"already",
"synchronized",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L1210-L1230 |
511 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionManager.java | TransactionManager.logStatistics | public void logStatistics() {
LOG.info("Transaction Statistics: write pointer = " + lastWritePointer +
", invalid = " + invalid.size() +
", in progress = " + inProgress.size() +
", committing = " + committingChangeSets.size() +
", committed = " + committedChangeSets.size());
} | java | public void logStatistics() {
LOG.info("Transaction Statistics: write pointer = " + lastWritePointer +
", invalid = " + invalid.size() +
", in progress = " + inProgress.size() +
", committing = " + committingChangeSets.size() +
", committed = " + committedChangeSets.size());
} | [
"public",
"void",
"logStatistics",
"(",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Transaction Statistics: write pointer = \"",
"+",
"lastWritePointer",
"+",
"\", invalid = \"",
"+",
"invalid",
".",
"size",
"(",
")",
"+",
"\", in progress = \"",
"+",
"inProgress",
".",
"size",
"(",
")",
"+",
"\", committing = \"",
"+",
"committingChangeSets",
".",
"size",
"(",
")",
"+",
"\", committed = \"",
"+",
"committedChangeSets",
".",
"size",
"(",
")",
")",
";",
"}"
] | Called from the tx service every 10 seconds.
This hack is needed because current metrics system is not flexible when it comes to adding new metrics. | [
"Called",
"from",
"the",
"tx",
"service",
"every",
"10",
"seconds",
".",
"This",
"hack",
"is",
"needed",
"because",
"current",
"metrics",
"system",
"is",
"not",
"flexible",
"when",
"it",
"comes",
"to",
"adding",
"new",
"metrics",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionManager.java#L1258-L1264 |
512 | cdapio/tephra | tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java | BalanceBooks.init | public void init() throws IOException {
Injector injector = Guice.createInjector(
new ConfigModule(conf),
new ZKModule(),
new DiscoveryModules().getDistributedModules(),
new TransactionModules().getDistributedModules(),
new TransactionClientModule()
);
zkClient = injector.getInstance(ZKClientService.class);
zkClient.startAndWait();
txClient = injector.getInstance(TransactionServiceClient.class);
createTableIfNotExists(conf, TABLE, new byte[][]{ FAMILY });
conn = HConnectionManager.createConnection(conf);
} | java | public void init() throws IOException {
Injector injector = Guice.createInjector(
new ConfigModule(conf),
new ZKModule(),
new DiscoveryModules().getDistributedModules(),
new TransactionModules().getDistributedModules(),
new TransactionClientModule()
);
zkClient = injector.getInstance(ZKClientService.class);
zkClient.startAndWait();
txClient = injector.getInstance(TransactionServiceClient.class);
createTableIfNotExists(conf, TABLE, new byte[][]{ FAMILY });
conn = HConnectionManager.createConnection(conf);
} | [
"public",
"void",
"init",
"(",
")",
"throws",
"IOException",
"{",
"Injector",
"injector",
"=",
"Guice",
".",
"createInjector",
"(",
"new",
"ConfigModule",
"(",
"conf",
")",
",",
"new",
"ZKModule",
"(",
")",
",",
"new",
"DiscoveryModules",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"TransactionModules",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"TransactionClientModule",
"(",
")",
")",
";",
"zkClient",
"=",
"injector",
".",
"getInstance",
"(",
"ZKClientService",
".",
"class",
")",
";",
"zkClient",
".",
"startAndWait",
"(",
")",
";",
"txClient",
"=",
"injector",
".",
"getInstance",
"(",
"TransactionServiceClient",
".",
"class",
")",
";",
"createTableIfNotExists",
"(",
"conf",
",",
"TABLE",
",",
"new",
"byte",
"[",
"]",
"[",
"]",
"{",
"FAMILY",
"}",
")",
";",
"conn",
"=",
"HConnectionManager",
".",
"createConnection",
"(",
"conf",
")",
";",
"}"
] | Sets up common resources required by all clients. | [
"Sets",
"up",
"common",
"resources",
"required",
"by",
"all",
"clients",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java#L104-L119 |
513 | cdapio/tephra | tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java | BalanceBooks.run | public void run() throws IOException, InterruptedException {
List<Client> clients = new ArrayList<>(totalClients);
for (int i = 0; i < totalClients; i++) {
Client c = new Client(i, totalClients, iterations);
c.init(txClient, conn.getTable(TABLE));
c.start();
clients.add(c);
}
for (Client c : clients) {
c.join();
Closeables.closeQuietly(c);
}
} | java | public void run() throws IOException, InterruptedException {
List<Client> clients = new ArrayList<>(totalClients);
for (int i = 0; i < totalClients; i++) {
Client c = new Client(i, totalClients, iterations);
c.init(txClient, conn.getTable(TABLE));
c.start();
clients.add(c);
}
for (Client c : clients) {
c.join();
Closeables.closeQuietly(c);
}
} | [
"public",
"void",
"run",
"(",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"List",
"<",
"Client",
">",
"clients",
"=",
"new",
"ArrayList",
"<>",
"(",
"totalClients",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"totalClients",
";",
"i",
"++",
")",
"{",
"Client",
"c",
"=",
"new",
"Client",
"(",
"i",
",",
"totalClients",
",",
"iterations",
")",
";",
"c",
".",
"init",
"(",
"txClient",
",",
"conn",
".",
"getTable",
"(",
"TABLE",
")",
")",
";",
"c",
".",
"start",
"(",
")",
";",
"clients",
".",
"add",
"(",
"c",
")",
";",
"}",
"for",
"(",
"Client",
"c",
":",
"clients",
")",
"{",
"c",
".",
"join",
"(",
")",
";",
"Closeables",
".",
"closeQuietly",
"(",
"c",
")",
";",
"}",
"}"
] | Runs all clients and waits for them to complete. | [
"Runs",
"all",
"clients",
"and",
"waits",
"for",
"them",
"to",
"complete",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java#L124-L137 |
514 | cdapio/tephra | tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java | BalanceBooks.close | public void close() {
try {
if (conn != null) {
conn.close();
}
} catch (IOException ignored) { }
if (zkClient != null) {
zkClient.stopAndWait();
}
} | java | public void close() {
try {
if (conn != null) {
conn.close();
}
} catch (IOException ignored) { }
if (zkClient != null) {
zkClient.stopAndWait();
}
} | [
"public",
"void",
"close",
"(",
")",
"{",
"try",
"{",
"if",
"(",
"conn",
"!=",
"null",
")",
"{",
"conn",
".",
"close",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"ignored",
")",
"{",
"}",
"if",
"(",
"zkClient",
"!=",
"null",
")",
"{",
"zkClient",
".",
"stopAndWait",
"(",
")",
";",
"}",
"}"
] | Frees up the underlying resources common to all clients. | [
"Frees",
"up",
"the",
"underlying",
"resources",
"common",
"to",
"all",
"clients",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-examples/src/main/java/co/cask/tephra/examples/BalanceBooks.java#L185-L195 |
515 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryDecoder.java | BinaryDecoder.readBytes | public byte[] readBytes() throws IOException {
int toRead = readInt();
byte[] bytes = new byte[toRead];
while (toRead > 0) {
int byteRead = input.read(bytes, bytes.length - toRead, toRead);
if (byteRead == -1) {
throw new EOFException();
}
toRead -= byteRead;
}
return bytes;
} | java | public byte[] readBytes() throws IOException {
int toRead = readInt();
byte[] bytes = new byte[toRead];
while (toRead > 0) {
int byteRead = input.read(bytes, bytes.length - toRead, toRead);
if (byteRead == -1) {
throw new EOFException();
}
toRead -= byteRead;
}
return bytes;
} | [
"public",
"byte",
"[",
"]",
"readBytes",
"(",
")",
"throws",
"IOException",
"{",
"int",
"toRead",
"=",
"readInt",
"(",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"new",
"byte",
"[",
"toRead",
"]",
";",
"while",
"(",
"toRead",
">",
"0",
")",
"{",
"int",
"byteRead",
"=",
"input",
".",
"read",
"(",
"bytes",
",",
"bytes",
".",
"length",
"-",
"toRead",
",",
"toRead",
")",
";",
"if",
"(",
"byteRead",
"==",
"-",
"1",
")",
"{",
"throw",
"new",
"EOFException",
"(",
")",
";",
"}",
"toRead",
"-=",
"byteRead",
";",
"}",
"return",
"bytes",
";",
"}"
] | Read a byte sequence. First read an int to indicate how many bytes to read, then that many bytes.
@return the read bytes as a byte array
@throws java.io.IOException If there is IO error.
@throws java.io.EOFException If end of file reached. | [
"Read",
"a",
"byte",
"sequence",
".",
"First",
"read",
"an",
"int",
"to",
"indicate",
"how",
"many",
"bytes",
"to",
"read",
"then",
"that",
"many",
"bytes",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryDecoder.java#L81-L92 |
516 | cdapio/tephra | tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java | TThreadedSelectorServerWithFix.startThreads | @Override
protected boolean startThreads() {
LOGGER.info("Starting {}", TThreadedSelectorServerWithFix.class.getSimpleName());
try {
for (int i = 0; i < args.selectorThreads; ++i) {
selectorThreads.add(new SelectorThread(args.acceptQueueSizePerThread));
}
acceptThread = new AcceptThread((TNonblockingServerTransport) serverTransport_,
createSelectorThreadLoadBalancer(selectorThreads));
stopped_ = false;
for (SelectorThread thread : selectorThreads) {
thread.start();
}
acceptThread.start();
return true;
} catch (IOException e) {
LOGGER.error("Failed to start threads!", e);
return false;
}
} | java | @Override
protected boolean startThreads() {
LOGGER.info("Starting {}", TThreadedSelectorServerWithFix.class.getSimpleName());
try {
for (int i = 0; i < args.selectorThreads; ++i) {
selectorThreads.add(new SelectorThread(args.acceptQueueSizePerThread));
}
acceptThread = new AcceptThread((TNonblockingServerTransport) serverTransport_,
createSelectorThreadLoadBalancer(selectorThreads));
stopped_ = false;
for (SelectorThread thread : selectorThreads) {
thread.start();
}
acceptThread.start();
return true;
} catch (IOException e) {
LOGGER.error("Failed to start threads!", e);
return false;
}
} | [
"@",
"Override",
"protected",
"boolean",
"startThreads",
"(",
")",
"{",
"LOGGER",
".",
"info",
"(",
"\"Starting {}\"",
",",
"TThreadedSelectorServerWithFix",
".",
"class",
".",
"getSimpleName",
"(",
")",
")",
";",
"try",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"args",
".",
"selectorThreads",
";",
"++",
"i",
")",
"{",
"selectorThreads",
".",
"add",
"(",
"new",
"SelectorThread",
"(",
"args",
".",
"acceptQueueSizePerThread",
")",
")",
";",
"}",
"acceptThread",
"=",
"new",
"AcceptThread",
"(",
"(",
"TNonblockingServerTransport",
")",
"serverTransport_",
",",
"createSelectorThreadLoadBalancer",
"(",
"selectorThreads",
")",
")",
";",
"stopped_",
"=",
"false",
";",
"for",
"(",
"SelectorThread",
"thread",
":",
"selectorThreads",
")",
"{",
"thread",
".",
"start",
"(",
")",
";",
"}",
"acceptThread",
".",
"start",
"(",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"LOGGER",
".",
"error",
"(",
"\"Failed to start threads!\"",
",",
"e",
")",
";",
"return",
"false",
";",
"}",
"}"
] | Start the accept and selector threads running to deal with clients.
@return true if everything went ok, false if we couldn't start for some
reason. | [
"Start",
"the",
"accept",
"and",
"selector",
"threads",
"running",
"to",
"deal",
"with",
"clients",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java#L220-L239 |
517 | cdapio/tephra | tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java | TThreadedSelectorServerWithFix.stop | @Override
public void stop() {
stopped_ = true;
// Stop queuing connect attempts asap
stopListening();
if (acceptThread != null) {
acceptThread.wakeupSelector();
}
if (selectorThreads != null) {
for (SelectorThread thread : selectorThreads) {
if (thread != null)
thread.wakeupSelector();
}
}
} | java | @Override
public void stop() {
stopped_ = true;
// Stop queuing connect attempts asap
stopListening();
if (acceptThread != null) {
acceptThread.wakeupSelector();
}
if (selectorThreads != null) {
for (SelectorThread thread : selectorThreads) {
if (thread != null)
thread.wakeupSelector();
}
}
} | [
"@",
"Override",
"public",
"void",
"stop",
"(",
")",
"{",
"stopped_",
"=",
"true",
";",
"// Stop queuing connect attempts asap",
"stopListening",
"(",
")",
";",
"if",
"(",
"acceptThread",
"!=",
"null",
")",
"{",
"acceptThread",
".",
"wakeupSelector",
"(",
")",
";",
"}",
"if",
"(",
"selectorThreads",
"!=",
"null",
")",
"{",
"for",
"(",
"SelectorThread",
"thread",
":",
"selectorThreads",
")",
"{",
"if",
"(",
"thread",
"!=",
"null",
")",
"thread",
".",
"wakeupSelector",
"(",
")",
";",
"}",
"}",
"}"
] | Stop serving and shut everything down. | [
"Stop",
"serving",
"and",
"shut",
"everything",
"down",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java#L266-L282 |
518 | cdapio/tephra | tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java | TThreadedSelectorServerWithFix.requestInvoke | @Override
protected boolean requestInvoke(FrameBuffer frameBuffer) {
Runnable invocation = getRunnable(frameBuffer);
if (invoker != null) {
try {
invoker.execute(invocation);
return true;
} catch (RejectedExecutionException rx) {
LOGGER.warn("ExecutorService rejected execution!", rx);
return false;
}
} else {
// Invoke on the caller's thread
invocation.run();
return true;
}
} | java | @Override
protected boolean requestInvoke(FrameBuffer frameBuffer) {
Runnable invocation = getRunnable(frameBuffer);
if (invoker != null) {
try {
invoker.execute(invocation);
return true;
} catch (RejectedExecutionException rx) {
LOGGER.warn("ExecutorService rejected execution!", rx);
return false;
}
} else {
// Invoke on the caller's thread
invocation.run();
return true;
}
} | [
"@",
"Override",
"protected",
"boolean",
"requestInvoke",
"(",
"FrameBuffer",
"frameBuffer",
")",
"{",
"Runnable",
"invocation",
"=",
"getRunnable",
"(",
"frameBuffer",
")",
";",
"if",
"(",
"invoker",
"!=",
"null",
")",
"{",
"try",
"{",
"invoker",
".",
"execute",
"(",
"invocation",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"RejectedExecutionException",
"rx",
")",
"{",
"LOGGER",
".",
"warn",
"(",
"\"ExecutorService rejected execution!\"",
",",
"rx",
")",
";",
"return",
"false",
";",
"}",
"}",
"else",
"{",
"// Invoke on the caller's thread",
"invocation",
".",
"run",
"(",
")",
";",
"return",
"true",
";",
"}",
"}"
] | We override the standard invoke method here to queue the invocation for
invoker service instead of immediately invoking. If there is no thread
pool, handle the invocation inline on this thread | [
"We",
"override",
"the",
"standard",
"invoke",
"method",
"here",
"to",
"queue",
"the",
"invocation",
"for",
"invoker",
"service",
"instead",
"of",
"immediately",
"invoking",
".",
"If",
"there",
"is",
"no",
"thread",
"pool",
"handle",
"the",
"invocation",
"inline",
"on",
"this",
"thread"
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java#L311-L327 |
519 | cdapio/tephra | tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java | TThreadedSelectorServerWithFix.createDefaultExecutor | protected static ExecutorService createDefaultExecutor(Args options) {
return (options.workerThreads > 0) ? Executors.newFixedThreadPool(options.workerThreads) : null;
} | java | protected static ExecutorService createDefaultExecutor(Args options) {
return (options.workerThreads > 0) ? Executors.newFixedThreadPool(options.workerThreads) : null;
} | [
"protected",
"static",
"ExecutorService",
"createDefaultExecutor",
"(",
"Args",
"options",
")",
"{",
"return",
"(",
"options",
".",
"workerThreads",
">",
"0",
")",
"?",
"Executors",
".",
"newFixedThreadPool",
"(",
"options",
".",
"workerThreads",
")",
":",
"null",
";",
"}"
] | Helper to create the invoker if one is not specified | [
"Helper",
"to",
"create",
"the",
"invoker",
"if",
"one",
"is",
"not",
"specified"
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/org/apache/thrift/server/TThreadedSelectorServerWithFix.java#L336-L338 |
520 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryEncoder.java | BinaryEncoder.writeInt | public BinaryEncoder writeInt(int i) throws IOException {
// Compute the zig-zag value. First double the value and flip the bit if the input is negative.
int val = (i << 1) ^ (i >> 31);
if ((val & ~0x7f) != 0) {
output.write(0x80 | val & 0x7f);
val >>>= 7;
while (val > 0x7f) {
output.write(0x80 | val & 0x7f);
val >>>= 7;
}
}
output.write(val);
return this;
} | java | public BinaryEncoder writeInt(int i) throws IOException {
// Compute the zig-zag value. First double the value and flip the bit if the input is negative.
int val = (i << 1) ^ (i >> 31);
if ((val & ~0x7f) != 0) {
output.write(0x80 | val & 0x7f);
val >>>= 7;
while (val > 0x7f) {
output.write(0x80 | val & 0x7f);
val >>>= 7;
}
}
output.write(val);
return this;
} | [
"public",
"BinaryEncoder",
"writeInt",
"(",
"int",
"i",
")",
"throws",
"IOException",
"{",
"// Compute the zig-zag value. First double the value and flip the bit if the input is negative.",
"int",
"val",
"=",
"(",
"i",
"<<",
"1",
")",
"^",
"(",
"i",
">>",
"31",
")",
";",
"if",
"(",
"(",
"val",
"&",
"~",
"0x7f",
")",
"!=",
"0",
")",
"{",
"output",
".",
"write",
"(",
"0x80",
"|",
"val",
"&",
"0x7f",
")",
";",
"val",
">>>=",
"7",
";",
"while",
"(",
"val",
">",
"0x7f",
")",
"{",
"output",
".",
"write",
"(",
"0x80",
"|",
"val",
"&",
"0x7f",
")",
";",
"val",
">>>=",
"7",
";",
"}",
"}",
"output",
".",
"write",
"(",
"val",
")",
";",
"return",
"this",
";",
"}"
] | write a single int value.
@throws java.io.IOException If there is IO error. | [
"write",
"a",
"single",
"int",
"value",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryEncoder.java#L40-L55 |
521 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryEncoder.java | BinaryEncoder.writeLong | public BinaryEncoder writeLong(long l) throws IOException {
// Compute the zig-zag value. First double the value and flip the bit if the input is negative.
long val = (l << 1) ^ (l >> 63);
if ((val & ~0x7f) != 0) {
output.write((int) (0x80 | val & 0x7f));
val >>>= 7;
while (val > 0x7f) {
output.write((int) (0x80 | val & 0x7f));
val >>>= 7;
}
}
output.write((int) val);
return this;
} | java | public BinaryEncoder writeLong(long l) throws IOException {
// Compute the zig-zag value. First double the value and flip the bit if the input is negative.
long val = (l << 1) ^ (l >> 63);
if ((val & ~0x7f) != 0) {
output.write((int) (0x80 | val & 0x7f));
val >>>= 7;
while (val > 0x7f) {
output.write((int) (0x80 | val & 0x7f));
val >>>= 7;
}
}
output.write((int) val);
return this;
} | [
"public",
"BinaryEncoder",
"writeLong",
"(",
"long",
"l",
")",
"throws",
"IOException",
"{",
"// Compute the zig-zag value. First double the value and flip the bit if the input is negative.",
"long",
"val",
"=",
"(",
"l",
"<<",
"1",
")",
"^",
"(",
"l",
">>",
"63",
")",
";",
"if",
"(",
"(",
"val",
"&",
"~",
"0x7f",
")",
"!=",
"0",
")",
"{",
"output",
".",
"write",
"(",
"(",
"int",
")",
"(",
"0x80",
"|",
"val",
"&",
"0x7f",
")",
")",
";",
"val",
">>>=",
"7",
";",
"while",
"(",
"val",
">",
"0x7f",
")",
"{",
"output",
".",
"write",
"(",
"(",
"int",
")",
"(",
"0x80",
"|",
"val",
"&",
"0x7f",
")",
")",
";",
"val",
">>>=",
"7",
";",
"}",
"}",
"output",
".",
"write",
"(",
"(",
"int",
")",
"val",
")",
";",
"return",
"this",
";",
"}"
] | write a single long int value.
@throws java.io.IOException If there is IO error. | [
"write",
"a",
"single",
"long",
"int",
"value",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryEncoder.java#L61-L76 |
522 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryEncoder.java | BinaryEncoder.writeBytes | public BinaryEncoder writeBytes(byte[] bytes) throws IOException {
writeLong(bytes.length);
output.write(bytes, 0, bytes.length);
return this;
} | java | public BinaryEncoder writeBytes(byte[] bytes) throws IOException {
writeLong(bytes.length);
output.write(bytes, 0, bytes.length);
return this;
} | [
"public",
"BinaryEncoder",
"writeBytes",
"(",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"IOException",
"{",
"writeLong",
"(",
"bytes",
".",
"length",
")",
";",
"output",
".",
"write",
"(",
"bytes",
",",
"0",
",",
"bytes",
".",
"length",
")",
";",
"return",
"this",
";",
"}"
] | write a sequence of bytes. First writes the number of bytes as an int, then the bytes themselves.
@throws java.io.IOException If there is IO error. | [
"write",
"a",
"sequence",
"of",
"bytes",
".",
"First",
"writes",
"the",
"number",
"of",
"bytes",
"as",
"an",
"int",
"then",
"the",
"bytes",
"themselves",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/snapshot/BinaryEncoder.java#L82-L86 |
523 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/persist/CommitMarkerCodec.java | CommitMarkerCodec.readMarker | public int readMarker(SequenceFile.Reader reader) throws IOException {
if (valueBytes == null) {
valueBytes = reader.createValueBytes();
}
rawKey.reset();
rawValue.reset();
// valueBytes need not be reset since nextRaw call does it (and it is a private method)
int status = reader.nextRaw(rawKey, valueBytes);
// if we reach EOF, return -1
if (status == -1) {
return -1;
}
// Check if the marker key is valid and return the count
if (isMarkerValid()) {
valueBytes.writeUncompressedBytes(rawValue);
rawValue.flush();
// rawValue.getData() may return a larger byte array but Ints.fromByteArray will only read the first four bytes
return Ints.fromByteArray(rawValue.getData());
}
// EOF not reached and marker is not valid, then thrown an IOException since we can't make progress
throw new IOException(String.format("Invalid key for num entries appended found %s, expected : %s",
new String(rawKey.getData()), TxConstants.TransactionLog.NUM_ENTRIES_APPENDED));
} | java | public int readMarker(SequenceFile.Reader reader) throws IOException {
if (valueBytes == null) {
valueBytes = reader.createValueBytes();
}
rawKey.reset();
rawValue.reset();
// valueBytes need not be reset since nextRaw call does it (and it is a private method)
int status = reader.nextRaw(rawKey, valueBytes);
// if we reach EOF, return -1
if (status == -1) {
return -1;
}
// Check if the marker key is valid and return the count
if (isMarkerValid()) {
valueBytes.writeUncompressedBytes(rawValue);
rawValue.flush();
// rawValue.getData() may return a larger byte array but Ints.fromByteArray will only read the first four bytes
return Ints.fromByteArray(rawValue.getData());
}
// EOF not reached and marker is not valid, then thrown an IOException since we can't make progress
throw new IOException(String.format("Invalid key for num entries appended found %s, expected : %s",
new String(rawKey.getData()), TxConstants.TransactionLog.NUM_ENTRIES_APPENDED));
} | [
"public",
"int",
"readMarker",
"(",
"SequenceFile",
".",
"Reader",
"reader",
")",
"throws",
"IOException",
"{",
"if",
"(",
"valueBytes",
"==",
"null",
")",
"{",
"valueBytes",
"=",
"reader",
".",
"createValueBytes",
"(",
")",
";",
"}",
"rawKey",
".",
"reset",
"(",
")",
";",
"rawValue",
".",
"reset",
"(",
")",
";",
"// valueBytes need not be reset since nextRaw call does it (and it is a private method)",
"int",
"status",
"=",
"reader",
".",
"nextRaw",
"(",
"rawKey",
",",
"valueBytes",
")",
";",
"// if we reach EOF, return -1",
"if",
"(",
"status",
"==",
"-",
"1",
")",
"{",
"return",
"-",
"1",
";",
"}",
"// Check if the marker key is valid and return the count",
"if",
"(",
"isMarkerValid",
"(",
")",
")",
"{",
"valueBytes",
".",
"writeUncompressedBytes",
"(",
"rawValue",
")",
";",
"rawValue",
".",
"flush",
"(",
")",
";",
"// rawValue.getData() may return a larger byte array but Ints.fromByteArray will only read the first four bytes",
"return",
"Ints",
".",
"fromByteArray",
"(",
"rawValue",
".",
"getData",
"(",
")",
")",
";",
"}",
"// EOF not reached and marker is not valid, then thrown an IOException since we can't make progress",
"throw",
"new",
"IOException",
"(",
"String",
".",
"format",
"(",
"\"Invalid key for num entries appended found %s, expected : %s\"",
",",
"new",
"String",
"(",
"rawKey",
".",
"getData",
"(",
")",
")",
",",
"TxConstants",
".",
"TransactionLog",
".",
"NUM_ENTRIES_APPENDED",
")",
")",
";",
"}"
] | since we can recover without any consequence | [
"since",
"we",
"can",
"recover",
"without",
"any",
"consequence"
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/persist/CommitMarkerCodec.java#L56-L82 |
524 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/coprocessor/TransactionStateCache.java | TransactionStateCache.tryInit | private void tryInit() {
try {
Configuration conf = getSnapshotConfiguration();
if (conf != null) {
// Since this is only used for background loading of transaction snapshots, we use the no-op metrics collector,
// as there are no relevant metrics to report
this.storage = new HDFSTransactionStateStorage(conf, new SnapshotCodecProvider(conf),
new TxMetricsCollector());
this.storage.startAndWait();
this.snapshotRefreshFrequency = conf.getLong(TxConstants.Manager.CFG_TX_SNAPSHOT_INTERVAL,
TxConstants.Manager.DEFAULT_TX_SNAPSHOT_INTERVAL) * 1000;
this.initialized = true;
} else {
LOG.info("Could not load configuration");
}
} catch (Exception e) {
LOG.info("Failed to initialize TransactionStateCache due to: " + e.getMessage());
}
} | java | private void tryInit() {
try {
Configuration conf = getSnapshotConfiguration();
if (conf != null) {
// Since this is only used for background loading of transaction snapshots, we use the no-op metrics collector,
// as there are no relevant metrics to report
this.storage = new HDFSTransactionStateStorage(conf, new SnapshotCodecProvider(conf),
new TxMetricsCollector());
this.storage.startAndWait();
this.snapshotRefreshFrequency = conf.getLong(TxConstants.Manager.CFG_TX_SNAPSHOT_INTERVAL,
TxConstants.Manager.DEFAULT_TX_SNAPSHOT_INTERVAL) * 1000;
this.initialized = true;
} else {
LOG.info("Could not load configuration");
}
} catch (Exception e) {
LOG.info("Failed to initialize TransactionStateCache due to: " + e.getMessage());
}
} | [
"private",
"void",
"tryInit",
"(",
")",
"{",
"try",
"{",
"Configuration",
"conf",
"=",
"getSnapshotConfiguration",
"(",
")",
";",
"if",
"(",
"conf",
"!=",
"null",
")",
"{",
"// Since this is only used for background loading of transaction snapshots, we use the no-op metrics collector,",
"// as there are no relevant metrics to report",
"this",
".",
"storage",
"=",
"new",
"HDFSTransactionStateStorage",
"(",
"conf",
",",
"new",
"SnapshotCodecProvider",
"(",
"conf",
")",
",",
"new",
"TxMetricsCollector",
"(",
")",
")",
";",
"this",
".",
"storage",
".",
"startAndWait",
"(",
")",
";",
"this",
".",
"snapshotRefreshFrequency",
"=",
"conf",
".",
"getLong",
"(",
"TxConstants",
".",
"Manager",
".",
"CFG_TX_SNAPSHOT_INTERVAL",
",",
"TxConstants",
".",
"Manager",
".",
"DEFAULT_TX_SNAPSHOT_INTERVAL",
")",
"*",
"1000",
";",
"this",
".",
"initialized",
"=",
"true",
";",
"}",
"else",
"{",
"LOG",
".",
"info",
"(",
"\"Could not load configuration\"",
")",
";",
"}",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Failed to initialize TransactionStateCache due to: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Try to initialize the Configuration and TransactionStateStorage instances. Obtaining the Configuration may
fail until ReactorServiceMain has been started. | [
"Try",
"to",
"initialize",
"the",
"Configuration",
"and",
"TransactionStateStorage",
"instances",
".",
"Obtaining",
"the",
"Configuration",
"may",
"fail",
"until",
"ReactorServiceMain",
"has",
"been",
"started",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/coprocessor/TransactionStateCache.java#L85-L103 |
525 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionServiceMain.java | TransactionServiceMain.doMain | public void doMain(final String[] args) throws Exception {
final CountDownLatch shutdownLatch = new CountDownLatch(1);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
try {
TransactionServiceMain.this.stop();
} finally {
try {
TransactionServiceMain.this.destroy();
} finally {
shutdownLatch.countDown();
}
}
} catch (Throwable t) {
LOG.error("Exception when shutting down: " + t.getMessage(), t);
}
}
});
init(args);
start();
shutdownLatch.await();
} | java | public void doMain(final String[] args) throws Exception {
final CountDownLatch shutdownLatch = new CountDownLatch(1);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
try {
TransactionServiceMain.this.stop();
} finally {
try {
TransactionServiceMain.this.destroy();
} finally {
shutdownLatch.countDown();
}
}
} catch (Throwable t) {
LOG.error("Exception when shutting down: " + t.getMessage(), t);
}
}
});
init(args);
start();
shutdownLatch.await();
} | [
"public",
"void",
"doMain",
"(",
"final",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"final",
"CountDownLatch",
"shutdownLatch",
"=",
"new",
"CountDownLatch",
"(",
"1",
")",
";",
"Runtime",
".",
"getRuntime",
"(",
")",
".",
"addShutdownHook",
"(",
"new",
"Thread",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"try",
"{",
"TransactionServiceMain",
".",
"this",
".",
"stop",
"(",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"TransactionServiceMain",
".",
"this",
".",
"destroy",
"(",
")",
";",
"}",
"finally",
"{",
"shutdownLatch",
".",
"countDown",
"(",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Exception when shutting down: \"",
"+",
"t",
".",
"getMessage",
"(",
")",
",",
"t",
")",
";",
"}",
"}",
"}",
")",
";",
"init",
"(",
"args",
")",
";",
"start",
"(",
")",
";",
"shutdownLatch",
".",
"await",
"(",
")",
";",
"}"
] | The main method. It simply call methods in the same sequence
as if the program is started by jsvc. | [
"The",
"main",
"method",
".",
"It",
"simply",
"call",
"methods",
"in",
"the",
"same",
"sequence",
"as",
"if",
"the",
"program",
"is",
"started",
"by",
"jsvc",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionServiceMain.java#L62-L86 |
526 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionServiceMain.java | TransactionServiceMain.start | public void start() throws Exception {
Injector injector = Guice.createInjector(
new ConfigModule(conf),
new ZKModule(),
new DiscoveryModules().getDistributedModules(),
new TransactionModules().getDistributedModules(),
new TransactionClientModule()
);
ZKClientService zkClientService = injector.getInstance(ZKClientService.class);
zkClientService.startAndWait();
// start a tx server
txService = injector.getInstance(TransactionService.class);
try {
LOG.info("Starting {}", getClass().getSimpleName());
txService.startAndWait();
} catch (Exception e) {
System.err.println("Failed to start service: " + e.getMessage());
}
} | java | public void start() throws Exception {
Injector injector = Guice.createInjector(
new ConfigModule(conf),
new ZKModule(),
new DiscoveryModules().getDistributedModules(),
new TransactionModules().getDistributedModules(),
new TransactionClientModule()
);
ZKClientService zkClientService = injector.getInstance(ZKClientService.class);
zkClientService.startAndWait();
// start a tx server
txService = injector.getInstance(TransactionService.class);
try {
LOG.info("Starting {}", getClass().getSimpleName());
txService.startAndWait();
} catch (Exception e) {
System.err.println("Failed to start service: " + e.getMessage());
}
} | [
"public",
"void",
"start",
"(",
")",
"throws",
"Exception",
"{",
"Injector",
"injector",
"=",
"Guice",
".",
"createInjector",
"(",
"new",
"ConfigModule",
"(",
"conf",
")",
",",
"new",
"ZKModule",
"(",
")",
",",
"new",
"DiscoveryModules",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"TransactionModules",
"(",
")",
".",
"getDistributedModules",
"(",
")",
",",
"new",
"TransactionClientModule",
"(",
")",
")",
";",
"ZKClientService",
"zkClientService",
"=",
"injector",
".",
"getInstance",
"(",
"ZKClientService",
".",
"class",
")",
";",
"zkClientService",
".",
"startAndWait",
"(",
")",
";",
"// start a tx server",
"txService",
"=",
"injector",
".",
"getInstance",
"(",
"TransactionService",
".",
"class",
")",
";",
"try",
"{",
"LOG",
".",
"info",
"(",
"\"Starting {}\"",
",",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
";",
"txService",
".",
"startAndWait",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"System",
".",
"err",
".",
"println",
"(",
"\"Failed to start service: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"}"
] | Invoked by jsvc to start the program. | [
"Invoked",
"by",
"jsvc",
"to",
"start",
"the",
"program",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionServiceMain.java#L100-L120 |
527 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/TransactionServiceMain.java | TransactionServiceMain.stop | public void stop() {
LOG.info("Stopping {}", getClass().getSimpleName());
if (txService == null) {
return;
}
try {
if (txService.isRunning()) {
txService.stopAndWait();
}
} catch (Throwable e) {
LOG.error("Failed to shutdown transaction service.", e);
// because shutdown hooks execute concurrently, the logger may be closed already: thus also print it.
System.err.println("Failed to shutdown transaction service: " + e.getMessage());
e.printStackTrace(System.err);
}
} | java | public void stop() {
LOG.info("Stopping {}", getClass().getSimpleName());
if (txService == null) {
return;
}
try {
if (txService.isRunning()) {
txService.stopAndWait();
}
} catch (Throwable e) {
LOG.error("Failed to shutdown transaction service.", e);
// because shutdown hooks execute concurrently, the logger may be closed already: thus also print it.
System.err.println("Failed to shutdown transaction service: " + e.getMessage());
e.printStackTrace(System.err);
}
} | [
"public",
"void",
"stop",
"(",
")",
"{",
"LOG",
".",
"info",
"(",
"\"Stopping {}\"",
",",
"getClass",
"(",
")",
".",
"getSimpleName",
"(",
")",
")",
";",
"if",
"(",
"txService",
"==",
"null",
")",
"{",
"return",
";",
"}",
"try",
"{",
"if",
"(",
"txService",
".",
"isRunning",
"(",
")",
")",
"{",
"txService",
".",
"stopAndWait",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Failed to shutdown transaction service.\"",
",",
"e",
")",
";",
"// because shutdown hooks execute concurrently, the logger may be closed already: thus also print it.",
"System",
".",
"err",
".",
"println",
"(",
"\"Failed to shutdown transaction service: \"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"e",
".",
"printStackTrace",
"(",
"System",
".",
"err",
")",
";",
"}",
"}"
] | Invoked by jsvc to stop the program. | [
"Invoked",
"by",
"jsvc",
"to",
"stop",
"the",
"program",
"."
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/TransactionServiceMain.java#L125-L140 |
528 | cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/distributed/ElasticPool.java | ElasticPool.getOrCreate | private T getOrCreate() throws E {
try {
T client = elements.poll();
// a client was available, all good. otherwise, create one
if (client != null) {
return client;
}
return create();
} catch (Exception e) {
// if an exception is thrown after acquiring the semaphore, release the
// semaphore before propagating the exception
semaphore.release();
throw e;
}
} | java | private T getOrCreate() throws E {
try {
T client = elements.poll();
// a client was available, all good. otherwise, create one
if (client != null) {
return client;
}
return create();
} catch (Exception e) {
// if an exception is thrown after acquiring the semaphore, release the
// semaphore before propagating the exception
semaphore.release();
throw e;
}
} | [
"private",
"T",
"getOrCreate",
"(",
")",
"throws",
"E",
"{",
"try",
"{",
"T",
"client",
"=",
"elements",
".",
"poll",
"(",
")",
";",
"// a client was available, all good. otherwise, create one",
"if",
"(",
"client",
"!=",
"null",
")",
"{",
"return",
"client",
";",
"}",
"return",
"create",
"(",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"// if an exception is thrown after acquiring the semaphore, release the",
"// semaphore before propagating the exception",
"semaphore",
".",
"release",
"(",
")",
";",
"throw",
"e",
";",
"}",
"}"
] | this method if it throws any exception | [
"this",
"method",
"if",
"it",
"throws",
"any",
"exception"
] | 082c56c15c6ece15002631ff6f89206a00d8915c | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/distributed/ElasticPool.java#L129-L143 |
529 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Skew.java | Skew.leq | private static boolean leq(int a1, int a2, int b1, int b2) {
return (a1 < b1 || (a1 == b1 && a2 <= b2));
} | java | private static boolean leq(int a1, int a2, int b1, int b2) {
return (a1 < b1 || (a1 == b1 && a2 <= b2));
} | [
"private",
"static",
"boolean",
"leq",
"(",
"int",
"a1",
",",
"int",
"a2",
",",
"int",
"b1",
",",
"int",
"b2",
")",
"{",
"return",
"(",
"a1",
"<",
"b1",
"||",
"(",
"a1",
"==",
"b1",
"&&",
"a2",
"<=",
"b2",
")",
")",
";",
"}"
] | Lexicographic order for pairs. | [
"Lexicographic",
"order",
"for",
"pairs",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Skew.java#L26-L28 |
530 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Skew.java | Skew.leq | private static boolean leq(int a1, int a2, int a3, int b1, int b2, int b3) {
return (a1 < b1 || (a1 == b1 && leq(a2, a3, b2, b3)));
} | java | private static boolean leq(int a1, int a2, int a3, int b1, int b2, int b3) {
return (a1 < b1 || (a1 == b1 && leq(a2, a3, b2, b3)));
} | [
"private",
"static",
"boolean",
"leq",
"(",
"int",
"a1",
",",
"int",
"a2",
",",
"int",
"a3",
",",
"int",
"b1",
",",
"int",
"b2",
",",
"int",
"b3",
")",
"{",
"return",
"(",
"a1",
"<",
"b1",
"||",
"(",
"a1",
"==",
"b1",
"&&",
"leq",
"(",
"a2",
",",
"a3",
",",
"b2",
",",
"b3",
")",
")",
")",
";",
"}"
] | Lexicographic order for triples. | [
"Lexicographic",
"order",
"for",
"triples",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Skew.java#L33-L35 |
531 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java | BPR.insSortUpdateRecurse_SaBucket | private void insSortUpdateRecurse_SaBucket(int leftPtr, int rightPtr, int offset,
int q) {
int rightTmpPtr = leftPtr + 1;
while (rightTmpPtr <= rightPtr) {
int tempValue = suffixArray[rightTmpPtr];
int tempHashValue = sufPtrMap[suffixArray[rightTmpPtr] + offset];
int leftTmpPtr = rightTmpPtr;
while (leftTmpPtr > leftPtr
&& sufPtrMap[suffixArray[leftTmpPtr - 1] + offset] > tempHashValue) {
suffixArray[leftTmpPtr] = suffixArray[leftTmpPtr - 1];
leftTmpPtr--;
}
suffixArray[leftTmpPtr] = tempValue;
rightTmpPtr++;
}
updatePtrAndRefineBuckets_SaBucket(leftPtr, rightPtr, offset, q);
} | java | private void insSortUpdateRecurse_SaBucket(int leftPtr, int rightPtr, int offset,
int q) {
int rightTmpPtr = leftPtr + 1;
while (rightTmpPtr <= rightPtr) {
int tempValue = suffixArray[rightTmpPtr];
int tempHashValue = sufPtrMap[suffixArray[rightTmpPtr] + offset];
int leftTmpPtr = rightTmpPtr;
while (leftTmpPtr > leftPtr
&& sufPtrMap[suffixArray[leftTmpPtr - 1] + offset] > tempHashValue) {
suffixArray[leftTmpPtr] = suffixArray[leftTmpPtr - 1];
leftTmpPtr--;
}
suffixArray[leftTmpPtr] = tempValue;
rightTmpPtr++;
}
updatePtrAndRefineBuckets_SaBucket(leftPtr, rightPtr, offset, q);
} | [
"private",
"void",
"insSortUpdateRecurse_SaBucket",
"(",
"int",
"leftPtr",
",",
"int",
"rightPtr",
",",
"int",
"offset",
",",
"int",
"q",
")",
"{",
"int",
"rightTmpPtr",
"=",
"leftPtr",
"+",
"1",
";",
"while",
"(",
"rightTmpPtr",
"<=",
"rightPtr",
")",
"{",
"int",
"tempValue",
"=",
"suffixArray",
"[",
"rightTmpPtr",
"]",
";",
"int",
"tempHashValue",
"=",
"sufPtrMap",
"[",
"suffixArray",
"[",
"rightTmpPtr",
"]",
"+",
"offset",
"]",
";",
"int",
"leftTmpPtr",
"=",
"rightTmpPtr",
";",
"while",
"(",
"leftTmpPtr",
">",
"leftPtr",
"&&",
"sufPtrMap",
"[",
"suffixArray",
"[",
"leftTmpPtr",
"-",
"1",
"]",
"+",
"offset",
"]",
">",
"tempHashValue",
")",
"{",
"suffixArray",
"[",
"leftTmpPtr",
"]",
"=",
"suffixArray",
"[",
"leftTmpPtr",
"-",
"1",
"]",
";",
"leftTmpPtr",
"--",
";",
"}",
"suffixArray",
"[",
"leftTmpPtr",
"]",
"=",
"tempValue",
";",
"rightTmpPtr",
"++",
";",
"}",
"updatePtrAndRefineBuckets_SaBucket",
"(",
"leftPtr",
",",
"rightPtr",
",",
"offset",
",",
"q",
")",
";",
"}"
] | Stably sorts a bucket at a refinement level regarding sort keys that are bucket
pointers in sufPtrMap with offset.
@param leftPtr points to the leftmost suffix of the current bucket.
@param rightPtr points to the rightmost suffix of the current bucket.
@param offset is the length of the common prefix of the suffixes (a multiple of q).
@param q is the initial prefix length used for the bucket sort. It also determines
the increase of offset. | [
"Stably",
"sorts",
"a",
"bucket",
"at",
"a",
"refinement",
"level",
"regarding",
"sort",
"keys",
"that",
"are",
"bucket",
"pointers",
"in",
"sufPtrMap",
"with",
"offset",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java#L288-L304 |
532 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java | BPR.computeBucketSize2_SaBucket | private void computeBucketSize2_SaBucket(int leftPtr, int rightPtr, int offset, int q) {
int suffix1 = suffixArray[leftPtr] + offset;
int suffix2 = suffixArray[rightPtr] + offset;
while (sufPtrMap[suffix1] == sufPtrMap[suffix2]) {
suffix1 += q;
suffix2 += q;
}
if (sufPtrMap[suffix1] > sufPtrMap[suffix2]) {
int tmpSwap = suffixArray[leftPtr];
suffixArray[leftPtr] = suffixArray[rightPtr];
suffixArray[rightPtr] = tmpSwap;
}
sufPtrMap[suffixArray[leftPtr]] = leftPtr;
sufPtrMap[suffixArray[rightPtr]] = rightPtr;
} | java | private void computeBucketSize2_SaBucket(int leftPtr, int rightPtr, int offset, int q) {
int suffix1 = suffixArray[leftPtr] + offset;
int suffix2 = suffixArray[rightPtr] + offset;
while (sufPtrMap[suffix1] == sufPtrMap[suffix2]) {
suffix1 += q;
suffix2 += q;
}
if (sufPtrMap[suffix1] > sufPtrMap[suffix2]) {
int tmpSwap = suffixArray[leftPtr];
suffixArray[leftPtr] = suffixArray[rightPtr];
suffixArray[rightPtr] = tmpSwap;
}
sufPtrMap[suffixArray[leftPtr]] = leftPtr;
sufPtrMap[suffixArray[rightPtr]] = rightPtr;
} | [
"private",
"void",
"computeBucketSize2_SaBucket",
"(",
"int",
"leftPtr",
",",
"int",
"rightPtr",
",",
"int",
"offset",
",",
"int",
"q",
")",
"{",
"int",
"suffix1",
"=",
"suffixArray",
"[",
"leftPtr",
"]",
"+",
"offset",
";",
"int",
"suffix2",
"=",
"suffixArray",
"[",
"rightPtr",
"]",
"+",
"offset",
";",
"while",
"(",
"sufPtrMap",
"[",
"suffix1",
"]",
"==",
"sufPtrMap",
"[",
"suffix2",
"]",
")",
"{",
"suffix1",
"+=",
"q",
";",
"suffix2",
"+=",
"q",
";",
"}",
"if",
"(",
"sufPtrMap",
"[",
"suffix1",
"]",
">",
"sufPtrMap",
"[",
"suffix2",
"]",
")",
"{",
"int",
"tmpSwap",
"=",
"suffixArray",
"[",
"leftPtr",
"]",
";",
"suffixArray",
"[",
"leftPtr",
"]",
"=",
"suffixArray",
"[",
"rightPtr",
"]",
";",
"suffixArray",
"[",
"rightPtr",
"]",
"=",
"tmpSwap",
";",
"}",
"sufPtrMap",
"[",
"suffixArray",
"[",
"leftPtr",
"]",
"]",
"=",
"leftPtr",
";",
"sufPtrMap",
"[",
"suffixArray",
"[",
"rightPtr",
"]",
"]",
"=",
"rightPtr",
";",
"}"
] | Completely sorts buckets of size 2.
@param leftPtr points to the leftmost suffix of the current bucket.
@param rightPtr points to the rightmost suffix of the current bucket.
@param offset is the length of the common prefix of the suffixes rounded down to a
multiple of q.
@param q is the initial prefix length used for the bucket sort. It also determines
the increase of offset. | [
"Completely",
"sorts",
"buckets",
"of",
"size",
"2",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java#L523-L538 |
533 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java | BPR.computeDiffDepthBucket_SaBucket | private int computeDiffDepthBucket_SaBucket(int leftPtr, int rightPtr, int offset,
int q) {
int lcp = offset;
while (true) {
int runPtr = leftPtr;
int a = suffixArray[rightPtr];
int tmpPtr = sufPtrMap[a + lcp];
while (runPtr < rightPtr) {
if (sufPtrMap[suffixArray[runPtr] + lcp] != tmpPtr) {
return lcp;
}
runPtr++;
}
lcp += q;
}
} | java | private int computeDiffDepthBucket_SaBucket(int leftPtr, int rightPtr, int offset,
int q) {
int lcp = offset;
while (true) {
int runPtr = leftPtr;
int a = suffixArray[rightPtr];
int tmpPtr = sufPtrMap[a + lcp];
while (runPtr < rightPtr) {
if (sufPtrMap[suffixArray[runPtr] + lcp] != tmpPtr) {
return lcp;
}
runPtr++;
}
lcp += q;
}
} | [
"private",
"int",
"computeDiffDepthBucket_SaBucket",
"(",
"int",
"leftPtr",
",",
"int",
"rightPtr",
",",
"int",
"offset",
",",
"int",
"q",
")",
"{",
"int",
"lcp",
"=",
"offset",
";",
"while",
"(",
"true",
")",
"{",
"int",
"runPtr",
"=",
"leftPtr",
";",
"int",
"a",
"=",
"suffixArray",
"[",
"rightPtr",
"]",
";",
"int",
"tmpPtr",
"=",
"sufPtrMap",
"[",
"a",
"+",
"lcp",
"]",
";",
"while",
"(",
"runPtr",
"<",
"rightPtr",
")",
"{",
"if",
"(",
"sufPtrMap",
"[",
"suffixArray",
"[",
"runPtr",
"]",
"+",
"lcp",
"]",
"!=",
"tmpPtr",
")",
"{",
"return",
"lcp",
";",
"}",
"runPtr",
"++",
";",
"}",
"lcp",
"+=",
"q",
";",
"}",
"}"
] | Computes about the LCP of all suffixes in this bucket. It will be the newoffset.
@param leftPtr points to the leftmost suffix of the current bucket.
@param rightPtr points to the rightmost suffix of the current bucket.
@param offset is the length of the common prefix of the suffixes rounded down to a
multiple of q.
@param q is the initial prefix length used for the bucket sort. It also determines
the increase of offset.
@return the LCP of suffixes in this bucket (newoffset). | [
"Computes",
"about",
"the",
"LCP",
"of",
"all",
"suffixes",
"in",
"this",
"bucket",
".",
"It",
"will",
"be",
"the",
"newoffset",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java#L551-L566 |
534 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java | BPR.determineAll_Buckets_Sarray_Sptrmap | private int[] determineAll_Buckets_Sarray_Sptrmap(int q) {
int[] buckets = determineAll_Buckets_Sarray(q);
int strLen = length;
sufPtrMap = new int[strLen + 2 * q + 1];
/* computation of first hashvalue */
int alphabetSize = alphabet.size;
int mappedUcharArray = 0;
int tempPower = 1;
int hashCode = 0;
int i;
for (i = q - 1; i >= 0; i--) {
hashCode += seq[start + mappedUcharArray + i] * tempPower;
tempPower *= alphabetSize;
}
int tempModulo = kbs_power_Ulong(alphabetSize, q - 1);
mappedUcharArray += q;
int j;
for (j = 0; j < strLen - 1; j++) {
sufPtrMap[j] = (buckets[hashCode + 1]) - 1;
hashCode -= (seq[start + mappedUcharArray - q]) * tempModulo;
hashCode *= alphabetSize;
hashCode += seq[start + mappedUcharArray];
mappedUcharArray++;
}
sufPtrMap[j] = buckets[hashCode];
/* set the values in sufPtrMap[strLen..strLen+2*d] to [-1, -2, ..., -2*d] */
int beginPtr = -1;
for (j = strLen; j <= strLen + 2 * q; j++) {
sufPtrMap[j] = beginPtr--;
}
return buckets;
} | java | private int[] determineAll_Buckets_Sarray_Sptrmap(int q) {
int[] buckets = determineAll_Buckets_Sarray(q);
int strLen = length;
sufPtrMap = new int[strLen + 2 * q + 1];
/* computation of first hashvalue */
int alphabetSize = alphabet.size;
int mappedUcharArray = 0;
int tempPower = 1;
int hashCode = 0;
int i;
for (i = q - 1; i >= 0; i--) {
hashCode += seq[start + mappedUcharArray + i] * tempPower;
tempPower *= alphabetSize;
}
int tempModulo = kbs_power_Ulong(alphabetSize, q - 1);
mappedUcharArray += q;
int j;
for (j = 0; j < strLen - 1; j++) {
sufPtrMap[j] = (buckets[hashCode + 1]) - 1;
hashCode -= (seq[start + mappedUcharArray - q]) * tempModulo;
hashCode *= alphabetSize;
hashCode += seq[start + mappedUcharArray];
mappedUcharArray++;
}
sufPtrMap[j] = buckets[hashCode];
/* set the values in sufPtrMap[strLen..strLen+2*d] to [-1, -2, ..., -2*d] */
int beginPtr = -1;
for (j = strLen; j <= strLen + 2 * q; j++) {
sufPtrMap[j] = beginPtr--;
}
return buckets;
} | [
"private",
"int",
"[",
"]",
"determineAll_Buckets_Sarray_Sptrmap",
"(",
"int",
"q",
")",
"{",
"int",
"[",
"]",
"buckets",
"=",
"determineAll_Buckets_Sarray",
"(",
"q",
")",
";",
"int",
"strLen",
"=",
"length",
";",
"sufPtrMap",
"=",
"new",
"int",
"[",
"strLen",
"+",
"2",
"*",
"q",
"+",
"1",
"]",
";",
"/* computation of first hashvalue */",
"int",
"alphabetSize",
"=",
"alphabet",
".",
"size",
";",
"int",
"mappedUcharArray",
"=",
"0",
";",
"int",
"tempPower",
"=",
"1",
";",
"int",
"hashCode",
"=",
"0",
";",
"int",
"i",
";",
"for",
"(",
"i",
"=",
"q",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"hashCode",
"+=",
"seq",
"[",
"start",
"+",
"mappedUcharArray",
"+",
"i",
"]",
"*",
"tempPower",
";",
"tempPower",
"*=",
"alphabetSize",
";",
"}",
"int",
"tempModulo",
"=",
"kbs_power_Ulong",
"(",
"alphabetSize",
",",
"q",
"-",
"1",
")",
";",
"mappedUcharArray",
"+=",
"q",
";",
"int",
"j",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"strLen",
"-",
"1",
";",
"j",
"++",
")",
"{",
"sufPtrMap",
"[",
"j",
"]",
"=",
"(",
"buckets",
"[",
"hashCode",
"+",
"1",
"]",
")",
"-",
"1",
";",
"hashCode",
"-=",
"(",
"seq",
"[",
"start",
"+",
"mappedUcharArray",
"-",
"q",
"]",
")",
"*",
"tempModulo",
";",
"hashCode",
"*=",
"alphabetSize",
";",
"hashCode",
"+=",
"seq",
"[",
"start",
"+",
"mappedUcharArray",
"]",
";",
"mappedUcharArray",
"++",
";",
"}",
"sufPtrMap",
"[",
"j",
"]",
"=",
"buckets",
"[",
"hashCode",
"]",
";",
"/* set the values in sufPtrMap[strLen..strLen+2*d] to [-1, -2, ..., -2*d] */",
"int",
"beginPtr",
"=",
"-",
"1",
";",
"for",
"(",
"j",
"=",
"strLen",
";",
"j",
"<=",
"strLen",
"+",
"2",
"*",
"q",
";",
"j",
"++",
")",
"{",
"sufPtrMap",
"[",
"j",
"]",
"=",
"beginPtr",
"--",
";",
"}",
"return",
"buckets",
";",
"}"
] | Constructs all buckets w.r.t. q-gram size q, the up to prefix q sorted suffix
array, and the bucket-pointer table.
@param q size of q-gram.
@return Buckets containing pointers into the suffix array.
@see #determine_Buckets_Sarray_Sptrmap | [
"Constructs",
"all",
"buckets",
"w",
".",
"r",
".",
"t",
".",
"q",
"-",
"gram",
"size",
"q",
"the",
"up",
"to",
"prefix",
"q",
"sorted",
"suffix",
"array",
"and",
"the",
"bucket",
"-",
"pointer",
"table",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java#L802-L834 |
535 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java | BPR.determinePower2Alpha_Buckets_Sarray_Sptrmap | private int[] determinePower2Alpha_Buckets_Sarray_Sptrmap(int q) {
int strLen = length;
int exp2 = kbs_getExp_Ulong(2, alphabet.size);
if (exp2 < 0) {
throw new RuntimeException("value out of bounds");
}
int[] buckets = determinePower2Alpha_Buckets_Sarray(q);
this.sufPtrMap = new int[strLen + 2 * q + 1];
int mappedUcharArray = 0;
int hashCode = 0;
int j;
for (j = 0; j < q; j++) {
hashCode = hashCode << exp2;
hashCode += seq[start + mappedUcharArray + j];
}
int tempModulo = 0;
tempModulo = ~tempModulo;
tempModulo = tempModulo << (exp2 * (q - 1));
tempModulo = ~tempModulo;
mappedUcharArray += q;
for (j = 0; j < strLen - 1; j++) {
sufPtrMap[j] = (buckets[hashCode + 1]) - 1;
hashCode = hashCode & tempModulo;
hashCode = hashCode << exp2;
hashCode = hashCode | seq[start + mappedUcharArray];
mappedUcharArray++;
}
sufPtrMap[j] = buckets[hashCode];
int beginPtr = -1;
for (j = strLen; j <= strLen + 2 * q; j++) {
sufPtrMap[j] = beginPtr--;
}
return buckets;
} | java | private int[] determinePower2Alpha_Buckets_Sarray_Sptrmap(int q) {
int strLen = length;
int exp2 = kbs_getExp_Ulong(2, alphabet.size);
if (exp2 < 0) {
throw new RuntimeException("value out of bounds");
}
int[] buckets = determinePower2Alpha_Buckets_Sarray(q);
this.sufPtrMap = new int[strLen + 2 * q + 1];
int mappedUcharArray = 0;
int hashCode = 0;
int j;
for (j = 0; j < q; j++) {
hashCode = hashCode << exp2;
hashCode += seq[start + mappedUcharArray + j];
}
int tempModulo = 0;
tempModulo = ~tempModulo;
tempModulo = tempModulo << (exp2 * (q - 1));
tempModulo = ~tempModulo;
mappedUcharArray += q;
for (j = 0; j < strLen - 1; j++) {
sufPtrMap[j] = (buckets[hashCode + 1]) - 1;
hashCode = hashCode & tempModulo;
hashCode = hashCode << exp2;
hashCode = hashCode | seq[start + mappedUcharArray];
mappedUcharArray++;
}
sufPtrMap[j] = buckets[hashCode];
int beginPtr = -1;
for (j = strLen; j <= strLen + 2 * q; j++) {
sufPtrMap[j] = beginPtr--;
}
return buckets;
} | [
"private",
"int",
"[",
"]",
"determinePower2Alpha_Buckets_Sarray_Sptrmap",
"(",
"int",
"q",
")",
"{",
"int",
"strLen",
"=",
"length",
";",
"int",
"exp2",
"=",
"kbs_getExp_Ulong",
"(",
"2",
",",
"alphabet",
".",
"size",
")",
";",
"if",
"(",
"exp2",
"<",
"0",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"value out of bounds\"",
")",
";",
"}",
"int",
"[",
"]",
"buckets",
"=",
"determinePower2Alpha_Buckets_Sarray",
"(",
"q",
")",
";",
"this",
".",
"sufPtrMap",
"=",
"new",
"int",
"[",
"strLen",
"+",
"2",
"*",
"q",
"+",
"1",
"]",
";",
"int",
"mappedUcharArray",
"=",
"0",
";",
"int",
"hashCode",
"=",
"0",
";",
"int",
"j",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"q",
";",
"j",
"++",
")",
"{",
"hashCode",
"=",
"hashCode",
"<<",
"exp2",
";",
"hashCode",
"+=",
"seq",
"[",
"start",
"+",
"mappedUcharArray",
"+",
"j",
"]",
";",
"}",
"int",
"tempModulo",
"=",
"0",
";",
"tempModulo",
"=",
"~",
"tempModulo",
";",
"tempModulo",
"=",
"tempModulo",
"<<",
"(",
"exp2",
"*",
"(",
"q",
"-",
"1",
")",
")",
";",
"tempModulo",
"=",
"~",
"tempModulo",
";",
"mappedUcharArray",
"+=",
"q",
";",
"for",
"(",
"j",
"=",
"0",
";",
"j",
"<",
"strLen",
"-",
"1",
";",
"j",
"++",
")",
"{",
"sufPtrMap",
"[",
"j",
"]",
"=",
"(",
"buckets",
"[",
"hashCode",
"+",
"1",
"]",
")",
"-",
"1",
";",
"hashCode",
"=",
"hashCode",
"&",
"tempModulo",
";",
"hashCode",
"=",
"hashCode",
"<<",
"exp2",
";",
"hashCode",
"=",
"hashCode",
"|",
"seq",
"[",
"start",
"+",
"mappedUcharArray",
"]",
";",
"mappedUcharArray",
"++",
";",
"}",
"sufPtrMap",
"[",
"j",
"]",
"=",
"buckets",
"[",
"hashCode",
"]",
";",
"int",
"beginPtr",
"=",
"-",
"1",
";",
"for",
"(",
"j",
"=",
"strLen",
";",
"j",
"<=",
"strLen",
"+",
"2",
"*",
"q",
";",
"j",
"++",
")",
"{",
"sufPtrMap",
"[",
"j",
"]",
"=",
"beginPtr",
"--",
";",
"}",
"return",
"buckets",
";",
"}"
] | Constructs all buckets w.r.t. q-gram size q, the up to prefix length q sorted
suffix array, and the bucket-pointer table.
@param q size of q-gram.
@return Buckets containing pointers into the suffix array.
@see #determine_Buckets_Sarray_Sptrmap | [
"Constructs",
"all",
"buckets",
"w",
".",
"r",
".",
"t",
".",
"q",
"-",
"gram",
"size",
"q",
"the",
"up",
"to",
"prefix",
"length",
"q",
"sorted",
"suffix",
"array",
"and",
"the",
"bucket",
"-",
"pointer",
"table",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/BPR.java#L931-L965 |
536 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.ssMergeForward | private void ssMergeForward(int PA, int first, int middle, int last, int buf,
int depth) {
// PA, first, middle, last, buf are pointers to SA
int a, b, c, bufend;// pointers to SA
int t, r;
bufend = buf + (middle - first) - 1;
ssBlockSwap(buf, first, middle - first);
for (t = SA[a = first], b = buf, c = middle; ; ) {
r = ssCompare(PA + SA[b], PA + SA[c], depth);
if (r < 0) {
do {
SA[a++] = SA[b];
if (bufend <= b) {
SA[bufend] = t;
return;
}
SA[b++] = SA[a];
}
while (SA[b] < 0);
} else if (r > 0) {
do {
SA[a++] = SA[c];
SA[c++] = SA[a];
if (last <= c) {
while (b < bufend) {
SA[a++] = SA[b];
SA[b++] = SA[a];
}
SA[a] = SA[b];
SA[b] = t;
return;
}
}
while (SA[c] < 0);
} else {
SA[c] = ~SA[c];
do {
SA[a++] = SA[b];
if (bufend <= b) {
SA[bufend] = t;
return;
}
SA[b++] = SA[a];
}
while (SA[b] < 0);
do {
SA[a++] = SA[c];
SA[c++] = SA[a];
if (last <= c) {
while (b < bufend) {
SA[a++] = SA[b];
SA[b++] = SA[a];
}
SA[a] = SA[b];
SA[b] = t;
return;
}
}
while (SA[c] < 0);
}
}
} | java | private void ssMergeForward(int PA, int first, int middle, int last, int buf,
int depth) {
// PA, first, middle, last, buf are pointers to SA
int a, b, c, bufend;// pointers to SA
int t, r;
bufend = buf + (middle - first) - 1;
ssBlockSwap(buf, first, middle - first);
for (t = SA[a = first], b = buf, c = middle; ; ) {
r = ssCompare(PA + SA[b], PA + SA[c], depth);
if (r < 0) {
do {
SA[a++] = SA[b];
if (bufend <= b) {
SA[bufend] = t;
return;
}
SA[b++] = SA[a];
}
while (SA[b] < 0);
} else if (r > 0) {
do {
SA[a++] = SA[c];
SA[c++] = SA[a];
if (last <= c) {
while (b < bufend) {
SA[a++] = SA[b];
SA[b++] = SA[a];
}
SA[a] = SA[b];
SA[b] = t;
return;
}
}
while (SA[c] < 0);
} else {
SA[c] = ~SA[c];
do {
SA[a++] = SA[b];
if (bufend <= b) {
SA[bufend] = t;
return;
}
SA[b++] = SA[a];
}
while (SA[b] < 0);
do {
SA[a++] = SA[c];
SA[c++] = SA[a];
if (last <= c) {
while (b < bufend) {
SA[a++] = SA[b];
SA[b++] = SA[a];
}
SA[a] = SA[b];
SA[b] = t;
return;
}
}
while (SA[c] < 0);
}
}
} | [
"private",
"void",
"ssMergeForward",
"(",
"int",
"PA",
",",
"int",
"first",
",",
"int",
"middle",
",",
"int",
"last",
",",
"int",
"buf",
",",
"int",
"depth",
")",
"{",
"// PA, first, middle, last, buf are pointers to SA",
"int",
"a",
",",
"b",
",",
"c",
",",
"bufend",
";",
"// pointers to SA",
"int",
"t",
",",
"r",
";",
"bufend",
"=",
"buf",
"+",
"(",
"middle",
"-",
"first",
")",
"-",
"1",
";",
"ssBlockSwap",
"(",
"buf",
",",
"first",
",",
"middle",
"-",
"first",
")",
";",
"for",
"(",
"t",
"=",
"SA",
"[",
"a",
"=",
"first",
"]",
",",
"b",
"=",
"buf",
",",
"c",
"=",
"middle",
";",
";",
")",
"{",
"r",
"=",
"ssCompare",
"(",
"PA",
"+",
"SA",
"[",
"b",
"]",
",",
"PA",
"+",
"SA",
"[",
"c",
"]",
",",
"depth",
")",
";",
"if",
"(",
"r",
"<",
"0",
")",
"{",
"do",
"{",
"SA",
"[",
"a",
"++",
"]",
"=",
"SA",
"[",
"b",
"]",
";",
"if",
"(",
"bufend",
"<=",
"b",
")",
"{",
"SA",
"[",
"bufend",
"]",
"=",
"t",
";",
"return",
";",
"}",
"SA",
"[",
"b",
"++",
"]",
"=",
"SA",
"[",
"a",
"]",
";",
"}",
"while",
"(",
"SA",
"[",
"b",
"]",
"<",
"0",
")",
";",
"}",
"else",
"if",
"(",
"r",
">",
"0",
")",
"{",
"do",
"{",
"SA",
"[",
"a",
"++",
"]",
"=",
"SA",
"[",
"c",
"]",
";",
"SA",
"[",
"c",
"++",
"]",
"=",
"SA",
"[",
"a",
"]",
";",
"if",
"(",
"last",
"<=",
"c",
")",
"{",
"while",
"(",
"b",
"<",
"bufend",
")",
"{",
"SA",
"[",
"a",
"++",
"]",
"=",
"SA",
"[",
"b",
"]",
";",
"SA",
"[",
"b",
"++",
"]",
"=",
"SA",
"[",
"a",
"]",
";",
"}",
"SA",
"[",
"a",
"]",
"=",
"SA",
"[",
"b",
"]",
";",
"SA",
"[",
"b",
"]",
"=",
"t",
";",
"return",
";",
"}",
"}",
"while",
"(",
"SA",
"[",
"c",
"]",
"<",
"0",
")",
";",
"}",
"else",
"{",
"SA",
"[",
"c",
"]",
"=",
"~",
"SA",
"[",
"c",
"]",
";",
"do",
"{",
"SA",
"[",
"a",
"++",
"]",
"=",
"SA",
"[",
"b",
"]",
";",
"if",
"(",
"bufend",
"<=",
"b",
")",
"{",
"SA",
"[",
"bufend",
"]",
"=",
"t",
";",
"return",
";",
"}",
"SA",
"[",
"b",
"++",
"]",
"=",
"SA",
"[",
"a",
"]",
";",
"}",
"while",
"(",
"SA",
"[",
"b",
"]",
"<",
"0",
")",
";",
"do",
"{",
"SA",
"[",
"a",
"++",
"]",
"=",
"SA",
"[",
"c",
"]",
";",
"SA",
"[",
"c",
"++",
"]",
"=",
"SA",
"[",
"a",
"]",
";",
"if",
"(",
"last",
"<=",
"c",
")",
"{",
"while",
"(",
"b",
"<",
"bufend",
")",
"{",
"SA",
"[",
"a",
"++",
"]",
"=",
"SA",
"[",
"b",
"]",
";",
"SA",
"[",
"b",
"++",
"]",
"=",
"SA",
"[",
"a",
"]",
";",
"}",
"SA",
"[",
"a",
"]",
"=",
"SA",
"[",
"b",
"]",
";",
"SA",
"[",
"b",
"]",
"=",
"t",
";",
"return",
";",
"}",
"}",
"while",
"(",
"SA",
"[",
"c",
"]",
"<",
"0",
")",
";",
"}",
"}",
"}"
] | Merge-forward with internal buffer. | [
"Merge",
"-",
"forward",
"with",
"internal",
"buffer",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L759-L824 |
537 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.ssInsertionSort | private void ssInsertionSort(int PA, int first, int last, int depth) {
// PA, first, last are pointers in SA
int i, j;// pointers in SA
int t, r;
for (i = last - 2; first <= i; --i) {
for (t = SA[i], j = i + 1; 0 < (r = ssCompare(PA + t, PA + SA[j], depth)); ) {
do {
SA[j - 1] = SA[j];
}
while ((++j < last) && (SA[j] < 0));
if (last <= j) {
break;
}
}
if (r == 0) {
SA[j] = ~SA[j];
}
SA[j - 1] = t;
}
} | java | private void ssInsertionSort(int PA, int first, int last, int depth) {
// PA, first, last are pointers in SA
int i, j;// pointers in SA
int t, r;
for (i = last - 2; first <= i; --i) {
for (t = SA[i], j = i + 1; 0 < (r = ssCompare(PA + t, PA + SA[j], depth)); ) {
do {
SA[j - 1] = SA[j];
}
while ((++j < last) && (SA[j] < 0));
if (last <= j) {
break;
}
}
if (r == 0) {
SA[j] = ~SA[j];
}
SA[j - 1] = t;
}
} | [
"private",
"void",
"ssInsertionSort",
"(",
"int",
"PA",
",",
"int",
"first",
",",
"int",
"last",
",",
"int",
"depth",
")",
"{",
"// PA, first, last are pointers in SA",
"int",
"i",
",",
"j",
";",
"// pointers in SA",
"int",
"t",
",",
"r",
";",
"for",
"(",
"i",
"=",
"last",
"-",
"2",
";",
"first",
"<=",
"i",
";",
"--",
"i",
")",
"{",
"for",
"(",
"t",
"=",
"SA",
"[",
"i",
"]",
",",
"j",
"=",
"i",
"+",
"1",
";",
"0",
"<",
"(",
"r",
"=",
"ssCompare",
"(",
"PA",
"+",
"t",
",",
"PA",
"+",
"SA",
"[",
"j",
"]",
",",
"depth",
")",
")",
";",
")",
"{",
"do",
"{",
"SA",
"[",
"j",
"-",
"1",
"]",
"=",
"SA",
"[",
"j",
"]",
";",
"}",
"while",
"(",
"(",
"++",
"j",
"<",
"last",
")",
"&&",
"(",
"SA",
"[",
"j",
"]",
"<",
"0",
")",
")",
";",
"if",
"(",
"last",
"<=",
"j",
")",
"{",
"break",
";",
"}",
"}",
"if",
"(",
"r",
"==",
"0",
")",
"{",
"SA",
"[",
"j",
"]",
"=",
"~",
"SA",
"[",
"j",
"]",
";",
"}",
"SA",
"[",
"j",
"-",
"1",
"]",
"=",
"t",
";",
"}",
"}"
] | Insertionsort for small size groups | [
"Insertionsort",
"for",
"small",
"size",
"groups"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L954-L975 |
538 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.ssMedian5 | private int ssMedian5(int Td, int PA, int v1, int v2, int v3, int v4, int v5) {
int t;
if (T[start + Td + SA[PA + SA[v2]]] > T[start + Td + SA[PA + SA[v3]]]) {
t = v2;
v2 = v3;
v3 = t;
}
if (T[start + Td + SA[PA + SA[v4]]] > T[start + Td + SA[PA + SA[v5]]]) {
t = v4;
v4 = v5;
v5 = t;
}
if (T[start + Td + SA[PA + SA[v2]]] > T[start + Td + SA[PA + SA[v4]]]) {
t = v2;
v2 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (T[start + Td + SA[PA + SA[v1]]] > T[start + Td + SA[PA + SA[v3]]]) {
t = v1;
v1 = v3;
v3 = t;
}
if (T[start + Td + SA[PA + SA[v1]]] > T[start + Td + SA[PA + SA[v4]]]) {
t = v1;
v1 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (T[start + Td + SA[PA + SA[v3]]] > T[start + Td + SA[PA + SA[v4]]]) {
return v4;
}
return v3;
} | java | private int ssMedian5(int Td, int PA, int v1, int v2, int v3, int v4, int v5) {
int t;
if (T[start + Td + SA[PA + SA[v2]]] > T[start + Td + SA[PA + SA[v3]]]) {
t = v2;
v2 = v3;
v3 = t;
}
if (T[start + Td + SA[PA + SA[v4]]] > T[start + Td + SA[PA + SA[v5]]]) {
t = v4;
v4 = v5;
v5 = t;
}
if (T[start + Td + SA[PA + SA[v2]]] > T[start + Td + SA[PA + SA[v4]]]) {
t = v2;
v2 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (T[start + Td + SA[PA + SA[v1]]] > T[start + Td + SA[PA + SA[v3]]]) {
t = v1;
v1 = v3;
v3 = t;
}
if (T[start + Td + SA[PA + SA[v1]]] > T[start + Td + SA[PA + SA[v4]]]) {
t = v1;
v1 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (T[start + Td + SA[PA + SA[v3]]] > T[start + Td + SA[PA + SA[v4]]]) {
return v4;
}
return v3;
} | [
"private",
"int",
"ssMedian5",
"(",
"int",
"Td",
",",
"int",
"PA",
",",
"int",
"v1",
",",
"int",
"v2",
",",
"int",
"v3",
",",
"int",
"v4",
",",
"int",
"v5",
")",
"{",
"int",
"t",
";",
"if",
"(",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v2",
"]",
"]",
"]",
">",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v3",
"]",
"]",
"]",
")",
"{",
"t",
"=",
"v2",
";",
"v2",
"=",
"v3",
";",
"v3",
"=",
"t",
";",
"}",
"if",
"(",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v4",
"]",
"]",
"]",
">",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v5",
"]",
"]",
"]",
")",
"{",
"t",
"=",
"v4",
";",
"v4",
"=",
"v5",
";",
"v5",
"=",
"t",
";",
"}",
"if",
"(",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v2",
"]",
"]",
"]",
">",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v4",
"]",
"]",
"]",
")",
"{",
"t",
"=",
"v2",
";",
"v2",
"=",
"v4",
";",
"v4",
"=",
"t",
";",
"t",
"=",
"v3",
";",
"v3",
"=",
"v5",
";",
"v5",
"=",
"t",
";",
"}",
"if",
"(",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v1",
"]",
"]",
"]",
">",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v3",
"]",
"]",
"]",
")",
"{",
"t",
"=",
"v1",
";",
"v1",
"=",
"v3",
";",
"v3",
"=",
"t",
";",
"}",
"if",
"(",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v1",
"]",
"]",
"]",
">",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v4",
"]",
"]",
"]",
")",
"{",
"t",
"=",
"v1",
";",
"v1",
"=",
"v4",
";",
"v4",
"=",
"t",
";",
"t",
"=",
"v3",
";",
"v3",
"=",
"v5",
";",
"v5",
"=",
"t",
";",
"}",
"if",
"(",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v3",
"]",
"]",
"]",
">",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"v4",
"]",
"]",
"]",
")",
"{",
"return",
"v4",
";",
"}",
"return",
"v3",
";",
"}"
] | Returns the median of five elements | [
"Returns",
"the",
"median",
"of",
"five",
"elements"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L1219-L1257 |
539 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.ssPartition | private int ssPartition(int PA, int first, int last, int depth) {
int a, b;// SA pointer
int t;
for (a = first - 1, b = last; ; ) {
for (; (++a < b) && ((SA[PA + SA[a]] + depth) >= (SA[PA + SA[a] + 1] + 1)); ) {
SA[a] = ~SA[a];
}
for (; (a < --b) && ((SA[PA + SA[b]] + depth) < (SA[PA + SA[b] + 1] + 1)); ) {
}
if (b <= a) {
break;
}
t = ~SA[b];
SA[b] = SA[a];
SA[a] = t;
}
if (first < a) {
SA[first] = ~SA[first];
}
return a;
} | java | private int ssPartition(int PA, int first, int last, int depth) {
int a, b;// SA pointer
int t;
for (a = first - 1, b = last; ; ) {
for (; (++a < b) && ((SA[PA + SA[a]] + depth) >= (SA[PA + SA[a] + 1] + 1)); ) {
SA[a] = ~SA[a];
}
for (; (a < --b) && ((SA[PA + SA[b]] + depth) < (SA[PA + SA[b] + 1] + 1)); ) {
}
if (b <= a) {
break;
}
t = ~SA[b];
SA[b] = SA[a];
SA[a] = t;
}
if (first < a) {
SA[first] = ~SA[first];
}
return a;
} | [
"private",
"int",
"ssPartition",
"(",
"int",
"PA",
",",
"int",
"first",
",",
"int",
"last",
",",
"int",
"depth",
")",
"{",
"int",
"a",
",",
"b",
";",
"// SA pointer",
"int",
"t",
";",
"for",
"(",
"a",
"=",
"first",
"-",
"1",
",",
"b",
"=",
"last",
";",
";",
")",
"{",
"for",
"(",
";",
"(",
"++",
"a",
"<",
"b",
")",
"&&",
"(",
"(",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"a",
"]",
"]",
"+",
"depth",
")",
">=",
"(",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"a",
"]",
"+",
"1",
"]",
"+",
"1",
")",
")",
";",
")",
"{",
"SA",
"[",
"a",
"]",
"=",
"~",
"SA",
"[",
"a",
"]",
";",
"}",
"for",
"(",
";",
"(",
"a",
"<",
"--",
"b",
")",
"&&",
"(",
"(",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"b",
"]",
"]",
"+",
"depth",
")",
"<",
"(",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"b",
"]",
"+",
"1",
"]",
"+",
"1",
")",
")",
";",
")",
"{",
"}",
"if",
"(",
"b",
"<=",
"a",
")",
"{",
"break",
";",
"}",
"t",
"=",
"~",
"SA",
"[",
"b",
"]",
";",
"SA",
"[",
"b",
"]",
"=",
"SA",
"[",
"a",
"]",
";",
"SA",
"[",
"a",
"]",
"=",
"t",
";",
"}",
"if",
"(",
"first",
"<",
"a",
")",
"{",
"SA",
"[",
"first",
"]",
"=",
"~",
"SA",
"[",
"first",
"]",
";",
"}",
"return",
"a",
";",
"}"
] | Binary partition for substrings. | [
"Binary",
"partition",
"for",
"substrings",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L1281-L1301 |
540 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.ssHeapSort | private void ssHeapSort(int Td, int PA, int sa, int size) {
int i, m, t;
m = size;
if ((size % 2) == 0) {
m--;
if (T[start + Td + SA[PA + SA[sa + (m / 2)]]] < T[start + Td
+ SA[PA + SA[sa + m]]]) {
swapInSA(sa + m, sa + (m / 2));
}
}
for (i = m / 2 - 1; 0 <= i; --i) {
ssFixDown(Td, PA, sa, i, m);
}
if ((size % 2) == 0) {
swapInSA(sa, sa + m);
ssFixDown(Td, PA, sa, 0, m);
}
for (i = m - 1; 0 < i; --i) {
t = SA[sa];
SA[sa] = SA[sa + i];
ssFixDown(Td, PA, sa, 0, i);
SA[sa + i] = t;
}
} | java | private void ssHeapSort(int Td, int PA, int sa, int size) {
int i, m, t;
m = size;
if ((size % 2) == 0) {
m--;
if (T[start + Td + SA[PA + SA[sa + (m / 2)]]] < T[start + Td
+ SA[PA + SA[sa + m]]]) {
swapInSA(sa + m, sa + (m / 2));
}
}
for (i = m / 2 - 1; 0 <= i; --i) {
ssFixDown(Td, PA, sa, i, m);
}
if ((size % 2) == 0) {
swapInSA(sa, sa + m);
ssFixDown(Td, PA, sa, 0, m);
}
for (i = m - 1; 0 < i; --i) {
t = SA[sa];
SA[sa] = SA[sa + i];
ssFixDown(Td, PA, sa, 0, i);
SA[sa + i] = t;
}
} | [
"private",
"void",
"ssHeapSort",
"(",
"int",
"Td",
",",
"int",
"PA",
",",
"int",
"sa",
",",
"int",
"size",
")",
"{",
"int",
"i",
",",
"m",
",",
"t",
";",
"m",
"=",
"size",
";",
"if",
"(",
"(",
"size",
"%",
"2",
")",
"==",
"0",
")",
"{",
"m",
"--",
";",
"if",
"(",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"sa",
"+",
"(",
"m",
"/",
"2",
")",
"]",
"]",
"]",
"<",
"T",
"[",
"start",
"+",
"Td",
"+",
"SA",
"[",
"PA",
"+",
"SA",
"[",
"sa",
"+",
"m",
"]",
"]",
"]",
")",
"{",
"swapInSA",
"(",
"sa",
"+",
"m",
",",
"sa",
"+",
"(",
"m",
"/",
"2",
")",
")",
";",
"}",
"}",
"for",
"(",
"i",
"=",
"m",
"/",
"2",
"-",
"1",
";",
"0",
"<=",
"i",
";",
"--",
"i",
")",
"{",
"ssFixDown",
"(",
"Td",
",",
"PA",
",",
"sa",
",",
"i",
",",
"m",
")",
";",
"}",
"if",
"(",
"(",
"size",
"%",
"2",
")",
"==",
"0",
")",
"{",
"swapInSA",
"(",
"sa",
",",
"sa",
"+",
"m",
")",
";",
"ssFixDown",
"(",
"Td",
",",
"PA",
",",
"sa",
",",
"0",
",",
"m",
")",
";",
"}",
"for",
"(",
"i",
"=",
"m",
"-",
"1",
";",
"0",
"<",
"i",
";",
"--",
"i",
")",
"{",
"t",
"=",
"SA",
"[",
"sa",
"]",
";",
"SA",
"[",
"sa",
"]",
"=",
"SA",
"[",
"sa",
"+",
"i",
"]",
";",
"ssFixDown",
"(",
"Td",
",",
"PA",
",",
"sa",
",",
"0",
",",
"i",
")",
";",
"SA",
"[",
"sa",
"+",
"i",
"]",
"=",
"t",
";",
"}",
"}"
] | Simple top-down heapsort. | [
"Simple",
"top",
"-",
"down",
"heapsort",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L1306-L1332 |
541 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.trSort | private void trSort(int ISA, int n, int depth) {
TRBudget budget = new TRBudget(trIlg(n) * 2 / 3, n);
int ISAd;
int first, last;// SA pointers
int t, skip, unsorted;
for (ISAd = ISA + depth; -n < SA[0]; ISAd += ISAd - ISA) {
first = 0;
skip = 0;
unsorted = 0;
do {
if ((t = SA[first]) < 0) {
first -= t;
skip += t;
} else {
if (skip != 0) {
SA[first + skip] = skip;
skip = 0;
}
last = SA[ISA + t] + 1;
if (1 < (last - first)) {
budget.count = 0;
trIntroSort(ISA, ISAd, first, last, budget);
if (budget.count != 0) {
unsorted += budget.count;
} else {
skip = first - last;
}
} else if ((last - first) == 1) {
skip = -1;
}
first = last;
}
}
while (first < n);
if (skip != 0) {
SA[first + skip] = skip;
}
if (unsorted == 0) {
break;
}
}
} | java | private void trSort(int ISA, int n, int depth) {
TRBudget budget = new TRBudget(trIlg(n) * 2 / 3, n);
int ISAd;
int first, last;// SA pointers
int t, skip, unsorted;
for (ISAd = ISA + depth; -n < SA[0]; ISAd += ISAd - ISA) {
first = 0;
skip = 0;
unsorted = 0;
do {
if ((t = SA[first]) < 0) {
first -= t;
skip += t;
} else {
if (skip != 0) {
SA[first + skip] = skip;
skip = 0;
}
last = SA[ISA + t] + 1;
if (1 < (last - first)) {
budget.count = 0;
trIntroSort(ISA, ISAd, first, last, budget);
if (budget.count != 0) {
unsorted += budget.count;
} else {
skip = first - last;
}
} else if ((last - first) == 1) {
skip = -1;
}
first = last;
}
}
while (first < n);
if (skip != 0) {
SA[first + skip] = skip;
}
if (unsorted == 0) {
break;
}
}
} | [
"private",
"void",
"trSort",
"(",
"int",
"ISA",
",",
"int",
"n",
",",
"int",
"depth",
")",
"{",
"TRBudget",
"budget",
"=",
"new",
"TRBudget",
"(",
"trIlg",
"(",
"n",
")",
"*",
"2",
"/",
"3",
",",
"n",
")",
";",
"int",
"ISAd",
";",
"int",
"first",
",",
"last",
";",
"// SA pointers",
"int",
"t",
",",
"skip",
",",
"unsorted",
";",
"for",
"(",
"ISAd",
"=",
"ISA",
"+",
"depth",
";",
"-",
"n",
"<",
"SA",
"[",
"0",
"]",
";",
"ISAd",
"+=",
"ISAd",
"-",
"ISA",
")",
"{",
"first",
"=",
"0",
";",
"skip",
"=",
"0",
";",
"unsorted",
"=",
"0",
";",
"do",
"{",
"if",
"(",
"(",
"t",
"=",
"SA",
"[",
"first",
"]",
")",
"<",
"0",
")",
"{",
"first",
"-=",
"t",
";",
"skip",
"+=",
"t",
";",
"}",
"else",
"{",
"if",
"(",
"skip",
"!=",
"0",
")",
"{",
"SA",
"[",
"first",
"+",
"skip",
"]",
"=",
"skip",
";",
"skip",
"=",
"0",
";",
"}",
"last",
"=",
"SA",
"[",
"ISA",
"+",
"t",
"]",
"+",
"1",
";",
"if",
"(",
"1",
"<",
"(",
"last",
"-",
"first",
")",
")",
"{",
"budget",
".",
"count",
"=",
"0",
";",
"trIntroSort",
"(",
"ISA",
",",
"ISAd",
",",
"first",
",",
"last",
",",
"budget",
")",
";",
"if",
"(",
"budget",
".",
"count",
"!=",
"0",
")",
"{",
"unsorted",
"+=",
"budget",
".",
"count",
";",
"}",
"else",
"{",
"skip",
"=",
"first",
"-",
"last",
";",
"}",
"}",
"else",
"if",
"(",
"(",
"last",
"-",
"first",
")",
"==",
"1",
")",
"{",
"skip",
"=",
"-",
"1",
";",
"}",
"first",
"=",
"last",
";",
"}",
"}",
"while",
"(",
"first",
"<",
"n",
")",
";",
"if",
"(",
"skip",
"!=",
"0",
")",
"{",
"SA",
"[",
"first",
"+",
"skip",
"]",
"=",
"skip",
";",
"}",
"if",
"(",
"unsorted",
"==",
"0",
")",
"{",
"break",
";",
"}",
"}",
"}"
] | Tandem repeat sort | [
"Tandem",
"repeat",
"sort"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L1378-L1419 |
542 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.trMedian5 | private int trMedian5(int ISAd, int v1, int v2, int v3, int v4, int v5) {
int t;
if (SA[ISAd + SA[v2]] > SA[ISAd + SA[v3]]) {
t = v2;
v2 = v3;
v3 = t;
}
if (SA[ISAd + SA[v4]] > SA[ISAd + SA[v5]]) {
t = v4;
v4 = v5;
v5 = t;
}
if (SA[ISAd + SA[v2]] > SA[ISAd + SA[v4]]) {
t = v2;
v2 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (SA[ISAd + SA[v1]] > SA[ISAd + SA[v3]]) {
t = v1;
v1 = v3;
v3 = t;
}
if (SA[ISAd + SA[v1]] > SA[ISAd + SA[v4]]) {
t = v1;
v1 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (SA[ISAd + SA[v3]] > SA[ISAd + SA[v4]]) {
return v4;
}
return v3;
} | java | private int trMedian5(int ISAd, int v1, int v2, int v3, int v4, int v5) {
int t;
if (SA[ISAd + SA[v2]] > SA[ISAd + SA[v3]]) {
t = v2;
v2 = v3;
v3 = t;
}
if (SA[ISAd + SA[v4]] > SA[ISAd + SA[v5]]) {
t = v4;
v4 = v5;
v5 = t;
}
if (SA[ISAd + SA[v2]] > SA[ISAd + SA[v4]]) {
t = v2;
v2 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (SA[ISAd + SA[v1]] > SA[ISAd + SA[v3]]) {
t = v1;
v1 = v3;
v3 = t;
}
if (SA[ISAd + SA[v1]] > SA[ISAd + SA[v4]]) {
t = v1;
v1 = v4;
v4 = t;
t = v3;
v3 = v5;
v5 = t;
}
if (SA[ISAd + SA[v3]] > SA[ISAd + SA[v4]]) {
return v4;
}
return v3;
} | [
"private",
"int",
"trMedian5",
"(",
"int",
"ISAd",
",",
"int",
"v1",
",",
"int",
"v2",
",",
"int",
"v3",
",",
"int",
"v4",
",",
"int",
"v5",
")",
"{",
"int",
"t",
";",
"if",
"(",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v2",
"]",
"]",
">",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v3",
"]",
"]",
")",
"{",
"t",
"=",
"v2",
";",
"v2",
"=",
"v3",
";",
"v3",
"=",
"t",
";",
"}",
"if",
"(",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v4",
"]",
"]",
">",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v5",
"]",
"]",
")",
"{",
"t",
"=",
"v4",
";",
"v4",
"=",
"v5",
";",
"v5",
"=",
"t",
";",
"}",
"if",
"(",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v2",
"]",
"]",
">",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v4",
"]",
"]",
")",
"{",
"t",
"=",
"v2",
";",
"v2",
"=",
"v4",
";",
"v4",
"=",
"t",
";",
"t",
"=",
"v3",
";",
"v3",
"=",
"v5",
";",
"v5",
"=",
"t",
";",
"}",
"if",
"(",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v1",
"]",
"]",
">",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v3",
"]",
"]",
")",
"{",
"t",
"=",
"v1",
";",
"v1",
"=",
"v3",
";",
"v3",
"=",
"t",
";",
"}",
"if",
"(",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v1",
"]",
"]",
">",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v4",
"]",
"]",
")",
"{",
"t",
"=",
"v1",
";",
"v1",
"=",
"v4",
";",
"v4",
"=",
"t",
";",
"t",
"=",
"v3",
";",
"v3",
"=",
"v5",
";",
"v5",
"=",
"t",
";",
"}",
"if",
"(",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v3",
"]",
"]",
">",
"SA",
"[",
"ISAd",
"+",
"SA",
"[",
"v4",
"]",
"]",
")",
"{",
"return",
"v4",
";",
"}",
"return",
"v3",
";",
"}"
] | Returns the median of five elements. | [
"Returns",
"the",
"median",
"of",
"five",
"elements",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L1893-L1930 |
543 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java | DivSufSort.trCopy | private void trCopy(int ISA, int first, int a, int b, int last, int depth) {
int c, d, e;// ptr
int s, v;
v = b - 1;
for (c = first, d = a - 1; c <= d; ++c) {
s = SA[c] - depth;
if ((0 <= s) && (SA[ISA + s] == v)) {
SA[++d] = s;
SA[ISA + s] = d;
}
}
for (c = last - 1, e = d + 1, d = b; e < d; --c) {
s = SA[c] - depth;
if ((0 <= s) && (SA[ISA + s] == v)) {
SA[--d] = s;
SA[ISA + s] = d;
}
}
} | java | private void trCopy(int ISA, int first, int a, int b, int last, int depth) {
int c, d, e;// ptr
int s, v;
v = b - 1;
for (c = first, d = a - 1; c <= d; ++c) {
s = SA[c] - depth;
if ((0 <= s) && (SA[ISA + s] == v)) {
SA[++d] = s;
SA[ISA + s] = d;
}
}
for (c = last - 1, e = d + 1, d = b; e < d; --c) {
s = SA[c] - depth;
if ((0 <= s) && (SA[ISA + s] == v)) {
SA[--d] = s;
SA[ISA + s] = d;
}
}
} | [
"private",
"void",
"trCopy",
"(",
"int",
"ISA",
",",
"int",
"first",
",",
"int",
"a",
",",
"int",
"b",
",",
"int",
"last",
",",
"int",
"depth",
")",
"{",
"int",
"c",
",",
"d",
",",
"e",
";",
"// ptr",
"int",
"s",
",",
"v",
";",
"v",
"=",
"b",
"-",
"1",
";",
"for",
"(",
"c",
"=",
"first",
",",
"d",
"=",
"a",
"-",
"1",
";",
"c",
"<=",
"d",
";",
"++",
"c",
")",
"{",
"s",
"=",
"SA",
"[",
"c",
"]",
"-",
"depth",
";",
"if",
"(",
"(",
"0",
"<=",
"s",
")",
"&&",
"(",
"SA",
"[",
"ISA",
"+",
"s",
"]",
"==",
"v",
")",
")",
"{",
"SA",
"[",
"++",
"d",
"]",
"=",
"s",
";",
"SA",
"[",
"ISA",
"+",
"s",
"]",
"=",
"d",
";",
"}",
"}",
"for",
"(",
"c",
"=",
"last",
"-",
"1",
",",
"e",
"=",
"d",
"+",
"1",
",",
"d",
"=",
"b",
";",
"e",
"<",
"d",
";",
"--",
"c",
")",
"{",
"s",
"=",
"SA",
"[",
"c",
"]",
"-",
"depth",
";",
"if",
"(",
"(",
"0",
"<=",
"s",
")",
"&&",
"(",
"SA",
"[",
"ISA",
"+",
"s",
"]",
"==",
"v",
")",
")",
"{",
"SA",
"[",
"--",
"d",
"]",
"=",
"s",
";",
"SA",
"[",
"ISA",
"+",
"s",
"]",
"=",
"d",
";",
"}",
"}",
"}"
] | sort suffixes of middle partition by using sorted order of suffixes of left and
right partition. | [
"sort",
"suffixes",
"of",
"middle",
"partition",
"by",
"using",
"sorted",
"order",
"of",
"suffixes",
"of",
"left",
"and",
"right",
"partition",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/DivSufSort.java#L2080-L2099 |
544 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Sequence.java | Sequence.add | void add(S sequence) {
for (I item : sequence) {
masterSequence.add(item);
}
SequenceTerminal<S> terminal = new SequenceTerminal<>(sequence);
masterSequence.add(terminal);
} | java | void add(S sequence) {
for (I item : sequence) {
masterSequence.add(item);
}
SequenceTerminal<S> terminal = new SequenceTerminal<>(sequence);
masterSequence.add(terminal);
} | [
"void",
"add",
"(",
"S",
"sequence",
")",
"{",
"for",
"(",
"I",
"item",
":",
"sequence",
")",
"{",
"masterSequence",
".",
"add",
"(",
"item",
")",
";",
"}",
"SequenceTerminal",
"<",
"S",
">",
"terminal",
"=",
"new",
"SequenceTerminal",
"<>",
"(",
"sequence",
")",
";",
"masterSequence",
".",
"add",
"(",
"terminal",
")",
";",
"}"
] | Adds a Sequence to the suffix tree.
@param sequence | [
"Adds",
"a",
"Sequence",
"to",
"the",
"suffix",
"tree",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Sequence.java#L49-L55 |
545 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Sequence.java | Sequence.iterator | @Override
public Iterator<Object> iterator() {
return new Iterator<Object>() {
int currentPosition = 0;
@Override
public boolean hasNext() {
return masterSequence.size() > currentPosition;
}
@Override
public Object next() {
if (currentPosition <= masterSequence.size())
return masterSequence.get(currentPosition++);
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove is not supported.");
}
};
} | java | @Override
public Iterator<Object> iterator() {
return new Iterator<Object>() {
int currentPosition = 0;
@Override
public boolean hasNext() {
return masterSequence.size() > currentPosition;
}
@Override
public Object next() {
if (currentPosition <= masterSequence.size())
return masterSequence.get(currentPosition++);
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Remove is not supported.");
}
};
} | [
"@",
"Override",
"public",
"Iterator",
"<",
"Object",
">",
"iterator",
"(",
")",
"{",
"return",
"new",
"Iterator",
"<",
"Object",
">",
"(",
")",
"{",
"int",
"currentPosition",
"=",
"0",
";",
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"return",
"masterSequence",
".",
"size",
"(",
")",
">",
"currentPosition",
";",
"}",
"@",
"Override",
"public",
"Object",
"next",
"(",
")",
"{",
"if",
"(",
"currentPosition",
"<=",
"masterSequence",
".",
"size",
"(",
")",
")",
"return",
"masterSequence",
".",
"get",
"(",
"currentPosition",
"++",
")",
";",
"return",
"null",
";",
"}",
"@",
"Override",
"public",
"void",
"remove",
"(",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"Remove is not supported.\"",
")",
";",
"}",
"}",
";",
"}"
] | Retrieves an iterator for the sequence. | [
"Retrieves",
"an",
"iterator",
"for",
"the",
"sequence",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Sequence.java#L60-L85 |
546 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java | Edge.insert | void insert(Suffix<T, S> suffix, ActivePoint<T, S> activePoint) {
Object item = suffix.getEndItem();
Object nextItem = getItemAt(activePoint.getLength());
if (item.equals(nextItem)) {
activePoint.incrementLength();
} else {
split(suffix, activePoint);
suffix.decrement();
activePoint.updateAfterInsert(suffix);
if (suffix.isEmpty()) {
}
else
tree.insert(suffix);
}
} | java | void insert(Suffix<T, S> suffix, ActivePoint<T, S> activePoint) {
Object item = suffix.getEndItem();
Object nextItem = getItemAt(activePoint.getLength());
if (item.equals(nextItem)) {
activePoint.incrementLength();
} else {
split(suffix, activePoint);
suffix.decrement();
activePoint.updateAfterInsert(suffix);
if (suffix.isEmpty()) {
}
else
tree.insert(suffix);
}
} | [
"void",
"insert",
"(",
"Suffix",
"<",
"T",
",",
"S",
">",
"suffix",
",",
"ActivePoint",
"<",
"T",
",",
"S",
">",
"activePoint",
")",
"{",
"Object",
"item",
"=",
"suffix",
".",
"getEndItem",
"(",
")",
";",
"Object",
"nextItem",
"=",
"getItemAt",
"(",
"activePoint",
".",
"getLength",
"(",
")",
")",
";",
"if",
"(",
"item",
".",
"equals",
"(",
"nextItem",
")",
")",
"{",
"activePoint",
".",
"incrementLength",
"(",
")",
";",
"}",
"else",
"{",
"split",
"(",
"suffix",
",",
"activePoint",
")",
";",
"suffix",
".",
"decrement",
"(",
")",
";",
"activePoint",
".",
"updateAfterInsert",
"(",
"suffix",
")",
";",
"if",
"(",
"suffix",
".",
"isEmpty",
"(",
")",
")",
"{",
"}",
"else",
"tree",
".",
"insert",
"(",
"suffix",
")",
";",
"}",
"}"
] | Insert the given suffix at the supplied active point.
@param suffix The suffix to insert.
@param activePoint The active point to insert it at.
@return | [
"Insert",
"the",
"given",
"suffix",
"at",
"the",
"supplied",
"active",
"point",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java#L53-L68 |
547 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java | Edge.split | private void split(Suffix<T, S> suffix, ActivePoint<T, S> activePoint) {
Node<T, S> breakNode = new Node<>(this, sequence, tree);
Edge<T, S> newEdge = new Edge<>(suffix.getEndPosition() - 1, breakNode,
sequence, tree);
breakNode.insert(newEdge);
Edge<T, S> oldEdge = new Edge<>(start + activePoint.getLength(),
breakNode, sequence, tree);
oldEdge.end = end;
oldEdge.terminal = this.terminal;
breakNode.insert(oldEdge);
this.terminal = breakNode;
end = start + activePoint.getLength();
tree.setSuffixLink(breakNode);
tree.incrementInsertCount();
} | java | private void split(Suffix<T, S> suffix, ActivePoint<T, S> activePoint) {
Node<T, S> breakNode = new Node<>(this, sequence, tree);
Edge<T, S> newEdge = new Edge<>(suffix.getEndPosition() - 1, breakNode,
sequence, tree);
breakNode.insert(newEdge);
Edge<T, S> oldEdge = new Edge<>(start + activePoint.getLength(),
breakNode, sequence, tree);
oldEdge.end = end;
oldEdge.terminal = this.terminal;
breakNode.insert(oldEdge);
this.terminal = breakNode;
end = start + activePoint.getLength();
tree.setSuffixLink(breakNode);
tree.incrementInsertCount();
} | [
"private",
"void",
"split",
"(",
"Suffix",
"<",
"T",
",",
"S",
">",
"suffix",
",",
"ActivePoint",
"<",
"T",
",",
"S",
">",
"activePoint",
")",
"{",
"Node",
"<",
"T",
",",
"S",
">",
"breakNode",
"=",
"new",
"Node",
"<>",
"(",
"this",
",",
"sequence",
",",
"tree",
")",
";",
"Edge",
"<",
"T",
",",
"S",
">",
"newEdge",
"=",
"new",
"Edge",
"<>",
"(",
"suffix",
".",
"getEndPosition",
"(",
")",
"-",
"1",
",",
"breakNode",
",",
"sequence",
",",
"tree",
")",
";",
"breakNode",
".",
"insert",
"(",
"newEdge",
")",
";",
"Edge",
"<",
"T",
",",
"S",
">",
"oldEdge",
"=",
"new",
"Edge",
"<>",
"(",
"start",
"+",
"activePoint",
".",
"getLength",
"(",
")",
",",
"breakNode",
",",
"sequence",
",",
"tree",
")",
";",
"oldEdge",
".",
"end",
"=",
"end",
";",
"oldEdge",
".",
"terminal",
"=",
"this",
".",
"terminal",
";",
"breakNode",
".",
"insert",
"(",
"oldEdge",
")",
";",
"this",
".",
"terminal",
"=",
"breakNode",
";",
"end",
"=",
"start",
"+",
"activePoint",
".",
"getLength",
"(",
")",
";",
"tree",
".",
"setSuffixLink",
"(",
"breakNode",
")",
";",
"tree",
".",
"incrementInsertCount",
"(",
")",
";",
"}"
] | Splits the edge to enable the insertion of supplied suffix at the
supplied active point.
@param suffix The suffix to insert.
@param activePoint The active point to insert it at. | [
"Splits",
"the",
"edge",
"to",
"enable",
"the",
"insertion",
"of",
"supplied",
"suffix",
"at",
"the",
"supplied",
"active",
"point",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java#L77-L91 |
548 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java | Edge.getItemAt | @SuppressWarnings("unchecked")
T getItemAt(int position) {
if (position > getLength())
throw new IllegalArgumentException("Index " + position
+ " is greater than " + getLength()
+ " - the length of this edge.");
return (T) sequence.getItem(start + position);
} | java | @SuppressWarnings("unchecked")
T getItemAt(int position) {
if (position > getLength())
throw new IllegalArgumentException("Index " + position
+ " is greater than " + getLength()
+ " - the length of this edge.");
return (T) sequence.getItem(start + position);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"T",
"getItemAt",
"(",
"int",
"position",
")",
"{",
"if",
"(",
"position",
">",
"getLength",
"(",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Index \"",
"+",
"position",
"+",
"\" is greater than \"",
"+",
"getLength",
"(",
")",
"+",
"\" - the length of this edge.\"",
")",
";",
"return",
"(",
"T",
")",
"sequence",
".",
"getItem",
"(",
"start",
"+",
"position",
")",
";",
"}"
] | Retrieves the item at given position within the current edge.
@param position The index of the item to retrieve relative to the start of
edge.
@return The item at position.
@throws IllegalArgumentException when the position exceeds the length of the current edge. | [
"Retrieves",
"the",
"item",
"at",
"given",
"position",
"within",
"the",
"current",
"edge",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java#L140-L147 |
549 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java | Edge.iterator | public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentPosition = start;
private boolean hasNext = true;
public boolean hasNext() {
return hasNext;
}
@SuppressWarnings("unchecked")
public T next() {
if (end == -1)
hasNext = !sequence.getItem(currentPosition).getClass().equals(SequenceTerminal.class);
else
hasNext = currentPosition < getEnd() - 1;
return (T) sequence.getItem(currentPosition++);
}
public void remove() {
throw new UnsupportedOperationException(
"The remove method is not supported.");
}
};
} | java | public Iterator<T> iterator() {
return new Iterator<T>() {
private int currentPosition = start;
private boolean hasNext = true;
public boolean hasNext() {
return hasNext;
}
@SuppressWarnings("unchecked")
public T next() {
if (end == -1)
hasNext = !sequence.getItem(currentPosition).getClass().equals(SequenceTerminal.class);
else
hasNext = currentPosition < getEnd() - 1;
return (T) sequence.getItem(currentPosition++);
}
public void remove() {
throw new UnsupportedOperationException(
"The remove method is not supported.");
}
};
} | [
"public",
"Iterator",
"<",
"T",
">",
"iterator",
"(",
")",
"{",
"return",
"new",
"Iterator",
"<",
"T",
">",
"(",
")",
"{",
"private",
"int",
"currentPosition",
"=",
"start",
";",
"private",
"boolean",
"hasNext",
"=",
"true",
";",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"return",
"hasNext",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"T",
"next",
"(",
")",
"{",
"if",
"(",
"end",
"==",
"-",
"1",
")",
"hasNext",
"=",
"!",
"sequence",
".",
"getItem",
"(",
"currentPosition",
")",
".",
"getClass",
"(",
")",
".",
"equals",
"(",
"SequenceTerminal",
".",
"class",
")",
";",
"else",
"hasNext",
"=",
"currentPosition",
"<",
"getEnd",
"(",
")",
"-",
"1",
";",
"return",
"(",
"T",
")",
"sequence",
".",
"getItem",
"(",
"currentPosition",
"++",
")",
";",
"}",
"public",
"void",
"remove",
"(",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"The remove method is not supported.\"",
")",
";",
"}",
"}",
";",
"}"
] | Retrieves an iterator that steps over the items in this edge.
@return An iterator that walks this edge up to the end or terminating
node. | [
"Retrieves",
"an",
"iterator",
"that",
"steps",
"over",
"the",
"items",
"in",
"this",
"edge",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Edge.java#L176-L199 |
550 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/island/Island.java | Island.isCompetitor | public boolean isCompetitor(Island isl) {
for (Coordinate c : isl) {
for (Coordinate d : islandCoordinates) {
if (c.sameColumn(d) || c.sameRow(d)) return true;
}
}
return false;
} | java | public boolean isCompetitor(Island isl) {
for (Coordinate c : isl) {
for (Coordinate d : islandCoordinates) {
if (c.sameColumn(d) || c.sameRow(d)) return true;
}
}
return false;
} | [
"public",
"boolean",
"isCompetitor",
"(",
"Island",
"isl",
")",
"{",
"for",
"(",
"Coordinate",
"c",
":",
"isl",
")",
"{",
"for",
"(",
"Coordinate",
"d",
":",
"islandCoordinates",
")",
"{",
"if",
"(",
"c",
".",
"sameColumn",
"(",
"d",
")",
"||",
"c",
".",
"sameRow",
"(",
"d",
")",
")",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Two islands are competitors if there is a horizontal or
vertical line which goes through both islands | [
"Two",
"islands",
"are",
"competitors",
"if",
"there",
"is",
"a",
"horizontal",
"or",
"vertical",
"line",
"which",
"goes",
"through",
"both",
"islands"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/dekker/island/Island.java#L69-L76 |
551 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/token_index/Block.java | Block.getAllOccurrencesAsRanges | public IntStream getAllOccurrencesAsRanges() {
IntStream result = IntStream.empty();
// with/or without end
for (int i = start; i < end; i++) {
// every i is one occurrence
int token_position = tokenIndex.suffix_array[i];
IntStream range = IntStream.range(token_position, token_position + length);
result = IntStream.concat(result, range);
}
return result;
} | java | public IntStream getAllOccurrencesAsRanges() {
IntStream result = IntStream.empty();
// with/or without end
for (int i = start; i < end; i++) {
// every i is one occurrence
int token_position = tokenIndex.suffix_array[i];
IntStream range = IntStream.range(token_position, token_position + length);
result = IntStream.concat(result, range);
}
return result;
} | [
"public",
"IntStream",
"getAllOccurrencesAsRanges",
"(",
")",
"{",
"IntStream",
"result",
"=",
"IntStream",
".",
"empty",
"(",
")",
";",
"// with/or without end",
"for",
"(",
"int",
"i",
"=",
"start",
";",
"i",
"<",
"end",
";",
"i",
"++",
")",
"{",
"// every i is one occurrence",
"int",
"token_position",
"=",
"tokenIndex",
".",
"suffix_array",
"[",
"i",
"]",
";",
"IntStream",
"range",
"=",
"IntStream",
".",
"range",
"(",
"token_position",
",",
"token_position",
"+",
"length",
")",
";",
"result",
"=",
"IntStream",
".",
"concat",
"(",
"result",
",",
"range",
")",
";",
"}",
"return",
"result",
";",
"}"
] | transform lcp interval into int stream range | [
"transform",
"lcp",
"interval",
"into",
"int",
"stream",
"range"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/dekker/token_index/Block.java#L67-L77 |
552 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/QSufSort.java | QSufSort.select_sort_split | private void select_sort_split(int p, int n) {
int pa, pb, pi, pn;
int f, v;
pa = p; /* pa is start of group being picked out. */
pn = p + n - 1; /* pn is last position of subarray. */
while (pa < pn) {
for (pi = pb = pa + 1, f = KEY(pa); pi <= pn; ++pi)
if ((v = KEY(pi)) < f) {
f = v; /* f is smallest key found. */
SWAP(pi, pa); /* place smallest element at beginning. */
pb = pa + 1; /* pb is position for elements equal to f. */
} else if (v == f) { /* if equal to smallest key. */
SWAP(pi, pb); /* place next to other smallest elements. */
++pb;
}
update_group(pa, pb - 1); /* update group values for new group. */
pa = pb; /* continue sorting rest of the subarray. */
}
if (pa == pn) { /* check if last part is single element. */
V[start + I[pa]] = pa;
I[pa] = -1; /* sorted group. */
}
} | java | private void select_sort_split(int p, int n) {
int pa, pb, pi, pn;
int f, v;
pa = p; /* pa is start of group being picked out. */
pn = p + n - 1; /* pn is last position of subarray. */
while (pa < pn) {
for (pi = pb = pa + 1, f = KEY(pa); pi <= pn; ++pi)
if ((v = KEY(pi)) < f) {
f = v; /* f is smallest key found. */
SWAP(pi, pa); /* place smallest element at beginning. */
pb = pa + 1; /* pb is position for elements equal to f. */
} else if (v == f) { /* if equal to smallest key. */
SWAP(pi, pb); /* place next to other smallest elements. */
++pb;
}
update_group(pa, pb - 1); /* update group values for new group. */
pa = pb; /* continue sorting rest of the subarray. */
}
if (pa == pn) { /* check if last part is single element. */
V[start + I[pa]] = pa;
I[pa] = -1; /* sorted group. */
}
} | [
"private",
"void",
"select_sort_split",
"(",
"int",
"p",
",",
"int",
"n",
")",
"{",
"int",
"pa",
",",
"pb",
",",
"pi",
",",
"pn",
";",
"int",
"f",
",",
"v",
";",
"pa",
"=",
"p",
";",
"/* pa is start of group being picked out. */",
"pn",
"=",
"p",
"+",
"n",
"-",
"1",
";",
"/* pn is last position of subarray. */",
"while",
"(",
"pa",
"<",
"pn",
")",
"{",
"for",
"(",
"pi",
"=",
"pb",
"=",
"pa",
"+",
"1",
",",
"f",
"=",
"KEY",
"(",
"pa",
")",
";",
"pi",
"<=",
"pn",
";",
"++",
"pi",
")",
"if",
"(",
"(",
"v",
"=",
"KEY",
"(",
"pi",
")",
")",
"<",
"f",
")",
"{",
"f",
"=",
"v",
";",
"/* f is smallest key found. */",
"SWAP",
"(",
"pi",
",",
"pa",
")",
";",
"/* place smallest element at beginning. */",
"pb",
"=",
"pa",
"+",
"1",
";",
"/* pb is position for elements equal to f. */",
"}",
"else",
"if",
"(",
"v",
"==",
"f",
")",
"{",
"/* if equal to smallest key. */",
"SWAP",
"(",
"pi",
",",
"pb",
")",
";",
"/* place next to other smallest elements. */",
"++",
"pb",
";",
"}",
"update_group",
"(",
"pa",
",",
"pb",
"-",
"1",
")",
";",
"/* update group values for new group. */",
"pa",
"=",
"pb",
";",
"/* continue sorting rest of the subarray. */",
"}",
"if",
"(",
"pa",
"==",
"pn",
")",
"{",
"/* check if last part is single element. */",
"V",
"[",
"start",
"+",
"I",
"[",
"pa",
"]",
"]",
"=",
"pa",
";",
"I",
"[",
"pa",
"]",
"=",
"-",
"1",
";",
"/* sorted group. */",
"}",
"}"
] | Quadratic sorting method to use for small subarrays. To be able to update group
numbers consistently, a variant of selection sorting is used. | [
"Quadratic",
"sorting",
"method",
"to",
"use",
"for",
"small",
"subarrays",
".",
"To",
"be",
"able",
"to",
"update",
"group",
"numbers",
"consistently",
"a",
"variant",
"of",
"selection",
"sorting",
"is",
"used",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/QSufSort.java#L254-L277 |
553 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java | SuffixArrays.createWithLCP | public static SuffixData createWithLCP(CharSequence s, ISuffixArrayBuilder builder) {
final CharSequenceAdapter adapter = new CharSequenceAdapter(builder);
final int[] sa = adapter.buildSuffixArray(s);
final int[] lcp = computeLCP(adapter.input, 0, s.length(), sa);
return new SuffixData(sa, lcp);
} | java | public static SuffixData createWithLCP(CharSequence s, ISuffixArrayBuilder builder) {
final CharSequenceAdapter adapter = new CharSequenceAdapter(builder);
final int[] sa = adapter.buildSuffixArray(s);
final int[] lcp = computeLCP(adapter.input, 0, s.length(), sa);
return new SuffixData(sa, lcp);
} | [
"public",
"static",
"SuffixData",
"createWithLCP",
"(",
"CharSequence",
"s",
",",
"ISuffixArrayBuilder",
"builder",
")",
"{",
"final",
"CharSequenceAdapter",
"adapter",
"=",
"new",
"CharSequenceAdapter",
"(",
"builder",
")",
";",
"final",
"int",
"[",
"]",
"sa",
"=",
"adapter",
".",
"buildSuffixArray",
"(",
"s",
")",
";",
"final",
"int",
"[",
"]",
"lcp",
"=",
"computeLCP",
"(",
"adapter",
".",
"input",
",",
"0",
",",
"s",
".",
"length",
"(",
")",
",",
"sa",
")",
";",
"return",
"new",
"SuffixData",
"(",
"sa",
",",
"lcp",
")",
";",
"}"
] | Create a suffix array and an LCP array for a given character sequence, use the
given algorithm for building the suffix array.
@see #computeLCP(int[], int, int, int[]) | [
"Create",
"a",
"suffix",
"array",
"and",
"an",
"LCP",
"array",
"for",
"a",
"given",
"character",
"sequence",
"use",
"the",
"given",
"algorithm",
"for",
"building",
"the",
"suffix",
"array",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java#L74-L79 |
554 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java | SuffixArrays.createWithLCP | public static SuffixData createWithLCP(int[] input, int start, int length) {
final ISuffixArrayBuilder builder = new DensePositiveDecorator(
new ExtraTrailingCellsDecorator(defaultAlgorithm(), 3));
return createWithLCP(input, start, length, builder);
} | java | public static SuffixData createWithLCP(int[] input, int start, int length) {
final ISuffixArrayBuilder builder = new DensePositiveDecorator(
new ExtraTrailingCellsDecorator(defaultAlgorithm(), 3));
return createWithLCP(input, start, length, builder);
} | [
"public",
"static",
"SuffixData",
"createWithLCP",
"(",
"int",
"[",
"]",
"input",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"final",
"ISuffixArrayBuilder",
"builder",
"=",
"new",
"DensePositiveDecorator",
"(",
"new",
"ExtraTrailingCellsDecorator",
"(",
"defaultAlgorithm",
"(",
")",
",",
"3",
")",
")",
";",
"return",
"createWithLCP",
"(",
"input",
",",
"start",
",",
"length",
",",
"builder",
")",
";",
"}"
] | Create a suffix array and an LCP array for a given input sequence of symbols. | [
"Create",
"a",
"suffix",
"array",
"and",
"an",
"LCP",
"array",
"for",
"a",
"given",
"input",
"sequence",
"of",
"symbols",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java#L84-L88 |
555 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java | SuffixArrays.createWithLCP | public static SuffixData createWithLCP(int[] input, int start, int length,
ISuffixArrayBuilder builder) {
final int[] sa = builder.buildSuffixArray(input, start, length);
final int[] lcp = computeLCP(input, start, length, sa);
return new SuffixData(sa, lcp);
} | java | public static SuffixData createWithLCP(int[] input, int start, int length,
ISuffixArrayBuilder builder) {
final int[] sa = builder.buildSuffixArray(input, start, length);
final int[] lcp = computeLCP(input, start, length, sa);
return new SuffixData(sa, lcp);
} | [
"public",
"static",
"SuffixData",
"createWithLCP",
"(",
"int",
"[",
"]",
"input",
",",
"int",
"start",
",",
"int",
"length",
",",
"ISuffixArrayBuilder",
"builder",
")",
"{",
"final",
"int",
"[",
"]",
"sa",
"=",
"builder",
".",
"buildSuffixArray",
"(",
"input",
",",
"start",
",",
"length",
")",
";",
"final",
"int",
"[",
"]",
"lcp",
"=",
"computeLCP",
"(",
"input",
",",
"start",
",",
"length",
",",
"sa",
")",
";",
"return",
"new",
"SuffixData",
"(",
"sa",
",",
"lcp",
")",
";",
"}"
] | Create a suffix array and an LCP array for a given input sequence of symbols and a
custom suffix array building strategy. | [
"Create",
"a",
"suffix",
"array",
"and",
"an",
"LCP",
"array",
"for",
"a",
"given",
"input",
"sequence",
"of",
"symbols",
"and",
"a",
"custom",
"suffix",
"array",
"building",
"strategy",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java#L94-L99 |
556 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java | SuffixArrays.createWithLCP | public static <T> SuffixData createWithLCP(T[] input, ISuffixArrayBuilder builder, Comparator<? super T> comparator) {
final GenericArrayAdapter adapter = new GenericArrayAdapter(builder, comparator);
final int[] sa = adapter.buildSuffixArray(input);
final int[] lcp = computeLCP(adapter.input, 0, input.length, sa);
return new SuffixData(sa, lcp);
} | java | public static <T> SuffixData createWithLCP(T[] input, ISuffixArrayBuilder builder, Comparator<? super T> comparator) {
final GenericArrayAdapter adapter = new GenericArrayAdapter(builder, comparator);
final int[] sa = adapter.buildSuffixArray(input);
final int[] lcp = computeLCP(adapter.input, 0, input.length, sa);
return new SuffixData(sa, lcp);
} | [
"public",
"static",
"<",
"T",
">",
"SuffixData",
"createWithLCP",
"(",
"T",
"[",
"]",
"input",
",",
"ISuffixArrayBuilder",
"builder",
",",
"Comparator",
"<",
"?",
"super",
"T",
">",
"comparator",
")",
"{",
"final",
"GenericArrayAdapter",
"adapter",
"=",
"new",
"GenericArrayAdapter",
"(",
"builder",
",",
"comparator",
")",
";",
"final",
"int",
"[",
"]",
"sa",
"=",
"adapter",
".",
"buildSuffixArray",
"(",
"input",
")",
";",
"final",
"int",
"[",
"]",
"lcp",
"=",
"computeLCP",
"(",
"adapter",
".",
"input",
",",
"0",
",",
"input",
".",
"length",
",",
"sa",
")",
";",
"return",
"new",
"SuffixData",
"(",
"sa",
",",
"lcp",
")",
";",
"}"
] | Create a suffix array and an LCP array for a given generic array and a
custom suffix array building strategy, using the given T object
comparator. | [
"Create",
"a",
"suffix",
"array",
"and",
"an",
"LCP",
"array",
"for",
"a",
"given",
"generic",
"array",
"and",
"a",
"custom",
"suffix",
"array",
"building",
"strategy",
"using",
"the",
"given",
"T",
"object",
"comparator",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/SuffixArrays.java#L106-L111 |
557 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java | Tools.max | static int max(int[] input, int start, int length) {
assert length >= 1;
int max = input[start];
for (int i = length - 2, index = start + 1; i >= 0; i--, index++) {
final int v = input[index];
if (v > max) {
max = v;
}
}
return max;
} | java | static int max(int[] input, int start, int length) {
assert length >= 1;
int max = input[start];
for (int i = length - 2, index = start + 1; i >= 0; i--, index++) {
final int v = input[index];
if (v > max) {
max = v;
}
}
return max;
} | [
"static",
"int",
"max",
"(",
"int",
"[",
"]",
"input",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"assert",
"length",
">=",
"1",
";",
"int",
"max",
"=",
"input",
"[",
"start",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"length",
"-",
"2",
",",
"index",
"=",
"start",
"+",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
",",
"index",
"++",
")",
"{",
"final",
"int",
"v",
"=",
"input",
"[",
"index",
"]",
";",
"if",
"(",
"v",
">",
"max",
")",
"{",
"max",
"=",
"v",
";",
"}",
"}",
"return",
"max",
";",
"}"
] | Determine the maximum value in a slice of an array. | [
"Determine",
"the",
"maximum",
"value",
"in",
"a",
"slice",
"of",
"an",
"array",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java#L31-L43 |
558 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java | Tools.min | static int min(int[] input, int start, int length) {
assert length >= 1;
int min = input[start];
for (int i = length - 2, index = start + 1; i >= 0; i--, index++) {
final int v = input[index];
if (v < min) {
min = v;
}
}
return min;
} | java | static int min(int[] input, int start, int length) {
assert length >= 1;
int min = input[start];
for (int i = length - 2, index = start + 1; i >= 0; i--, index++) {
final int v = input[index];
if (v < min) {
min = v;
}
}
return min;
} | [
"static",
"int",
"min",
"(",
"int",
"[",
"]",
"input",
",",
"int",
"start",
",",
"int",
"length",
")",
"{",
"assert",
"length",
">=",
"1",
";",
"int",
"min",
"=",
"input",
"[",
"start",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"length",
"-",
"2",
",",
"index",
"=",
"start",
"+",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
",",
"index",
"++",
")",
"{",
"final",
"int",
"v",
"=",
"input",
"[",
"index",
"]",
";",
"if",
"(",
"v",
"<",
"min",
")",
"{",
"min",
"=",
"v",
";",
"}",
"}",
"return",
"min",
";",
"}"
] | Determine the minimum value in a slice of an array. | [
"Determine",
"the",
"minimum",
"value",
"in",
"a",
"slice",
"of",
"an",
"array",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java#L48-L60 |
559 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java | Tools.minmax | static MinMax minmax(int[] input, final int start, final int length) {
int max = input[start];
int min = max;
for (int i = length - 2, index = start + 1; i >= 0; i--, index++) {
final int v = input[index];
if (v > max) {
max = v;
}
if (v < min) {
min = v;
}
}
return new MinMax(min, max);
} | java | static MinMax minmax(int[] input, final int start, final int length) {
int max = input[start];
int min = max;
for (int i = length - 2, index = start + 1; i >= 0; i--, index++) {
final int v = input[index];
if (v > max) {
max = v;
}
if (v < min) {
min = v;
}
}
return new MinMax(min, max);
} | [
"static",
"MinMax",
"minmax",
"(",
"int",
"[",
"]",
"input",
",",
"final",
"int",
"start",
",",
"final",
"int",
"length",
")",
"{",
"int",
"max",
"=",
"input",
"[",
"start",
"]",
";",
"int",
"min",
"=",
"max",
";",
"for",
"(",
"int",
"i",
"=",
"length",
"-",
"2",
",",
"index",
"=",
"start",
"+",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
",",
"index",
"++",
")",
"{",
"final",
"int",
"v",
"=",
"input",
"[",
"index",
"]",
";",
"if",
"(",
"v",
">",
"max",
")",
"{",
"max",
"=",
"v",
";",
"}",
"if",
"(",
"v",
"<",
"min",
")",
"{",
"min",
"=",
"v",
";",
"}",
"}",
"return",
"new",
"MinMax",
"(",
"min",
",",
"max",
")",
";",
"}"
] | Calculate minimum and maximum value for a slice of an array. | [
"Calculate",
"minimum",
"and",
"maximum",
"value",
"for",
"a",
"slice",
"of",
"an",
"array",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/Tools.java#L65-L79 |
560 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Suffix.java | Suffix.getItemXFromEnd | public Object getItemXFromEnd(int distanceFromEnd) {
if ((end - (distanceFromEnd)) < start) {
throw new IllegalArgumentException(distanceFromEnd
+ " extends before the start of this suffix: ");
}
return sequence.getItem(end - distanceFromEnd);
} | java | public Object getItemXFromEnd(int distanceFromEnd) {
if ((end - (distanceFromEnd)) < start) {
throw new IllegalArgumentException(distanceFromEnd
+ " extends before the start of this suffix: ");
}
return sequence.getItem(end - distanceFromEnd);
} | [
"public",
"Object",
"getItemXFromEnd",
"(",
"int",
"distanceFromEnd",
")",
"{",
"if",
"(",
"(",
"end",
"-",
"(",
"distanceFromEnd",
")",
")",
"<",
"start",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"distanceFromEnd",
"+",
"\" extends before the start of this suffix: \"",
")",
";",
"}",
"return",
"sequence",
".",
"getItem",
"(",
"end",
"-",
"distanceFromEnd",
")",
";",
"}"
] | Retrieves the item the given distance from the end of the suffix.
@param distanceFromEnd The distance from the end.
@return The item the given distance from the end.
@throws IllegalArgumentException if the distance from end is greater than the length of the
suffix. | [
"Retrieves",
"the",
"item",
"the",
"given",
"distance",
"from",
"the",
"end",
"of",
"the",
"suffix",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Suffix.java#L134-L140 |
561 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableSerializer.java | MatchTableSerializer.toHtml | public String toHtml(Archipelago arch) {
int mat[] = new int[rowNum()];
for (Island isl : arch.getIslands()) {
for (Coordinate c : isl) {
mat[c.row] = c.column;
}
}
StringBuilder result = new StringBuilder("<table>\n<tr><td></td>\n");
ArrayList<String> colLabels = columnLabels();
for (String cLabel : colLabels) {
result.append("<td>").append(cLabel).append("</td>");
}
result.append("</tr>\n");
ArrayList<String> rLabels = rowLabels();
int row = 0;
for (String label : rLabels) {
result.append("<tr><td>").append(label).append("</td>");
if (mat[row] > 0) {
result.append("<td colspan=\"").append(mat[row]).append("\"></td>").append("<td BGCOLOR=\"lightgreen\">M</td>");
}
result.append("</tr>\n");
row++;
}
result.append("</table>");
return result.toString();
} | java | public String toHtml(Archipelago arch) {
int mat[] = new int[rowNum()];
for (Island isl : arch.getIslands()) {
for (Coordinate c : isl) {
mat[c.row] = c.column;
}
}
StringBuilder result = new StringBuilder("<table>\n<tr><td></td>\n");
ArrayList<String> colLabels = columnLabels();
for (String cLabel : colLabels) {
result.append("<td>").append(cLabel).append("</td>");
}
result.append("</tr>\n");
ArrayList<String> rLabels = rowLabels();
int row = 0;
for (String label : rLabels) {
result.append("<tr><td>").append(label).append("</td>");
if (mat[row] > 0) {
result.append("<td colspan=\"").append(mat[row]).append("\"></td>").append("<td BGCOLOR=\"lightgreen\">M</td>");
}
result.append("</tr>\n");
row++;
}
result.append("</table>");
return result.toString();
} | [
"public",
"String",
"toHtml",
"(",
"Archipelago",
"arch",
")",
"{",
"int",
"mat",
"[",
"]",
"=",
"new",
"int",
"[",
"rowNum",
"(",
")",
"]",
";",
"for",
"(",
"Island",
"isl",
":",
"arch",
".",
"getIslands",
"(",
")",
")",
"{",
"for",
"(",
"Coordinate",
"c",
":",
"isl",
")",
"{",
"mat",
"[",
"c",
".",
"row",
"]",
"=",
"c",
".",
"column",
";",
"}",
"}",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
"\"<table>\\n<tr><td></td>\\n\"",
")",
";",
"ArrayList",
"<",
"String",
">",
"colLabels",
"=",
"columnLabels",
"(",
")",
";",
"for",
"(",
"String",
"cLabel",
":",
"colLabels",
")",
"{",
"result",
".",
"append",
"(",
"\"<td>\"",
")",
".",
"append",
"(",
"cLabel",
")",
".",
"append",
"(",
"\"</td>\"",
")",
";",
"}",
"result",
".",
"append",
"(",
"\"</tr>\\n\"",
")",
";",
"ArrayList",
"<",
"String",
">",
"rLabels",
"=",
"rowLabels",
"(",
")",
";",
"int",
"row",
"=",
"0",
";",
"for",
"(",
"String",
"label",
":",
"rLabels",
")",
"{",
"result",
".",
"append",
"(",
"\"<tr><td>\"",
")",
".",
"append",
"(",
"label",
")",
".",
"append",
"(",
"\"</td>\"",
")",
";",
"if",
"(",
"mat",
"[",
"row",
"]",
">",
"0",
")",
"{",
"result",
".",
"append",
"(",
"\"<td colspan=\\\"\"",
")",
".",
"append",
"(",
"mat",
"[",
"row",
"]",
")",
".",
"append",
"(",
"\"\\\"></td>\"",
")",
".",
"append",
"(",
"\"<td BGCOLOR=\\\"lightgreen\\\">M</td>\"",
")",
";",
"}",
"result",
".",
"append",
"(",
"\"</tr>\\n\"",
")",
";",
"row",
"++",
";",
"}",
"result",
".",
"append",
"(",
"\"</table>\"",
")",
";",
"return",
"result",
".",
"toString",
"(",
")",
";",
"}"
] | arch = preferred matches | [
"arch",
"=",
"preferred",
"matches"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableSerializer.java#L68-L93 |
562 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Node.java | Node.insert | @SuppressWarnings("unchecked")
void insert(Suffix<T, S> suffix, ActivePoint<T, S> activePoint) {
Object item = suffix.getEndItem();
if (edges.containsKey(item)) {
if (tree.isNotFirstInsert() && activePoint.getNode() != tree.getRoot())
tree.setSuffixLink(activePoint.getNode());
activePoint.setEdge(edges.get(item));
activePoint.incrementLength();
} else {
saveSequenceTerminal(item);
Edge<T, S> newEdge = new Edge<>(suffix.getEndPosition() - 1, this,
sequence, tree);
edges.put((T) suffix.getEndItem(), newEdge);
suffix.decrement();
activePoint.updateAfterInsert(suffix);
if (tree.isNotFirstInsert() && !this.equals(tree.getRoot())) {
tree.getLastNodeInserted().setSuffixLink(this);
}
if (suffix.isEmpty()) {
}
else
tree.insert(suffix);
}
} | java | @SuppressWarnings("unchecked")
void insert(Suffix<T, S> suffix, ActivePoint<T, S> activePoint) {
Object item = suffix.getEndItem();
if (edges.containsKey(item)) {
if (tree.isNotFirstInsert() && activePoint.getNode() != tree.getRoot())
tree.setSuffixLink(activePoint.getNode());
activePoint.setEdge(edges.get(item));
activePoint.incrementLength();
} else {
saveSequenceTerminal(item);
Edge<T, S> newEdge = new Edge<>(suffix.getEndPosition() - 1, this,
sequence, tree);
edges.put((T) suffix.getEndItem(), newEdge);
suffix.decrement();
activePoint.updateAfterInsert(suffix);
if (tree.isNotFirstInsert() && !this.equals(tree.getRoot())) {
tree.getLastNodeInserted().setSuffixLink(this);
}
if (suffix.isEmpty()) {
}
else
tree.insert(suffix);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"void",
"insert",
"(",
"Suffix",
"<",
"T",
",",
"S",
">",
"suffix",
",",
"ActivePoint",
"<",
"T",
",",
"S",
">",
"activePoint",
")",
"{",
"Object",
"item",
"=",
"suffix",
".",
"getEndItem",
"(",
")",
";",
"if",
"(",
"edges",
".",
"containsKey",
"(",
"item",
")",
")",
"{",
"if",
"(",
"tree",
".",
"isNotFirstInsert",
"(",
")",
"&&",
"activePoint",
".",
"getNode",
"(",
")",
"!=",
"tree",
".",
"getRoot",
"(",
")",
")",
"tree",
".",
"setSuffixLink",
"(",
"activePoint",
".",
"getNode",
"(",
")",
")",
";",
"activePoint",
".",
"setEdge",
"(",
"edges",
".",
"get",
"(",
"item",
")",
")",
";",
"activePoint",
".",
"incrementLength",
"(",
")",
";",
"}",
"else",
"{",
"saveSequenceTerminal",
"(",
"item",
")",
";",
"Edge",
"<",
"T",
",",
"S",
">",
"newEdge",
"=",
"new",
"Edge",
"<>",
"(",
"suffix",
".",
"getEndPosition",
"(",
")",
"-",
"1",
",",
"this",
",",
"sequence",
",",
"tree",
")",
";",
"edges",
".",
"put",
"(",
"(",
"T",
")",
"suffix",
".",
"getEndItem",
"(",
")",
",",
"newEdge",
")",
";",
"suffix",
".",
"decrement",
"(",
")",
";",
"activePoint",
".",
"updateAfterInsert",
"(",
"suffix",
")",
";",
"if",
"(",
"tree",
".",
"isNotFirstInsert",
"(",
")",
"&&",
"!",
"this",
".",
"equals",
"(",
"tree",
".",
"getRoot",
"(",
")",
")",
")",
"{",
"tree",
".",
"getLastNodeInserted",
"(",
")",
".",
"setSuffixLink",
"(",
"this",
")",
";",
"}",
"if",
"(",
"suffix",
".",
"isEmpty",
"(",
")",
")",
"{",
"}",
"else",
"tree",
".",
"insert",
"(",
"suffix",
")",
";",
"}",
"}"
] | Inserts the suffix at the given active point.
@param suffix The suffix to insert.
@param activePoint The active point to insert it at. | [
"Inserts",
"the",
"suffix",
"at",
"the",
"given",
"active",
"point",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Node.java#L42-L67 |
563 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Node.java | Node.insert | void insert(Edge<T, S> edge) {
if (edges.containsKey(edge.getStartItem()))
throw new IllegalArgumentException("Item " + edge.getStartItem()
+ " already exists in node " + toString());
edges.put(edge.getStartItem(), edge);
} | java | void insert(Edge<T, S> edge) {
if (edges.containsKey(edge.getStartItem()))
throw new IllegalArgumentException("Item " + edge.getStartItem()
+ " already exists in node " + toString());
edges.put(edge.getStartItem(), edge);
} | [
"void",
"insert",
"(",
"Edge",
"<",
"T",
",",
"S",
">",
"edge",
")",
"{",
"if",
"(",
"edges",
".",
"containsKey",
"(",
"edge",
".",
"getStartItem",
"(",
")",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Item \"",
"+",
"edge",
".",
"getStartItem",
"(",
")",
"+",
"\" already exists in node \"",
"+",
"toString",
"(",
")",
")",
";",
"edges",
".",
"put",
"(",
"edge",
".",
"getStartItem",
"(",
")",
",",
"edge",
")",
";",
"}"
] | Inserts the given edge as a child of this node. The edge must not already
exist as child or an IllegalArgumentException will be thrown.
@param edge The edge to be inserted.
@throws IllegalArgumentException This is thrown when the edge already exists as an out bound
edge of this node. | [
"Inserts",
"the",
"given",
"edge",
"as",
"a",
"child",
"of",
"this",
"node",
".",
"The",
"edge",
"must",
"not",
"already",
"exist",
"as",
"child",
"or",
"an",
"IllegalArgumentException",
"will",
"be",
"thrown",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Node.java#L85-L90 |
564 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Utils.java | Utils.addTerminalToSequence | static <I, S extends Iterable<I>> Object[] addTerminalToSequence(S sequence,
SequenceTerminal<S> terminatingObject) {
ArrayList<Object> list = new ArrayList<>();
for (I item : sequence)
list.add(item);
Object[] newSequence = new Object[list.size() + 1];
int i = 0;
for (; i < list.size(); i++)
newSequence[i] = list.get(i);
newSequence[i] = terminatingObject;
return newSequence;
} | java | static <I, S extends Iterable<I>> Object[] addTerminalToSequence(S sequence,
SequenceTerminal<S> terminatingObject) {
ArrayList<Object> list = new ArrayList<>();
for (I item : sequence)
list.add(item);
Object[] newSequence = new Object[list.size() + 1];
int i = 0;
for (; i < list.size(); i++)
newSequence[i] = list.get(i);
newSequence[i] = terminatingObject;
return newSequence;
} | [
"static",
"<",
"I",
",",
"S",
"extends",
"Iterable",
"<",
"I",
">",
">",
"Object",
"[",
"]",
"addTerminalToSequence",
"(",
"S",
"sequence",
",",
"SequenceTerminal",
"<",
"S",
">",
"terminatingObject",
")",
"{",
"ArrayList",
"<",
"Object",
">",
"list",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"I",
"item",
":",
"sequence",
")",
"list",
".",
"(",
"item",
")",
";",
"Object",
"[",
"]",
"newSequence",
"=",
"new",
"Object",
"[",
"list",
".",
"size",
"(",
")",
"+",
"1",
"]",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
";",
"i",
"<",
"list",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"newSequence",
"[",
"i",
"]",
"=",
"list",
".",
"get",
"(",
"i",
")",
";",
"newSequence",
"[",
"i",
"]",
"=",
"terminatingObject",
";",
"return",
"newSequence",
";",
"}"
] | Appends a SequenceTerminal element to a supplied array.
@param sequence The sequence to which we are applying the terminating object.
@param terminatingObject The instance of the terminating object.
@return A new sequence with an extra element at the end containing the
terminating object. | [
"Appends",
"a",
"SequenceTerminal",
"element",
"to",
"a",
"supplied",
"array",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Utils.java#L21-L35 |
565 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Utils.java | Utils.printTreeForGraphViz | static <T, S extends Iterable<T>> String printTreeForGraphViz(SuffixTree<T, S> tree, boolean printSuffixLinks) {
LinkedList<Node<T, S>> stack = new LinkedList<>();
stack.add(tree.getRoot());
Map<Node<T, S>, Integer> nodeMap = new HashMap<>();
nodeMap.put(tree.getRoot(), 0);
int nodeId = 1;
StringBuilder sb = new StringBuilder(
"\ndigraph suffixTree{\n node [shape=circle, label=\"\", fixedsize=true, width=0.1, height=0.1]\n");
while (stack.size() > 0) {
LinkedList<Node<T, S>> childNodes = new LinkedList<>();
for (Node<T, S> node : stack) {
// List<Edge> edges = node.getEdges();
for (Edge<T, S> edge : node) {
int id = nodeId++;
if (edge.isTerminating()) {
childNodes.push(edge.getTerminal());
nodeMap.put(edge.getTerminal(), id);
}
sb.append(nodeMap.get(node)).append(" -> ").append(id)
.append(" [label=\"");
for (T item : edge) {
//if(item != null)
sb.append(item.toString());
}
sb.append("\"];\n");
}
}
stack = childNodes;
}
if (printSuffixLinks) {
// loop again to find all suffix links.
sb.append("edge [color=red]\n");
for (Map.Entry<Node<T, S>, Integer> entry : nodeMap.entrySet()) {
Node n1 = entry.getKey();
int id1 = entry.getValue();
if (n1.hasSuffixLink()) {
Node n2 = n1.getSuffixLink();
Integer id2 = nodeMap.get(n2);
// if(id2 != null)
sb.append(id1).append(" -> ").append(id2).append(" ;\n");
}
}
}
sb.append("}");
return (sb.toString());
} | java | static <T, S extends Iterable<T>> String printTreeForGraphViz(SuffixTree<T, S> tree, boolean printSuffixLinks) {
LinkedList<Node<T, S>> stack = new LinkedList<>();
stack.add(tree.getRoot());
Map<Node<T, S>, Integer> nodeMap = new HashMap<>();
nodeMap.put(tree.getRoot(), 0);
int nodeId = 1;
StringBuilder sb = new StringBuilder(
"\ndigraph suffixTree{\n node [shape=circle, label=\"\", fixedsize=true, width=0.1, height=0.1]\n");
while (stack.size() > 0) {
LinkedList<Node<T, S>> childNodes = new LinkedList<>();
for (Node<T, S> node : stack) {
// List<Edge> edges = node.getEdges();
for (Edge<T, S> edge : node) {
int id = nodeId++;
if (edge.isTerminating()) {
childNodes.push(edge.getTerminal());
nodeMap.put(edge.getTerminal(), id);
}
sb.append(nodeMap.get(node)).append(" -> ").append(id)
.append(" [label=\"");
for (T item : edge) {
//if(item != null)
sb.append(item.toString());
}
sb.append("\"];\n");
}
}
stack = childNodes;
}
if (printSuffixLinks) {
// loop again to find all suffix links.
sb.append("edge [color=red]\n");
for (Map.Entry<Node<T, S>, Integer> entry : nodeMap.entrySet()) {
Node n1 = entry.getKey();
int id1 = entry.getValue();
if (n1.hasSuffixLink()) {
Node n2 = n1.getSuffixLink();
Integer id2 = nodeMap.get(n2);
// if(id2 != null)
sb.append(id1).append(" -> ").append(id2).append(" ;\n");
}
}
}
sb.append("}");
return (sb.toString());
} | [
"static",
"<",
"T",
",",
"S",
"extends",
"Iterable",
"<",
"T",
">",
">",
"String",
"printTreeForGraphViz",
"(",
"SuffixTree",
"<",
"T",
",",
"S",
">",
"tree",
",",
"boolean",
"printSuffixLinks",
")",
"{",
"LinkedList",
"<",
"Node",
"<",
"T",
",",
"S",
">",
">",
"stack",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"stack",
".",
"add",
"(",
"tree",
".",
"getRoot",
"(",
")",
")",
";",
"Map",
"<",
"Node",
"<",
"T",
",",
"S",
">",
",",
"Integer",
">",
"nodeMap",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"nodeMap",
".",
"put",
"(",
"tree",
".",
"getRoot",
"(",
")",
",",
"0",
")",
";",
"int",
"nodeId",
"=",
"1",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"\"\\ndigraph suffixTree{\\n node [shape=circle, label=\\\"\\\", fixedsize=true, width=0.1, height=0.1]\\n\"",
")",
";",
"while",
"(",
"stack",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"LinkedList",
"<",
"Node",
"<",
"T",
",",
"S",
">",
">",
"childNodes",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"for",
"(",
"Node",
"<",
"T",
",",
"S",
">",
"node",
":",
"stack",
")",
"{",
"// List<Edge> edges = node.getEdges();",
"for",
"(",
"Edge",
"<",
"T",
",",
"S",
">",
"edge",
":",
"node",
")",
"{",
"int",
"id",
"=",
"nodeId",
"++",
";",
"if",
"(",
"edge",
".",
"isTerminating",
"(",
")",
")",
"{",
"childNodes",
".",
"push",
"(",
"edge",
".",
"getTerminal",
"(",
")",
")",
";",
"nodeMap",
".",
"put",
"(",
"edge",
".",
"getTerminal",
"(",
")",
",",
"id",
")",
";",
"}",
"sb",
".",
"append",
"(",
"nodeMap",
".",
"get",
"(",
"node",
")",
")",
".",
"append",
"(",
"\" -> \"",
")",
".",
"append",
"(",
"id",
")",
".",
"append",
"(",
"\" [label=\\\"\"",
")",
";",
"for",
"(",
"T",
"item",
":",
"edge",
")",
"{",
"//if(item != null)",
"sb",
".",
"append",
"(",
"item",
".",
"toString",
"(",
")",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\"\\\"];\\n\"",
")",
";",
"}",
"}",
"stack",
"=",
"childNodes",
";",
"}",
"if",
"(",
"printSuffixLinks",
")",
"{",
"// loop again to find all suffix links.",
"sb",
".",
"append",
"(",
"\"edge [color=red]\\n\"",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Node",
"<",
"T",
",",
"S",
">",
",",
"Integer",
">",
"entry",
":",
"nodeMap",
".",
"entrySet",
"(",
")",
")",
"{",
"Node",
"n1",
"=",
"entry",
".",
"getKey",
"(",
")",
";",
"int",
"id1",
"=",
"entry",
".",
"getValue",
"(",
")",
";",
"if",
"(",
"n1",
".",
"hasSuffixLink",
"(",
")",
")",
"{",
"Node",
"n2",
"=",
"n1",
".",
"getSuffixLink",
"(",
")",
";",
"Integer",
"id2",
"=",
"nodeMap",
".",
"get",
"(",
"n2",
")",
";",
"// if(id2 != null)",
"sb",
".",
"append",
"(",
"id1",
")",
".",
"append",
"(",
"\" -> \"",
")",
".",
"append",
"(",
"id2",
")",
".",
"append",
"(",
"\" ;\\n\"",
")",
";",
"}",
"}",
"}",
"sb",
".",
"append",
"(",
"\"}\"",
")",
";",
"return",
"(",
"sb",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Generates a .dot format string for visualizing a suffix tree.
@param tree The tree for which we are generating a dot file.
@return A string containing the contents of a .dot representation of the
tree. | [
"Generates",
"a",
".",
"dot",
"format",
"string",
"for",
"visualizing",
"a",
"suffix",
"tree",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/Utils.java#L48-L99 |
566 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/CharSequenceAdapter.java | CharSequenceAdapter.buildSuffixArray | public int[] buildSuffixArray(CharSequence sequence) {
/*
* Allocate slightly more space, some suffix construction strategies need it and
* we don't want to waste space for multiple symbol mappings.
*/
this.input = new int[sequence.length() + SuffixArrays.MAX_EXTRA_TRAILING_SPACE];
for (int i = sequence.length() - 1; i >= 0; i--) {
input[i] = sequence.charAt(i);
}
final int start = 0;
final int length = sequence.length();
final ISymbolMapper mapper = new DensePositiveMapper(input, start, length);
mapper.map(input, start, length);
return delegate.buildSuffixArray(input, start, length);
} | java | public int[] buildSuffixArray(CharSequence sequence) {
/*
* Allocate slightly more space, some suffix construction strategies need it and
* we don't want to waste space for multiple symbol mappings.
*/
this.input = new int[sequence.length() + SuffixArrays.MAX_EXTRA_TRAILING_SPACE];
for (int i = sequence.length() - 1; i >= 0; i--) {
input[i] = sequence.charAt(i);
}
final int start = 0;
final int length = sequence.length();
final ISymbolMapper mapper = new DensePositiveMapper(input, start, length);
mapper.map(input, start, length);
return delegate.buildSuffixArray(input, start, length);
} | [
"public",
"int",
"[",
"]",
"buildSuffixArray",
"(",
"CharSequence",
"sequence",
")",
"{",
"/*\n * Allocate slightly more space, some suffix construction strategies need it and\n * we don't want to waste space for multiple symbol mappings.\n */",
"this",
".",
"input",
"=",
"new",
"int",
"[",
"sequence",
".",
"length",
"(",
")",
"+",
"SuffixArrays",
".",
"MAX_EXTRA_TRAILING_SPACE",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"sequence",
".",
"length",
"(",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"input",
"[",
"i",
"]",
"=",
"sequence",
".",
"charAt",
"(",
"i",
")",
";",
"}",
"final",
"int",
"start",
"=",
"0",
";",
"final",
"int",
"length",
"=",
"sequence",
".",
"length",
"(",
")",
";",
"final",
"ISymbolMapper",
"mapper",
"=",
"new",
"DensePositiveMapper",
"(",
"input",
",",
"start",
",",
"length",
")",
";",
"mapper",
".",
"map",
"(",
"input",
",",
"start",
",",
"length",
")",
";",
"return",
"delegate",
".",
"buildSuffixArray",
"(",
"input",
",",
"start",
",",
"length",
")",
";",
"}"
] | Construct a suffix array for a given character sequence. | [
"Construct",
"a",
"suffix",
"array",
"for",
"a",
"given",
"character",
"sequence",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/CharSequenceAdapter.java#L33-L51 |
567 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java | ActivePoint.setPosition | void setPosition(Node<T, S> node, Edge<T, S> edge, int length) {
activeNode = node;
activeEdge = edge;
activeLength = length;
} | java | void setPosition(Node<T, S> node, Edge<T, S> edge, int length) {
activeNode = node;
activeEdge = edge;
activeLength = length;
} | [
"void",
"setPosition",
"(",
"Node",
"<",
"T",
",",
"S",
">",
"node",
",",
"Edge",
"<",
"T",
",",
"S",
">",
"edge",
",",
"int",
"length",
")",
"{",
"activeNode",
"=",
"node",
";",
"activeEdge",
"=",
"edge",
";",
"activeLength",
"=",
"length",
";",
"}"
] | Sets the active point to a new node, edge, length tripple.
@param node
@param edge
@param length | [
"Sets",
"the",
"active",
"point",
"to",
"a",
"new",
"node",
"edge",
"length",
"tripple",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java#L38-L42 |
568 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java | ActivePoint.updateAfterInsert | public void updateAfterInsert(Suffix<T, S> suffix) {
if (activeNode == root && suffix.isEmpty()) {
activeNode = root;
activeEdge = null;
activeLength = 0;
} else if (activeNode == root) {
Object item = suffix.getStart();
activeEdge = root.getEdgeStarting(item);
decrementLength();
fixActiveEdgeAfterSuffixLink(suffix);
if (activeLength == 0)
activeEdge = null;
} else if (activeNode.hasSuffixLink()) {
activeNode = activeNode.getSuffixLink();
findTrueActiveEdge();
fixActiveEdgeAfterSuffixLink(suffix);
if (activeLength == 0)
activeEdge = null;
} else {
activeNode = root;
findTrueActiveEdge();
fixActiveEdgeAfterSuffixLink(suffix);
if (activeLength == 0)
activeEdge = null;
}
} | java | public void updateAfterInsert(Suffix<T, S> suffix) {
if (activeNode == root && suffix.isEmpty()) {
activeNode = root;
activeEdge = null;
activeLength = 0;
} else if (activeNode == root) {
Object item = suffix.getStart();
activeEdge = root.getEdgeStarting(item);
decrementLength();
fixActiveEdgeAfterSuffixLink(suffix);
if (activeLength == 0)
activeEdge = null;
} else if (activeNode.hasSuffixLink()) {
activeNode = activeNode.getSuffixLink();
findTrueActiveEdge();
fixActiveEdgeAfterSuffixLink(suffix);
if (activeLength == 0)
activeEdge = null;
} else {
activeNode = root;
findTrueActiveEdge();
fixActiveEdgeAfterSuffixLink(suffix);
if (activeLength == 0)
activeEdge = null;
}
} | [
"public",
"void",
"updateAfterInsert",
"(",
"Suffix",
"<",
"T",
",",
"S",
">",
"suffix",
")",
"{",
"if",
"(",
"activeNode",
"==",
"root",
"&&",
"suffix",
".",
"isEmpty",
"(",
")",
")",
"{",
"activeNode",
"=",
"root",
";",
"activeEdge",
"=",
"null",
";",
"activeLength",
"=",
"0",
";",
"}",
"else",
"if",
"(",
"activeNode",
"==",
"root",
")",
"{",
"Object",
"item",
"=",
"suffix",
".",
"getStart",
"(",
")",
";",
"activeEdge",
"=",
"root",
".",
"getEdgeStarting",
"(",
"item",
")",
";",
"decrementLength",
"(",
")",
";",
"fixActiveEdgeAfterSuffixLink",
"(",
"suffix",
")",
";",
"if",
"(",
"activeLength",
"==",
"0",
")",
"activeEdge",
"=",
"null",
";",
"}",
"else",
"if",
"(",
"activeNode",
".",
"hasSuffixLink",
"(",
")",
")",
"{",
"activeNode",
"=",
"activeNode",
".",
"getSuffixLink",
"(",
")",
";",
"findTrueActiveEdge",
"(",
")",
";",
"fixActiveEdgeAfterSuffixLink",
"(",
"suffix",
")",
";",
"if",
"(",
"activeLength",
"==",
"0",
")",
"activeEdge",
"=",
"null",
";",
"}",
"else",
"{",
"activeNode",
"=",
"root",
";",
"findTrueActiveEdge",
"(",
")",
";",
"fixActiveEdgeAfterSuffixLink",
"(",
"suffix",
")",
";",
"if",
"(",
"activeLength",
"==",
"0",
")",
"activeEdge",
"=",
"null",
";",
"}",
"}"
] | Resets the active point after an insert.
@param suffix
The remaining suffix to be inserted. | [
"Resets",
"the",
"active",
"point",
"after",
"an",
"insert",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java#L125-L150 |
569 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java | ActivePoint.fixActiveEdgeAfterSuffixLink | private void fixActiveEdgeAfterSuffixLink(Suffix<T, S> suffix) {
while (activeEdge != null && activeLength > activeEdge.getLength()) {
activeLength = activeLength - activeEdge.getLength();
activeNode = activeEdge.getTerminal();
Object item = suffix.getItemXFromEnd(activeLength + 1);
activeEdge = activeNode.getEdgeStarting(item);
}
resetActivePointToTerminal();
} | java | private void fixActiveEdgeAfterSuffixLink(Suffix<T, S> suffix) {
while (activeEdge != null && activeLength > activeEdge.getLength()) {
activeLength = activeLength - activeEdge.getLength();
activeNode = activeEdge.getTerminal();
Object item = suffix.getItemXFromEnd(activeLength + 1);
activeEdge = activeNode.getEdgeStarting(item);
}
resetActivePointToTerminal();
} | [
"private",
"void",
"fixActiveEdgeAfterSuffixLink",
"(",
"Suffix",
"<",
"T",
",",
"S",
">",
"suffix",
")",
"{",
"while",
"(",
"activeEdge",
"!=",
"null",
"&&",
"activeLength",
">",
"activeEdge",
".",
"getLength",
"(",
")",
")",
"{",
"activeLength",
"=",
"activeLength",
"-",
"activeEdge",
".",
"getLength",
"(",
")",
";",
"activeNode",
"=",
"activeEdge",
".",
"getTerminal",
"(",
")",
";",
"Object",
"item",
"=",
"suffix",
".",
"getItemXFromEnd",
"(",
"activeLength",
"+",
"1",
")",
";",
"activeEdge",
"=",
"activeNode",
".",
"getEdgeStarting",
"(",
"item",
")",
";",
"}",
"resetActivePointToTerminal",
"(",
")",
";",
"}"
] | Deal with the case when we follow a suffix link but the active length is
greater than the new active edge length. In this situation we must walk
down the tree updating the entire active point. | [
"Deal",
"with",
"the",
"case",
"when",
"we",
"follow",
"a",
"suffix",
"link",
"but",
"the",
"active",
"length",
"is",
"greater",
"than",
"the",
"new",
"active",
"edge",
"length",
".",
"In",
"this",
"situation",
"we",
"must",
"walk",
"down",
"the",
"tree",
"updating",
"the",
"entire",
"active",
"point",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java#L157-L165 |
570 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java | ActivePoint.findTrueActiveEdge | private void findTrueActiveEdge() {
if (activeEdge != null) {
Object item = activeEdge.getStartItem();
activeEdge = activeNode.getEdgeStarting(item);
}
} | java | private void findTrueActiveEdge() {
if (activeEdge != null) {
Object item = activeEdge.getStartItem();
activeEdge = activeNode.getEdgeStarting(item);
}
} | [
"private",
"void",
"findTrueActiveEdge",
"(",
")",
"{",
"if",
"(",
"activeEdge",
"!=",
"null",
")",
"{",
"Object",
"item",
"=",
"activeEdge",
".",
"getStartItem",
"(",
")",
";",
"activeEdge",
"=",
"activeNode",
".",
"getEdgeStarting",
"(",
"item",
")",
";",
"}",
"}"
] | Finds the edge instance who's start item matches the current active edge
start item but comes from the current active node. | [
"Finds",
"the",
"edge",
"instance",
"who",
"s",
"start",
"item",
"matches",
"the",
"current",
"active",
"edge",
"start",
"item",
"but",
"comes",
"from",
"the",
"current",
"active",
"node",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java#L171-L176 |
571 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java | ActivePoint.resetActivePointToTerminal | private boolean resetActivePointToTerminal() {
if (activeEdge != null && activeEdge.getLength() == activeLength && activeEdge.isTerminating()) {
activeNode = activeEdge.getTerminal();
activeEdge = null;
activeLength = 0;
return true;
}
return false;
} | java | private boolean resetActivePointToTerminal() {
if (activeEdge != null && activeEdge.getLength() == activeLength && activeEdge.isTerminating()) {
activeNode = activeEdge.getTerminal();
activeEdge = null;
activeLength = 0;
return true;
}
return false;
} | [
"private",
"boolean",
"resetActivePointToTerminal",
"(",
")",
"{",
"if",
"(",
"activeEdge",
"!=",
"null",
"&&",
"activeEdge",
".",
"getLength",
"(",
")",
"==",
"activeLength",
"&&",
"activeEdge",
".",
"isTerminating",
"(",
")",
")",
"{",
"activeNode",
"=",
"activeEdge",
".",
"getTerminal",
"(",
")",
";",
"activeEdge",
"=",
"null",
";",
"activeLength",
"=",
"0",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}"
] | Resizes the active length in the case where we are sitting on a terminal.
@return true if reset occurs false otherwise. | [
"Resizes",
"the",
"active",
"length",
"in",
"the",
"case",
"where",
"we",
"are",
"sitting",
"on",
"a",
"terminal",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/ActivePoint.java#L183-L192 |
572 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixarray/GenericArrayAdapter.java | GenericArrayAdapter.buildSuffixArray | public int[] buildSuffixArray(T[] tokens) {
final int length = tokens.length;
/*
* Allocate slightly more space, some suffix construction strategies need it and
* we don't want to waste space for multiple symbol mappings.
*/
input = new int[length + SuffixArrays.MAX_EXTRA_TRAILING_SPACE];
//System.out.println("Assigning token ids ...");
/*
* We associate every token to an id, all `equal´ tokens to the same id.
* The suffix array is built using only the the ids.
*/
tokIDs = new TreeMap<>(comparator);
for (int i = 0; i < length; i++) {
tokIDs.putIfAbsent(tokens[i], i);
input[i] = tokIDs.get(tokens[i]);
}
//System.out.println("Token ids assigned.");
return delegate.buildSuffixArray(input, 0, length);
} | java | public int[] buildSuffixArray(T[] tokens) {
final int length = tokens.length;
/*
* Allocate slightly more space, some suffix construction strategies need it and
* we don't want to waste space for multiple symbol mappings.
*/
input = new int[length + SuffixArrays.MAX_EXTRA_TRAILING_SPACE];
//System.out.println("Assigning token ids ...");
/*
* We associate every token to an id, all `equal´ tokens to the same id.
* The suffix array is built using only the the ids.
*/
tokIDs = new TreeMap<>(comparator);
for (int i = 0; i < length; i++) {
tokIDs.putIfAbsent(tokens[i], i);
input[i] = tokIDs.get(tokens[i]);
}
//System.out.println("Token ids assigned.");
return delegate.buildSuffixArray(input, 0, length);
} | [
"public",
"int",
"[",
"]",
"buildSuffixArray",
"(",
"T",
"[",
"]",
"tokens",
")",
"{",
"final",
"int",
"length",
"=",
"tokens",
".",
"length",
";",
"/*\n * Allocate slightly more space, some suffix construction strategies need it and\n * we don't want to waste space for multiple symbol mappings.\n */",
"input",
"=",
"new",
"int",
"[",
"length",
"+",
"SuffixArrays",
".",
"MAX_EXTRA_TRAILING_SPACE",
"]",
";",
"//System.out.println(\"Assigning token ids ...\");",
"/*\n * We associate every token to an id, all `equal´ tokens to the same id.\n * The suffix array is built using only the the ids.\n */",
"tokIDs",
"=",
"new",
"TreeMap",
"<>",
"(",
"comparator",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"tokIDs",
".",
"putIfAbsent",
"(",
"tokens",
"[",
"i",
"]",
",",
"i",
")",
";",
"input",
"[",
"i",
"]",
"=",
"tokIDs",
".",
"get",
"(",
"tokens",
"[",
"i",
"]",
")",
";",
"}",
"//System.out.println(\"Token ids assigned.\");",
"return",
"delegate",
".",
"buildSuffixArray",
"(",
"input",
",",
"0",
",",
"length",
")",
";",
"}"
] | Construct a suffix array for a given generic token array. | [
"Construct",
"a",
"suffix",
"array",
"for",
"a",
"given",
"generic",
"token",
"array",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixarray/GenericArrayAdapter.java#L33-L57 |
573 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java | SuffixTree.add | public void add(S sequence) {
int start = currentEnd;
this.sequence.add(sequence);
suffix = new Suffix<>(currentEnd, currentEnd, this.sequence);
activePoint.setPosition(root, null, 0);
extendTree(start, this.sequence.getLength());
} | java | public void add(S sequence) {
int start = currentEnd;
this.sequence.add(sequence);
suffix = new Suffix<>(currentEnd, currentEnd, this.sequence);
activePoint.setPosition(root, null, 0);
extendTree(start, this.sequence.getLength());
} | [
"public",
"void",
"add",
"(",
"S",
"sequence",
")",
"{",
"int",
"start",
"=",
"currentEnd",
";",
"this",
".",
"sequence",
".",
"add",
"(",
"sequence",
")",
";",
"suffix",
"=",
"new",
"Suffix",
"<>",
"(",
"currentEnd",
",",
"currentEnd",
",",
"this",
".",
"sequence",
")",
";",
"activePoint",
".",
"setPosition",
"(",
"root",
",",
"null",
",",
"0",
")",
";",
"extendTree",
"(",
"start",
",",
"this",
".",
"sequence",
".",
"getLength",
"(",
")",
")",
";",
"}"
] | Add a sequence to the suffix tree. It is immediately processed
and added to the tree.
@param sequence A sequence to be added. | [
"Add",
"a",
"sequence",
"to",
"the",
"suffix",
"tree",
".",
"It",
"is",
"immediately",
"processed",
"and",
"added",
"to",
"the",
"tree",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java#L54-L60 |
574 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java | SuffixTree.insert | void insert(Suffix<I, S> suffix) {
if (activePoint.isNode()) {
Node<I, S> node = activePoint.getNode();
node.insert(suffix, activePoint);
} else if (activePoint.isEdge()) {
Edge<I, S> edge = activePoint.getEdge();
edge.insert(suffix, activePoint);
}
} | java | void insert(Suffix<I, S> suffix) {
if (activePoint.isNode()) {
Node<I, S> node = activePoint.getNode();
node.insert(suffix, activePoint);
} else if (activePoint.isEdge()) {
Edge<I, S> edge = activePoint.getEdge();
edge.insert(suffix, activePoint);
}
} | [
"void",
"insert",
"(",
"Suffix",
"<",
"I",
",",
"S",
">",
"suffix",
")",
"{",
"if",
"(",
"activePoint",
".",
"isNode",
"(",
")",
")",
"{",
"Node",
"<",
"I",
",",
"S",
">",
"node",
"=",
"activePoint",
".",
"getNode",
"(",
")",
";",
"node",
".",
"insert",
"(",
"suffix",
",",
"activePoint",
")",
";",
"}",
"else",
"if",
"(",
"activePoint",
".",
"isEdge",
"(",
")",
")",
"{",
"Edge",
"<",
"I",
",",
"S",
">",
"edge",
"=",
"activePoint",
".",
"getEdge",
"(",
")",
";",
"edge",
".",
"insert",
"(",
"suffix",
",",
"activePoint",
")",
";",
"}",
"}"
] | Inserts the given suffix into this tree.
@param suffix The suffix to insert. | [
"Inserts",
"the",
"given",
"suffix",
"into",
"this",
"tree",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java#L77-L85 |
575 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java | SuffixTree.setSuffixLink | void setSuffixLink(Node<I, S> node) {
if (isNotFirstInsert()) {
lastNodeInserted.setSuffixLink(node);
}
lastNodeInserted = node;
} | java | void setSuffixLink(Node<I, S> node) {
if (isNotFirstInsert()) {
lastNodeInserted.setSuffixLink(node);
}
lastNodeInserted = node;
} | [
"void",
"setSuffixLink",
"(",
"Node",
"<",
"I",
",",
"S",
">",
"node",
")",
"{",
"if",
"(",
"isNotFirstInsert",
"(",
")",
")",
"{",
"lastNodeInserted",
".",
"setSuffixLink",
"(",
"node",
")",
";",
"}",
"lastNodeInserted",
"=",
"node",
";",
"}"
] | Sets the suffix link of the last inserted node to point to the supplied
node. This method checks the state of the step and only applies the
suffix link if there is a previous node inserted during this step. This
method also set the last node inserted to the supplied node after
applying any suffix linking.
@param node The node to which the last node inserted's suffix link should
point to. | [
"Sets",
"the",
"suffix",
"link",
"of",
"the",
"last",
"inserted",
"node",
"to",
"point",
"to",
"the",
"supplied",
"node",
".",
"This",
"method",
"checks",
"the",
"state",
"of",
"the",
"step",
"and",
"only",
"applies",
"the",
"suffix",
"link",
"if",
"there",
"is",
"a",
"previous",
"node",
"inserted",
"during",
"this",
"step",
".",
"This",
"method",
"also",
"set",
"the",
"last",
"node",
"inserted",
"to",
"the",
"supplied",
"node",
"after",
"applying",
"any",
"suffix",
"linking",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/suffixtree/SuffixTree.java#L150-L155 |
576 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableImpl.java | MatchTableImpl.create | public static MatchTable create(VariantGraph graph, Iterable<Token> witness) {
Comparator<Token> comparator = new EqualityTokenComparator();
return MatchTableImpl.create(graph, witness, comparator);
} | java | public static MatchTable create(VariantGraph graph, Iterable<Token> witness) {
Comparator<Token> comparator = new EqualityTokenComparator();
return MatchTableImpl.create(graph, witness, comparator);
} | [
"public",
"static",
"MatchTable",
"create",
"(",
"VariantGraph",
"graph",
",",
"Iterable",
"<",
"Token",
">",
"witness",
")",
"{",
"Comparator",
"<",
"Token",
">",
"comparator",
"=",
"new",
"EqualityTokenComparator",
"(",
")",
";",
"return",
"MatchTableImpl",
".",
"create",
"(",
"graph",
",",
"witness",
",",
"comparator",
")",
";",
"}"
] | assumes default token comparator | [
"assumes",
"default",
"token",
"comparator"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableImpl.java#L53-L56 |
577 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableImpl.java | MatchTableImpl.getIslands | @Override
public Set<Island> getIslands() {
Map<Coordinate, Island> coordinateMapper = new HashMap<>();
List<Coordinate> allMatches = allMatches();
for (Coordinate c : allMatches) {
// LOG.debug("coordinate {}", c);
addToIslands(coordinateMapper, c);
}
Set<Coordinate> smallestIslandsCoordinates = new HashSet<>(allMatches);
smallestIslandsCoordinates.removeAll(coordinateMapper.keySet());
for (Coordinate coordinate : smallestIslandsCoordinates) {
Island island = new Island();
island.add(coordinate);
coordinateMapper.put(coordinate, island);
}
return new HashSet<>(coordinateMapper.values());
} | java | @Override
public Set<Island> getIslands() {
Map<Coordinate, Island> coordinateMapper = new HashMap<>();
List<Coordinate> allMatches = allMatches();
for (Coordinate c : allMatches) {
// LOG.debug("coordinate {}", c);
addToIslands(coordinateMapper, c);
}
Set<Coordinate> smallestIslandsCoordinates = new HashSet<>(allMatches);
smallestIslandsCoordinates.removeAll(coordinateMapper.keySet());
for (Coordinate coordinate : smallestIslandsCoordinates) {
Island island = new Island();
island.add(coordinate);
coordinateMapper.put(coordinate, island);
}
return new HashSet<>(coordinateMapper.values());
} | [
"@",
"Override",
"public",
"Set",
"<",
"Island",
">",
"getIslands",
"(",
")",
"{",
"Map",
"<",
"Coordinate",
",",
"Island",
">",
"coordinateMapper",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"List",
"<",
"Coordinate",
">",
"allMatches",
"=",
"allMatches",
"(",
")",
";",
"for",
"(",
"Coordinate",
"c",
":",
"allMatches",
")",
"{",
"// LOG.debug(\"coordinate {}\", c);",
"addToIslands",
"(",
"coordinateMapper",
",",
"c",
")",
";",
"}",
"Set",
"<",
"Coordinate",
">",
"smallestIslandsCoordinates",
"=",
"new",
"HashSet",
"<>",
"(",
"allMatches",
")",
";",
"smallestIslandsCoordinates",
".",
"removeAll",
"(",
"coordinateMapper",
".",
"keySet",
"(",
")",
")",
";",
"for",
"(",
"Coordinate",
"coordinate",
":",
"smallestIslandsCoordinates",
")",
"{",
"Island",
"island",
"=",
"new",
"Island",
"(",
")",
";",
"island",
".",
"add",
"(",
"coordinate",
")",
";",
"coordinateMapper",
".",
"put",
"(",
"coordinate",
",",
"island",
")",
";",
"}",
"return",
"new",
"HashSet",
"<>",
"(",
"coordinateMapper",
".",
"values",
"(",
")",
")",
";",
"}"
] | we don't need to check the lower right neighbor. | [
"we",
"don",
"t",
"need",
"to",
"check",
"the",
"lower",
"right",
"neighbor",
"."
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableImpl.java#L96-L112 |
578 | interedition/collatex | collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableImpl.java | MatchTableImpl.fillTableWithMatches | private void fillTableWithMatches(VariantGraphRanking ranking, VariantGraph graph, Iterable<Token> witness, Comparator<Token> comparator) {
Matches matches = Matches.between(graph.vertices(), witness, comparator);
Set<Token> unique = matches.uniqueInWitness;
Set<Token> ambiguous = matches.ambiguousInWitness;
int rowIndex = 0;
for (Token t : witness) {
if (unique.contains(t) || ambiguous.contains(t)) {
List<VariantGraph.Vertex> matchingVertices = matches.allMatches.getOrDefault(t, Collections.emptyList());
for (VariantGraph.Vertex vgv : matchingVertices) {
set(rowIndex, ranking.apply(vgv) - 1, t, vgv);
}
}
rowIndex++;
}
} | java | private void fillTableWithMatches(VariantGraphRanking ranking, VariantGraph graph, Iterable<Token> witness, Comparator<Token> comparator) {
Matches matches = Matches.between(graph.vertices(), witness, comparator);
Set<Token> unique = matches.uniqueInWitness;
Set<Token> ambiguous = matches.ambiguousInWitness;
int rowIndex = 0;
for (Token t : witness) {
if (unique.contains(t) || ambiguous.contains(t)) {
List<VariantGraph.Vertex> matchingVertices = matches.allMatches.getOrDefault(t, Collections.emptyList());
for (VariantGraph.Vertex vgv : matchingVertices) {
set(rowIndex, ranking.apply(vgv) - 1, t, vgv);
}
}
rowIndex++;
}
} | [
"private",
"void",
"fillTableWithMatches",
"(",
"VariantGraphRanking",
"ranking",
",",
"VariantGraph",
"graph",
",",
"Iterable",
"<",
"Token",
">",
"witness",
",",
"Comparator",
"<",
"Token",
">",
"comparator",
")",
"{",
"Matches",
"matches",
"=",
"Matches",
".",
"between",
"(",
"graph",
".",
"vertices",
"(",
")",
",",
"witness",
",",
"comparator",
")",
";",
"Set",
"<",
"Token",
">",
"unique",
"=",
"matches",
".",
"uniqueInWitness",
";",
"Set",
"<",
"Token",
">",
"ambiguous",
"=",
"matches",
".",
"ambiguousInWitness",
";",
"int",
"rowIndex",
"=",
"0",
";",
"for",
"(",
"Token",
"t",
":",
"witness",
")",
"{",
"if",
"(",
"unique",
".",
"contains",
"(",
"t",
")",
"||",
"ambiguous",
".",
"contains",
"(",
"t",
")",
")",
"{",
"List",
"<",
"VariantGraph",
".",
"Vertex",
">",
"matchingVertices",
"=",
"matches",
".",
"allMatches",
".",
"getOrDefault",
"(",
"t",
",",
"Collections",
".",
"emptyList",
"(",
")",
")",
";",
"for",
"(",
"VariantGraph",
".",
"Vertex",
"vgv",
":",
"matchingVertices",
")",
"{",
"set",
"(",
"rowIndex",
",",
"ranking",
".",
"apply",
"(",
"vgv",
")",
"-",
"1",
",",
"t",
",",
"vgv",
")",
";",
"}",
"}",
"rowIndex",
"++",
";",
"}",
"}"
] | move parameters into fields? | [
"move",
"parameters",
"into",
"fields?"
] | 76dd1fcc36047bc66a87d31142e72e98b5347821 | https://github.com/interedition/collatex/blob/76dd1fcc36047bc66a87d31142e72e98b5347821/collatex-core/src/main/java/eu/interedition/collatex/dekker/legacy/MatchTableImpl.java#L130-L144 |
579 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/MutableSymbolTable.java | MutableSymbolTable.remove | public void remove(int id) {
String symbol = invert().keyForId(id);
idToSymbol.remove(id);
symbolToId.remove(symbol);
} | java | public void remove(int id) {
String symbol = invert().keyForId(id);
idToSymbol.remove(id);
symbolToId.remove(symbol);
} | [
"public",
"void",
"remove",
"(",
"int",
"id",
")",
"{",
"String",
"symbol",
"=",
"invert",
"(",
")",
".",
"keyForId",
"(",
"id",
")",
";",
"idToSymbol",
".",
"remove",
"(",
"id",
")",
";",
"symbolToId",
".",
"remove",
"(",
"symbol",
")",
";",
"}"
] | Remove the mapping for the given id. Note that the newly assigned 'next' ids are monotonically
increasing, so removing one id does not free it up to be assigned in future symbol table adds; there
will just be holes in the symbol mappings
@see #trimIds() for a way to compact the assigned ids
@param id | [
"Remove",
"the",
"mapping",
"for",
"the",
"given",
"id",
".",
"Note",
"that",
"the",
"newly",
"assigned",
"next",
"ids",
"are",
"monotonically",
"increasing",
"so",
"removing",
"one",
"id",
"does",
"not",
"free",
"it",
"up",
"to",
"be",
"assigned",
"in",
"future",
"symbol",
"table",
"adds",
";",
"there",
"will",
"just",
"be",
"holes",
"in",
"the",
"symbol",
"mappings"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/MutableSymbolTable.java#L79-L83 |
580 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/MutableSymbolTable.java | MutableSymbolTable.trimIds | public void trimIds() {
// typical case shortcut
if (idToSymbol.containsKey(nextId - 1)) {
return;
}
int max = -1;
for (IntObjectCursor<String> cursor : idToSymbol) {
max = Math.max(max, cursor.key);
}
nextId = max + 1;
} | java | public void trimIds() {
// typical case shortcut
if (idToSymbol.containsKey(nextId - 1)) {
return;
}
int max = -1;
for (IntObjectCursor<String> cursor : idToSymbol) {
max = Math.max(max, cursor.key);
}
nextId = max + 1;
} | [
"public",
"void",
"trimIds",
"(",
")",
"{",
"// typical case shortcut",
"if",
"(",
"idToSymbol",
".",
"containsKey",
"(",
"nextId",
"-",
"1",
")",
")",
"{",
"return",
";",
"}",
"int",
"max",
"=",
"-",
"1",
";",
"for",
"(",
"IntObjectCursor",
"<",
"String",
">",
"cursor",
":",
"idToSymbol",
")",
"{",
"max",
"=",
"Math",
".",
"max",
"(",
"max",
",",
"cursor",
".",
"key",
")",
";",
"}",
"nextId",
"=",
"max",
"+",
"1",
";",
"}"
] | If there are ids to reclaim at the end, then this will do this. Certainly be careful if you are
doing operations where it is expected that the id mappings will be consistent across multiple FSTs
such as in compose where you want the output of A to be equal to the input of B | [
"If",
"there",
"are",
"ids",
"to",
"reclaim",
"at",
"the",
"end",
"then",
"this",
"will",
"do",
"this",
".",
"Certainly",
"be",
"careful",
"if",
"you",
"are",
"doing",
"operations",
"where",
"it",
"is",
"expected",
"that",
"the",
"id",
"mappings",
"will",
"be",
"consistent",
"across",
"multiple",
"FSTs",
"such",
"as",
"in",
"compose",
"where",
"you",
"want",
"the",
"output",
"of",
"A",
"to",
"be",
"equal",
"to",
"the",
"input",
"of",
"B"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/MutableSymbolTable.java#L90-L100 |
581 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Compose.java | Compose.precomputeInner | public static PrecomputedComposeFst precomputeInner(Fst fst2, Semiring semiring) {
fst2.throwIfInvalid();
MutableFst mutableFst = MutableFst.copyFrom(fst2);
WriteableSymbolTable table = mutableFst.getInputSymbols();
int e1index = getOrAddEps(table, true);
int e2index = getOrAddEps(table, false);
String eps1 = table.invert().keyForId(e1index);
String eps2 = table.invert().keyForId(e2index);
augment(AugmentLabels.INPUT, mutableFst, semiring, eps1, eps2);
ArcSort.sortByInput(mutableFst);
MutableFst filter = makeFilter(table, semiring, eps1, eps2);
ArcSort.sortByInput(filter);
return new PrecomputedComposeFst(eps1, eps2, new ImmutableFst(mutableFst), semiring, new ImmutableFst(filter));
} | java | public static PrecomputedComposeFst precomputeInner(Fst fst2, Semiring semiring) {
fst2.throwIfInvalid();
MutableFst mutableFst = MutableFst.copyFrom(fst2);
WriteableSymbolTable table = mutableFst.getInputSymbols();
int e1index = getOrAddEps(table, true);
int e2index = getOrAddEps(table, false);
String eps1 = table.invert().keyForId(e1index);
String eps2 = table.invert().keyForId(e2index);
augment(AugmentLabels.INPUT, mutableFst, semiring, eps1, eps2);
ArcSort.sortByInput(mutableFst);
MutableFst filter = makeFilter(table, semiring, eps1, eps2);
ArcSort.sortByInput(filter);
return new PrecomputedComposeFst(eps1, eps2, new ImmutableFst(mutableFst), semiring, new ImmutableFst(filter));
} | [
"public",
"static",
"PrecomputedComposeFst",
"precomputeInner",
"(",
"Fst",
"fst2",
",",
"Semiring",
"semiring",
")",
"{",
"fst2",
".",
"throwIfInvalid",
"(",
")",
";",
"MutableFst",
"mutableFst",
"=",
"MutableFst",
".",
"copyFrom",
"(",
"fst2",
")",
";",
"WriteableSymbolTable",
"table",
"=",
"mutableFst",
".",
"getInputSymbols",
"(",
")",
";",
"int",
"e1index",
"=",
"getOrAddEps",
"(",
"table",
",",
"true",
")",
";",
"int",
"e2index",
"=",
"getOrAddEps",
"(",
"table",
",",
"false",
")",
";",
"String",
"eps1",
"=",
"table",
".",
"invert",
"(",
")",
".",
"keyForId",
"(",
"e1index",
")",
";",
"String",
"eps2",
"=",
"table",
".",
"invert",
"(",
")",
".",
"keyForId",
"(",
"e2index",
")",
";",
"augment",
"(",
"AugmentLabels",
".",
"INPUT",
",",
"mutableFst",
",",
"semiring",
",",
"eps1",
",",
"eps2",
")",
";",
"ArcSort",
".",
"sortByInput",
"(",
"mutableFst",
")",
";",
"MutableFst",
"filter",
"=",
"makeFilter",
"(",
"table",
",",
"semiring",
",",
"eps1",
",",
"eps2",
")",
";",
"ArcSort",
".",
"sortByInput",
"(",
"filter",
")",
";",
"return",
"new",
"PrecomputedComposeFst",
"(",
"eps1",
",",
"eps2",
",",
"new",
"ImmutableFst",
"(",
"mutableFst",
")",
",",
"semiring",
",",
"new",
"ImmutableFst",
"(",
"filter",
")",
")",
";",
"}"
] | Pre-processes a FST that is going to be used on the right hand side of a compose operator many times
@param fst2 the fst that will appear on the right hand side
@param semiring the semiring that will be used for the compose operation
@return a pre-processed form of the inner fst that can be passed to `composeWithPrecomputed` | [
"Pre",
"-",
"processes",
"a",
"FST",
"that",
"is",
"going",
"to",
"be",
"used",
"on",
"the",
"right",
"hand",
"side",
"of",
"a",
"compose",
"operator",
"many",
"times"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Compose.java#L62-L77 |
582 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Compose.java | Compose.makeFilter | private static MutableFst makeFilter(WriteableSymbolTable table, Semiring semiring, String eps1, String eps2) {
MutableFst filter = new MutableFst(semiring, table, table);
// State 0
MutableState s0 = filter.newStartState();
s0.setFinalWeight(semiring.one());
MutableState s1 = filter.newState();
s1.setFinalWeight(semiring.one());
MutableState s2 = filter.newState();
s2.setFinalWeight(semiring.one());
filter.addArc(s0, eps2, eps1, s0, semiring.one());
filter.addArc(s0, eps1, eps1, s1, semiring.one());
filter.addArc(s0, eps2, eps2, s2, semiring.one());
// self loops
filter.addArc(s1, eps1, eps1, s1, semiring.one());
filter.addArc(s2, eps2, eps2, s2, semiring.one());
for (ObjectIntCursor<String> cursor : table) {
int i = cursor.value;
String key = cursor.key;
if (key.equals(Fst.EPS) || key.equals(eps1) || key.equals(eps2)) {
continue;
}
filter.addArc(s0, i, i, s0, semiring.one());
filter.addArc(s1, i, i, s0, semiring.one());
filter.addArc(s2, i, i, s0, semiring.one());
}
return filter;
} | java | private static MutableFst makeFilter(WriteableSymbolTable table, Semiring semiring, String eps1, String eps2) {
MutableFst filter = new MutableFst(semiring, table, table);
// State 0
MutableState s0 = filter.newStartState();
s0.setFinalWeight(semiring.one());
MutableState s1 = filter.newState();
s1.setFinalWeight(semiring.one());
MutableState s2 = filter.newState();
s2.setFinalWeight(semiring.one());
filter.addArc(s0, eps2, eps1, s0, semiring.one());
filter.addArc(s0, eps1, eps1, s1, semiring.one());
filter.addArc(s0, eps2, eps2, s2, semiring.one());
// self loops
filter.addArc(s1, eps1, eps1, s1, semiring.one());
filter.addArc(s2, eps2, eps2, s2, semiring.one());
for (ObjectIntCursor<String> cursor : table) {
int i = cursor.value;
String key = cursor.key;
if (key.equals(Fst.EPS) || key.equals(eps1) || key.equals(eps2)) {
continue;
}
filter.addArc(s0, i, i, s0, semiring.one());
filter.addArc(s1, i, i, s0, semiring.one());
filter.addArc(s2, i, i, s0, semiring.one());
}
return filter;
} | [
"private",
"static",
"MutableFst",
"makeFilter",
"(",
"WriteableSymbolTable",
"table",
",",
"Semiring",
"semiring",
",",
"String",
"eps1",
",",
"String",
"eps2",
")",
"{",
"MutableFst",
"filter",
"=",
"new",
"MutableFst",
"(",
"semiring",
",",
"table",
",",
"table",
")",
";",
"// State 0",
"MutableState",
"s0",
"=",
"filter",
".",
"newStartState",
"(",
")",
";",
"s0",
".",
"setFinalWeight",
"(",
"semiring",
".",
"one",
"(",
")",
")",
";",
"MutableState",
"s1",
"=",
"filter",
".",
"newState",
"(",
")",
";",
"s1",
".",
"setFinalWeight",
"(",
"semiring",
".",
"one",
"(",
")",
")",
";",
"MutableState",
"s2",
"=",
"filter",
".",
"newState",
"(",
")",
";",
"s2",
".",
"setFinalWeight",
"(",
"semiring",
".",
"one",
"(",
")",
")",
";",
"filter",
".",
"addArc",
"(",
"s0",
",",
"eps2",
",",
"eps1",
",",
"s0",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"filter",
".",
"addArc",
"(",
"s0",
",",
"eps1",
",",
"eps1",
",",
"s1",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"filter",
".",
"addArc",
"(",
"s0",
",",
"eps2",
",",
"eps2",
",",
"s2",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"// self loops",
"filter",
".",
"addArc",
"(",
"s1",
",",
"eps1",
",",
"eps1",
",",
"s1",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"filter",
".",
"addArc",
"(",
"s2",
",",
"eps2",
",",
"eps2",
",",
"s2",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"for",
"(",
"ObjectIntCursor",
"<",
"String",
">",
"cursor",
":",
"table",
")",
"{",
"int",
"i",
"=",
"cursor",
".",
"value",
";",
"String",
"key",
"=",
"cursor",
".",
"key",
";",
"if",
"(",
"key",
".",
"equals",
"(",
"Fst",
".",
"EPS",
")",
"||",
"key",
".",
"equals",
"(",
"eps1",
")",
"||",
"key",
".",
"equals",
"(",
"eps2",
")",
")",
"{",
"continue",
";",
"}",
"filter",
".",
"addArc",
"(",
"s0",
",",
"i",
",",
"i",
",",
"s0",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"filter",
".",
"addArc",
"(",
"s1",
",",
"i",
",",
"i",
",",
"s0",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"filter",
".",
"addArc",
"(",
"s2",
",",
"i",
",",
"i",
",",
"s0",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"}",
"return",
"filter",
";",
"}"
] | Get a filter to use for avoiding multiple epsilon paths in the resulting Fst
See: M. Mohri, "Weighted automata algorithms", Handbook of Weighted Automata. Springer, pp. 213-250, 2009.
@param table the filter's input/output symbols
@param semiring the semiring to use in the operation | [
"Get",
"a",
"filter",
"to",
"use",
"for",
"avoiding",
"multiple",
"epsilon",
"paths",
"in",
"the",
"resulting",
"Fst"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Compose.java#L190-L219 |
583 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Compose.java | Compose.augment | private static void augment(AugmentLabels label, MutableFst fst, Semiring semiring, String eps1, String eps2) {
// label: 0->augment on ilabel
// 1->augment on olabel
int e1inputIndex = fst.getInputSymbols().getOrAdd(eps1);
int e2inputIndex = fst.getInputSymbols().getOrAdd(eps2);
int e1outputIndex = fst.getOutputSymbols().getOrAdd(eps1);
int e2outputIndex = fst.getOutputSymbols().getOrAdd(eps2);
int iEps = fst.getInputSymbols().get(Fst.EPS);
int oEps = fst.getOutputSymbols().get(Fst.EPS);
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
for (MutableArc arc : s.getArcs()) {
if ((label == AugmentLabels.OUTPUT) && (arc.getOlabel() == oEps)) {
arc.setOlabel(e2outputIndex);
} else if ((label == AugmentLabels.INPUT) && (arc.getIlabel() == iEps)) {
arc.setIlabel(e1inputIndex);
}
}
if (label == AugmentLabels.INPUT) {
fst.addArc(s, e2inputIndex, oEps, s, semiring.one());
} else if (label == AugmentLabels.OUTPUT) {
fst.addArc(s, iEps, e1outputIndex, s, semiring.one());
}
}
} | java | private static void augment(AugmentLabels label, MutableFst fst, Semiring semiring, String eps1, String eps2) {
// label: 0->augment on ilabel
// 1->augment on olabel
int e1inputIndex = fst.getInputSymbols().getOrAdd(eps1);
int e2inputIndex = fst.getInputSymbols().getOrAdd(eps2);
int e1outputIndex = fst.getOutputSymbols().getOrAdd(eps1);
int e2outputIndex = fst.getOutputSymbols().getOrAdd(eps2);
int iEps = fst.getInputSymbols().get(Fst.EPS);
int oEps = fst.getOutputSymbols().get(Fst.EPS);
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
for (MutableArc arc : s.getArcs()) {
if ((label == AugmentLabels.OUTPUT) && (arc.getOlabel() == oEps)) {
arc.setOlabel(e2outputIndex);
} else if ((label == AugmentLabels.INPUT) && (arc.getIlabel() == iEps)) {
arc.setIlabel(e1inputIndex);
}
}
if (label == AugmentLabels.INPUT) {
fst.addArc(s, e2inputIndex, oEps, s, semiring.one());
} else if (label == AugmentLabels.OUTPUT) {
fst.addArc(s, iEps, e1outputIndex, s, semiring.one());
}
}
} | [
"private",
"static",
"void",
"augment",
"(",
"AugmentLabels",
"label",
",",
"MutableFst",
"fst",
",",
"Semiring",
"semiring",
",",
"String",
"eps1",
",",
"String",
"eps2",
")",
"{",
"// label: 0->augment on ilabel",
"// 1->augment on olabel",
"int",
"e1inputIndex",
"=",
"fst",
".",
"getInputSymbols",
"(",
")",
".",
"getOrAdd",
"(",
"eps1",
")",
";",
"int",
"e2inputIndex",
"=",
"fst",
".",
"getInputSymbols",
"(",
")",
".",
"getOrAdd",
"(",
"eps2",
")",
";",
"int",
"e1outputIndex",
"=",
"fst",
".",
"getOutputSymbols",
"(",
")",
".",
"getOrAdd",
"(",
"eps1",
")",
";",
"int",
"e2outputIndex",
"=",
"fst",
".",
"getOutputSymbols",
"(",
")",
".",
"getOrAdd",
"(",
"eps2",
")",
";",
"int",
"iEps",
"=",
"fst",
".",
"getInputSymbols",
"(",
")",
".",
"get",
"(",
"Fst",
".",
"EPS",
")",
";",
"int",
"oEps",
"=",
"fst",
".",
"getOutputSymbols",
"(",
")",
".",
"get",
"(",
"Fst",
".",
"EPS",
")",
";",
"int",
"numStates",
"=",
"fst",
".",
"getStateCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numStates",
";",
"i",
"++",
")",
"{",
"MutableState",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"for",
"(",
"MutableArc",
"arc",
":",
"s",
".",
"getArcs",
"(",
")",
")",
"{",
"if",
"(",
"(",
"label",
"==",
"AugmentLabels",
".",
"OUTPUT",
")",
"&&",
"(",
"arc",
".",
"getOlabel",
"(",
")",
"==",
"oEps",
")",
")",
"{",
"arc",
".",
"setOlabel",
"(",
"e2outputIndex",
")",
";",
"}",
"else",
"if",
"(",
"(",
"label",
"==",
"AugmentLabels",
".",
"INPUT",
")",
"&&",
"(",
"arc",
".",
"getIlabel",
"(",
")",
"==",
"iEps",
")",
")",
"{",
"arc",
".",
"setIlabel",
"(",
"e1inputIndex",
")",
";",
"}",
"}",
"if",
"(",
"label",
"==",
"AugmentLabels",
".",
"INPUT",
")",
"{",
"fst",
".",
"addArc",
"(",
"s",
",",
"e2inputIndex",
",",
"oEps",
",",
"s",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"label",
"==",
"AugmentLabels",
".",
"OUTPUT",
")",
"{",
"fst",
".",
"addArc",
"(",
"s",
",",
"iEps",
",",
"e1outputIndex",
",",
"s",
",",
"semiring",
".",
"one",
"(",
")",
")",
";",
"}",
"}",
"}"
] | Augments the labels of an Fst in order to use it for composition avoiding multiple epsilon paths in the resulting
Fst
@param label constant denoting if the augment should take place on input or output labels For value equal to 0
augment will take place for input labels For value equal to 1 augment will take place for output
labels
@param fst the fst to augment | [
"Augments",
"the",
"labels",
"of",
"an",
"Fst",
"in",
"order",
"to",
"use",
"it",
"for",
"composition",
"avoiding",
"multiple",
"epsilon",
"paths",
"in",
"the",
"resulting",
"Fst"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Compose.java#L230-L259 |
584 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Project.java | Project.apply | public static void apply(MutableFst fst, ProjectType pType) {
if (pType == ProjectType.INPUT) {
fst.setOutputSymbolsAsCopyFromThatInput(fst);
} else if (pType == ProjectType.OUTPUT) {
fst.setInputSymbolsAsCopyFromThatOutput(fst);
}
for (int i = 0; i < fst.getStateCount(); i++) {
MutableState state = fst.getState(i);
// Immutable fsts hold an additional (null) arc
for (int j = 0; j < state.getArcCount(); j++) {
MutableArc a = state.getArc(j);
if (pType == ProjectType.INPUT) {
a.setOlabel(a.getIlabel());
} else if (pType == ProjectType.OUTPUT) {
a.setIlabel(a.getOlabel());
}
}
}
} | java | public static void apply(MutableFst fst, ProjectType pType) {
if (pType == ProjectType.INPUT) {
fst.setOutputSymbolsAsCopyFromThatInput(fst);
} else if (pType == ProjectType.OUTPUT) {
fst.setInputSymbolsAsCopyFromThatOutput(fst);
}
for (int i = 0; i < fst.getStateCount(); i++) {
MutableState state = fst.getState(i);
// Immutable fsts hold an additional (null) arc
for (int j = 0; j < state.getArcCount(); j++) {
MutableArc a = state.getArc(j);
if (pType == ProjectType.INPUT) {
a.setOlabel(a.getIlabel());
} else if (pType == ProjectType.OUTPUT) {
a.setIlabel(a.getOlabel());
}
}
}
} | [
"public",
"static",
"void",
"apply",
"(",
"MutableFst",
"fst",
",",
"ProjectType",
"pType",
")",
"{",
"if",
"(",
"pType",
"==",
"ProjectType",
".",
"INPUT",
")",
"{",
"fst",
".",
"setOutputSymbolsAsCopyFromThatInput",
"(",
"fst",
")",
";",
"}",
"else",
"if",
"(",
"pType",
"==",
"ProjectType",
".",
"OUTPUT",
")",
"{",
"fst",
".",
"setInputSymbolsAsCopyFromThatOutput",
"(",
"fst",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"fst",
".",
"getStateCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"MutableState",
"state",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"// Immutable fsts hold an additional (null) arc",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"state",
".",
"getArcCount",
"(",
")",
";",
"j",
"++",
")",
"{",
"MutableArc",
"a",
"=",
"state",
".",
"getArc",
"(",
"j",
")",
";",
"if",
"(",
"pType",
"==",
"ProjectType",
".",
"INPUT",
")",
"{",
"a",
".",
"setOlabel",
"(",
"a",
".",
"getIlabel",
"(",
")",
")",
";",
"}",
"else",
"if",
"(",
"pType",
"==",
"ProjectType",
".",
"OUTPUT",
")",
"{",
"a",
".",
"setIlabel",
"(",
"a",
".",
"getOlabel",
"(",
")",
")",
";",
"}",
"}",
"}",
"}"
] | Projects an fst onto its domain or range by either copying each arc's input label to its output label or vice
versa. | [
"Projects",
"an",
"fst",
"onto",
"its",
"domain",
"or",
"range",
"by",
"either",
"copying",
"each",
"arc",
"s",
"input",
"label",
"to",
"its",
"output",
"label",
"or",
"vice",
"versa",
"."
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Project.java#L35-L54 |
585 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Connect.java | Connect.apply | public static void apply(MutableFst fst) {
fst.throwIfInvalid();
IntOpenHashSet accessible = new IntOpenHashSet(fst.getStateCount());
IntOpenHashSet coaccessible = new IntOpenHashSet(fst.getStateCount());
dfsForward(fst.getStartState(), accessible);
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
if (fst.getSemiring().isNotZero(s.getFinalWeight())) {
dfsBackward(s, coaccessible);
}
}
if (accessible.size() == fst.getStateCount() && coaccessible.size() == fst.getStateCount()) {
// common case, optimization bail early
return;
}
ArrayList<MutableState> toDelete = new ArrayList<>();
int startId = fst.getStartState().getId();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
if (s.getId() == startId) {
continue; // cant delete the start state
}
if (!accessible.contains(s.getId()) || !coaccessible.contains(s.getId())) {
toDelete.add(s);
}
}
fst.deleteStates(toDelete);
} | java | public static void apply(MutableFst fst) {
fst.throwIfInvalid();
IntOpenHashSet accessible = new IntOpenHashSet(fst.getStateCount());
IntOpenHashSet coaccessible = new IntOpenHashSet(fst.getStateCount());
dfsForward(fst.getStartState(), accessible);
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
if (fst.getSemiring().isNotZero(s.getFinalWeight())) {
dfsBackward(s, coaccessible);
}
}
if (accessible.size() == fst.getStateCount() && coaccessible.size() == fst.getStateCount()) {
// common case, optimization bail early
return;
}
ArrayList<MutableState> toDelete = new ArrayList<>();
int startId = fst.getStartState().getId();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
if (s.getId() == startId) {
continue; // cant delete the start state
}
if (!accessible.contains(s.getId()) || !coaccessible.contains(s.getId())) {
toDelete.add(s);
}
}
fst.deleteStates(toDelete);
} | [
"public",
"static",
"void",
"apply",
"(",
"MutableFst",
"fst",
")",
"{",
"fst",
".",
"throwIfInvalid",
"(",
")",
";",
"IntOpenHashSet",
"accessible",
"=",
"new",
"IntOpenHashSet",
"(",
"fst",
".",
"getStateCount",
"(",
")",
")",
";",
"IntOpenHashSet",
"coaccessible",
"=",
"new",
"IntOpenHashSet",
"(",
"fst",
".",
"getStateCount",
"(",
")",
")",
";",
"dfsForward",
"(",
"fst",
".",
"getStartState",
"(",
")",
",",
"accessible",
")",
";",
"int",
"numStates",
"=",
"fst",
".",
"getStateCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numStates",
";",
"i",
"++",
")",
"{",
"MutableState",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"if",
"(",
"fst",
".",
"getSemiring",
"(",
")",
".",
"isNotZero",
"(",
"s",
".",
"getFinalWeight",
"(",
")",
")",
")",
"{",
"dfsBackward",
"(",
"s",
",",
"coaccessible",
")",
";",
"}",
"}",
"if",
"(",
"accessible",
".",
"size",
"(",
")",
"==",
"fst",
".",
"getStateCount",
"(",
")",
"&&",
"coaccessible",
".",
"size",
"(",
")",
"==",
"fst",
".",
"getStateCount",
"(",
")",
")",
"{",
"// common case, optimization bail early",
"return",
";",
"}",
"ArrayList",
"<",
"MutableState",
">",
"toDelete",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"int",
"startId",
"=",
"fst",
".",
"getStartState",
"(",
")",
".",
"getId",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numStates",
";",
"i",
"++",
")",
"{",
"MutableState",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"if",
"(",
"s",
".",
"getId",
"(",
")",
"==",
"startId",
")",
"{",
"continue",
";",
"// cant delete the start state",
"}",
"if",
"(",
"!",
"accessible",
".",
"contains",
"(",
"s",
".",
"getId",
"(",
")",
")",
"||",
"!",
"coaccessible",
".",
"contains",
"(",
"s",
".",
"getId",
"(",
")",
")",
")",
"{",
"toDelete",
".",
"add",
"(",
"s",
")",
";",
"}",
"}",
"fst",
".",
"deleteStates",
"(",
"toDelete",
")",
";",
"}"
] | Trims an Fst, removing states and arcs that are not on successful paths.
@param fst the fst to trim | [
"Trims",
"an",
"Fst",
"removing",
"states",
"and",
"arcs",
"that",
"are",
"not",
"on",
"successful",
"paths",
"."
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Connect.java#L38-L69 |
586 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/MutableFst.java | MutableFst.setStart | public MutableState setStart(MutableState start) {
checkArgument(start.getId() >= 0, "must set id before setting start");
throwIfSymbolTableMissingId(start.getId());
correctStateWeight(start);
this.start = start;
return start;
} | java | public MutableState setStart(MutableState start) {
checkArgument(start.getId() >= 0, "must set id before setting start");
throwIfSymbolTableMissingId(start.getId());
correctStateWeight(start);
this.start = start;
return start;
} | [
"public",
"MutableState",
"setStart",
"(",
"MutableState",
"start",
")",
"{",
"checkArgument",
"(",
"start",
".",
"getId",
"(",
")",
">=",
"0",
",",
"\"must set id before setting start\"",
")",
";",
"throwIfSymbolTableMissingId",
"(",
"start",
".",
"getId",
"(",
")",
")",
";",
"correctStateWeight",
"(",
"start",
")",
";",
"this",
".",
"start",
"=",
"start",
";",
"return",
"start",
";",
"}"
] | Set the initial state
@param start the initial state | [
"Set",
"the",
"initial",
"state"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/MutableFst.java#L249-L255 |
587 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/MutableFst.java | MutableFst.deleteStates | public void deleteStates(Collection<MutableState> statesToDelete) {
if (statesToDelete.isEmpty()) {
return;
}
for (MutableState state : statesToDelete) {
deleteState(state);
}
remapStateIds();
} | java | public void deleteStates(Collection<MutableState> statesToDelete) {
if (statesToDelete.isEmpty()) {
return;
}
for (MutableState state : statesToDelete) {
deleteState(state);
}
remapStateIds();
} | [
"public",
"void",
"deleteStates",
"(",
"Collection",
"<",
"MutableState",
">",
"statesToDelete",
")",
"{",
"if",
"(",
"statesToDelete",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"for",
"(",
"MutableState",
"state",
":",
"statesToDelete",
")",
"{",
"deleteState",
"(",
"state",
")",
";",
"}",
"remapStateIds",
"(",
")",
";",
"}"
] | Deletes the given states and remaps the existing state ids | [
"Deletes",
"the",
"given",
"states",
"and",
"remaps",
"the",
"existing",
"state",
"ids"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/MutableFst.java#L494-L502 |
588 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/MutableFst.java | MutableFst.deleteState | private void deleteState(MutableState state) {
if (state.getId() == this.start.getId()) {
throw new IllegalArgumentException("Cannot delete start state.");
}
// we're going to "compact" all of the nulls out and remap state ids at the end
this.states.set(state.getId(), null);
if (isUsingStateSymbols()) {
stateSymbols.remove(state.getId());
}
// this state won't be incoming to any of its arc's targets anymore
for (MutableArc mutableArc : state.getArcs()) {
mutableArc.getNextState().removeIncomingState(state);
}
// delete arc's with nextstate equal to stateid
for (MutableState inState : state.getIncomingStates()) {
Iterator<MutableArc> iter = inState.getArcs().iterator();
while (iter.hasNext()) {
MutableArc arc = iter.next();
if (arc.getNextState() == state) {
iter.remove();
}
}
}
} | java | private void deleteState(MutableState state) {
if (state.getId() == this.start.getId()) {
throw new IllegalArgumentException("Cannot delete start state.");
}
// we're going to "compact" all of the nulls out and remap state ids at the end
this.states.set(state.getId(), null);
if (isUsingStateSymbols()) {
stateSymbols.remove(state.getId());
}
// this state won't be incoming to any of its arc's targets anymore
for (MutableArc mutableArc : state.getArcs()) {
mutableArc.getNextState().removeIncomingState(state);
}
// delete arc's with nextstate equal to stateid
for (MutableState inState : state.getIncomingStates()) {
Iterator<MutableArc> iter = inState.getArcs().iterator();
while (iter.hasNext()) {
MutableArc arc = iter.next();
if (arc.getNextState() == state) {
iter.remove();
}
}
}
} | [
"private",
"void",
"deleteState",
"(",
"MutableState",
"state",
")",
"{",
"if",
"(",
"state",
".",
"getId",
"(",
")",
"==",
"this",
".",
"start",
".",
"getId",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot delete start state.\"",
")",
";",
"}",
"// we're going to \"compact\" all of the nulls out and remap state ids at the end",
"this",
".",
"states",
".",
"set",
"(",
"state",
".",
"getId",
"(",
")",
",",
"null",
")",
";",
"if",
"(",
"isUsingStateSymbols",
"(",
")",
")",
"{",
"stateSymbols",
".",
"remove",
"(",
"state",
".",
"getId",
"(",
")",
")",
";",
"}",
"// this state won't be incoming to any of its arc's targets anymore",
"for",
"(",
"MutableArc",
"mutableArc",
":",
"state",
".",
"getArcs",
"(",
")",
")",
"{",
"mutableArc",
".",
"getNextState",
"(",
")",
".",
"removeIncomingState",
"(",
"state",
")",
";",
"}",
"// delete arc's with nextstate equal to stateid",
"for",
"(",
"MutableState",
"inState",
":",
"state",
".",
"getIncomingStates",
"(",
")",
")",
"{",
"Iterator",
"<",
"MutableArc",
">",
"iter",
"=",
"inState",
".",
"getArcs",
"(",
")",
".",
"iterator",
"(",
")",
";",
"while",
"(",
"iter",
".",
"hasNext",
"(",
")",
")",
"{",
"MutableArc",
"arc",
"=",
"iter",
".",
"next",
"(",
")",
";",
"if",
"(",
"arc",
".",
"getNextState",
"(",
")",
"==",
"state",
")",
"{",
"iter",
".",
"remove",
"(",
")",
";",
"}",
"}",
"}",
"}"
] | Deletes a state;
@param state the state to delete | [
"Deletes",
"a",
"state",
";"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/MutableFst.java#L509-L534 |
589 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Determinize.java | Determinize.compute | public MutableFst compute(final Fst fst) {
fst.throwIfInvalid();
// init for this run of compute
this.semiring = fst.getSemiring();
this.gallicSemiring = new GallicSemiring(this.semiring, this.gallicMode);
this.unionSemiring = makeUnionRing(semiring, gallicSemiring, mode);
this.inputFst = fst;
this.outputFst = MutableFst.emptyWithCopyOfSymbols(fst);
this.outputStateIdToTuple = HashBiMap.create();
// workQueue holds the pending work of determinizing the input fst
Deque<DetStateTuple> workQueue = new LinkedList<>();
// finalQueue holds the pending work of expanding out the final paths (handled by the FactorFst in the
// open fst implementation)
Deque<DetElement> finalQueue = new LinkedList<>();
// start the algorithm by starting with the input start state
MutableState initialOutState = outputFst.newStartState();
DetElement initialElement = new DetElement(fst.getStartState().getId(),
GallicWeight.createEmptyLabels(semiring.one()));
DetStateTuple initialTuple = new DetStateTuple(initialElement);
workQueue.addLast(initialTuple);
this.outputStateIdToTuple.put(initialOutState.getId(), initialTuple);
// process all of the input states via the work queue
while (!workQueue.isEmpty()) {
DetStateTuple entry = workQueue.removeFirst();
MutableState outStateForTuple = getOutputStateForStateTuple(entry);
Collection<DetArcWork> arcWorks = groupByInputLabel(entry);
arcWorks.forEach(this::normalizeArcWork);
for (DetArcWork arcWork : arcWorks) {
DetStateTuple targetTuple = new DetStateTuple(arcWork.pendingElements);
if (!this.outputStateIdToTuple.inverse().containsKey(targetTuple)) {
// we've never seen this tuple before so new state + enqueue the work
MutableState newOutState = outputFst.newState();
this.outputStateIdToTuple.put(newOutState.getId(), targetTuple);
newOutState.setFinalWeight(computeFinalWeight(newOutState.getId(), targetTuple, finalQueue));
workQueue.addLast(targetTuple);
}
MutableState targetOutState = getOutputStateForStateTuple(targetTuple);
// the computed divisor is a 'legal' arc meaning that it only has zero or one substring; though there
// might be multiple entries if we're in non_functional mode
UnionWeight<GallicWeight> unionWeight = arcWork.computedDivisor;
for (GallicWeight gallicWeight : unionWeight.getWeights()) {
Preconditions.checkState(gallicSemiring.isNotZero(gallicWeight), "gallic weight zero computed from group by",
gallicWeight);
int oLabel = this.outputEps;
if (!gallicWeight.getLabels().isEmpty()) {
Preconditions.checkState(gallicWeight.getLabels().size() == 1,
"cant gave gallic arc weight with more than a single symbol", gallicWeight);
oLabel = gallicWeight.getLabels().get(0);
}
outputFst.addArc(outStateForTuple, arcWork.inputLabel, oLabel, targetOutState, gallicWeight.getWeight());
}
}
}
// we might've deferred some final state work that needs to be expanded
expandDeferredFinalStates(finalQueue);
return outputFst;
} | java | public MutableFst compute(final Fst fst) {
fst.throwIfInvalid();
// init for this run of compute
this.semiring = fst.getSemiring();
this.gallicSemiring = new GallicSemiring(this.semiring, this.gallicMode);
this.unionSemiring = makeUnionRing(semiring, gallicSemiring, mode);
this.inputFst = fst;
this.outputFst = MutableFst.emptyWithCopyOfSymbols(fst);
this.outputStateIdToTuple = HashBiMap.create();
// workQueue holds the pending work of determinizing the input fst
Deque<DetStateTuple> workQueue = new LinkedList<>();
// finalQueue holds the pending work of expanding out the final paths (handled by the FactorFst in the
// open fst implementation)
Deque<DetElement> finalQueue = new LinkedList<>();
// start the algorithm by starting with the input start state
MutableState initialOutState = outputFst.newStartState();
DetElement initialElement = new DetElement(fst.getStartState().getId(),
GallicWeight.createEmptyLabels(semiring.one()));
DetStateTuple initialTuple = new DetStateTuple(initialElement);
workQueue.addLast(initialTuple);
this.outputStateIdToTuple.put(initialOutState.getId(), initialTuple);
// process all of the input states via the work queue
while (!workQueue.isEmpty()) {
DetStateTuple entry = workQueue.removeFirst();
MutableState outStateForTuple = getOutputStateForStateTuple(entry);
Collection<DetArcWork> arcWorks = groupByInputLabel(entry);
arcWorks.forEach(this::normalizeArcWork);
for (DetArcWork arcWork : arcWorks) {
DetStateTuple targetTuple = new DetStateTuple(arcWork.pendingElements);
if (!this.outputStateIdToTuple.inverse().containsKey(targetTuple)) {
// we've never seen this tuple before so new state + enqueue the work
MutableState newOutState = outputFst.newState();
this.outputStateIdToTuple.put(newOutState.getId(), targetTuple);
newOutState.setFinalWeight(computeFinalWeight(newOutState.getId(), targetTuple, finalQueue));
workQueue.addLast(targetTuple);
}
MutableState targetOutState = getOutputStateForStateTuple(targetTuple);
// the computed divisor is a 'legal' arc meaning that it only has zero or one substring; though there
// might be multiple entries if we're in non_functional mode
UnionWeight<GallicWeight> unionWeight = arcWork.computedDivisor;
for (GallicWeight gallicWeight : unionWeight.getWeights()) {
Preconditions.checkState(gallicSemiring.isNotZero(gallicWeight), "gallic weight zero computed from group by",
gallicWeight);
int oLabel = this.outputEps;
if (!gallicWeight.getLabels().isEmpty()) {
Preconditions.checkState(gallicWeight.getLabels().size() == 1,
"cant gave gallic arc weight with more than a single symbol", gallicWeight);
oLabel = gallicWeight.getLabels().get(0);
}
outputFst.addArc(outStateForTuple, arcWork.inputLabel, oLabel, targetOutState, gallicWeight.getWeight());
}
}
}
// we might've deferred some final state work that needs to be expanded
expandDeferredFinalStates(finalQueue);
return outputFst;
} | [
"public",
"MutableFst",
"compute",
"(",
"final",
"Fst",
"fst",
")",
"{",
"fst",
".",
"throwIfInvalid",
"(",
")",
";",
"// init for this run of compute",
"this",
".",
"semiring",
"=",
"fst",
".",
"getSemiring",
"(",
")",
";",
"this",
".",
"gallicSemiring",
"=",
"new",
"GallicSemiring",
"(",
"this",
".",
"semiring",
",",
"this",
".",
"gallicMode",
")",
";",
"this",
".",
"unionSemiring",
"=",
"makeUnionRing",
"(",
"semiring",
",",
"gallicSemiring",
",",
"mode",
")",
";",
"this",
".",
"inputFst",
"=",
"fst",
";",
"this",
".",
"outputFst",
"=",
"MutableFst",
".",
"emptyWithCopyOfSymbols",
"(",
"fst",
")",
";",
"this",
".",
"outputStateIdToTuple",
"=",
"HashBiMap",
".",
"create",
"(",
")",
";",
"// workQueue holds the pending work of determinizing the input fst",
"Deque",
"<",
"DetStateTuple",
">",
"workQueue",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"// finalQueue holds the pending work of expanding out the final paths (handled by the FactorFst in the",
"// open fst implementation)",
"Deque",
"<",
"DetElement",
">",
"finalQueue",
"=",
"new",
"LinkedList",
"<>",
"(",
")",
";",
"// start the algorithm by starting with the input start state",
"MutableState",
"initialOutState",
"=",
"outputFst",
".",
"newStartState",
"(",
")",
";",
"DetElement",
"initialElement",
"=",
"new",
"DetElement",
"(",
"fst",
".",
"getStartState",
"(",
")",
".",
"getId",
"(",
")",
",",
"GallicWeight",
".",
"createEmptyLabels",
"(",
"semiring",
".",
"one",
"(",
")",
")",
")",
";",
"DetStateTuple",
"initialTuple",
"=",
"new",
"DetStateTuple",
"(",
"initialElement",
")",
";",
"workQueue",
".",
"addLast",
"(",
"initialTuple",
")",
";",
"this",
".",
"outputStateIdToTuple",
".",
"put",
"(",
"initialOutState",
".",
"getId",
"(",
")",
",",
"initialTuple",
")",
";",
"// process all of the input states via the work queue",
"while",
"(",
"!",
"workQueue",
".",
"isEmpty",
"(",
")",
")",
"{",
"DetStateTuple",
"entry",
"=",
"workQueue",
".",
"removeFirst",
"(",
")",
";",
"MutableState",
"outStateForTuple",
"=",
"getOutputStateForStateTuple",
"(",
"entry",
")",
";",
"Collection",
"<",
"DetArcWork",
">",
"arcWorks",
"=",
"groupByInputLabel",
"(",
"entry",
")",
";",
"arcWorks",
".",
"forEach",
"(",
"this",
"::",
"normalizeArcWork",
")",
";",
"for",
"(",
"DetArcWork",
"arcWork",
":",
"arcWorks",
")",
"{",
"DetStateTuple",
"targetTuple",
"=",
"new",
"DetStateTuple",
"(",
"arcWork",
".",
"pendingElements",
")",
";",
"if",
"(",
"!",
"this",
".",
"outputStateIdToTuple",
".",
"inverse",
"(",
")",
".",
"containsKey",
"(",
"targetTuple",
")",
")",
"{",
"// we've never seen this tuple before so new state + enqueue the work",
"MutableState",
"newOutState",
"=",
"outputFst",
".",
"newState",
"(",
")",
";",
"this",
".",
"outputStateIdToTuple",
".",
"put",
"(",
"newOutState",
".",
"getId",
"(",
")",
",",
"targetTuple",
")",
";",
"newOutState",
".",
"setFinalWeight",
"(",
"computeFinalWeight",
"(",
"newOutState",
".",
"getId",
"(",
")",
",",
"targetTuple",
",",
"finalQueue",
")",
")",
";",
"workQueue",
".",
"addLast",
"(",
"targetTuple",
")",
";",
"}",
"MutableState",
"targetOutState",
"=",
"getOutputStateForStateTuple",
"(",
"targetTuple",
")",
";",
"// the computed divisor is a 'legal' arc meaning that it only has zero or one substring; though there",
"// might be multiple entries if we're in non_functional mode",
"UnionWeight",
"<",
"GallicWeight",
">",
"unionWeight",
"=",
"arcWork",
".",
"computedDivisor",
";",
"for",
"(",
"GallicWeight",
"gallicWeight",
":",
"unionWeight",
".",
"getWeights",
"(",
")",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"gallicSemiring",
".",
"isNotZero",
"(",
"gallicWeight",
")",
",",
"\"gallic weight zero computed from group by\"",
",",
"gallicWeight",
")",
";",
"int",
"oLabel",
"=",
"this",
".",
"outputEps",
";",
"if",
"(",
"!",
"gallicWeight",
".",
"getLabels",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"Preconditions",
".",
"checkState",
"(",
"gallicWeight",
".",
"getLabels",
"(",
")",
".",
"size",
"(",
")",
"==",
"1",
",",
"\"cant gave gallic arc weight with more than a single symbol\"",
",",
"gallicWeight",
")",
";",
"oLabel",
"=",
"gallicWeight",
".",
"getLabels",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"}",
"outputFst",
".",
"addArc",
"(",
"outStateForTuple",
",",
"arcWork",
".",
"inputLabel",
",",
"oLabel",
",",
"targetOutState",
",",
"gallicWeight",
".",
"getWeight",
"(",
")",
")",
";",
"}",
"}",
"}",
"// we might've deferred some final state work that needs to be expanded",
"expandDeferredFinalStates",
"(",
"finalQueue",
")",
";",
"return",
"outputFst",
";",
"}"
] | Determinizes an FSA or FST. For this algorithm, epsilon transitions are treated as regular symbols.
@param fst the fst to determinize
@return the determinized fst | [
"Determinizes",
"an",
"FSA",
"or",
"FST",
".",
"For",
"this",
"algorithm",
"epsilon",
"transitions",
"are",
"treated",
"as",
"regular",
"symbols",
"."
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Determinize.java#L126-L189 |
590 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Determinize.java | Determinize.normalizeArcWork | private void normalizeArcWork(final DetArcWork arcWork) {
Collections.sort(arcWork.pendingElements);
ArrayList<DetElement> deduped = Lists.newArrayList();
for (int i = 0; i < arcWork.pendingElements.size(); i++) {
// first update the running common divisor that we'll use later
DetElement currentElement = arcWork.pendingElements.get(i);
arcWork.computedDivisor = unionSemiring.commonDivisor(arcWork.computedDivisor, currentElement.residual);
// now we want to add and dedup at the same time (this is ok because we sorted)
if (deduped.isEmpty() || deduped.get(deduped.size() - 1).inputStateId != currentElement.inputStateId) {
deduped.add(currentElement);
} else {
// merge this next one into the existing one
int lastIndex = deduped.size() - 1;
DetElement lastElement = deduped.get(lastIndex);
UnionWeight<GallicWeight> merged = unionSemiring.plus(lastElement.residual, currentElement.residual);
deduped.set(lastIndex, lastElement.withResidual(merged));
}
}
arcWork.pendingElements = deduped;
// dividing out the weights with the divisor across all elements
for (int i = 0; i < arcWork.pendingElements.size(); i++) {
DetElement currentElement = arcWork.pendingElements.get(i);
UnionWeight<GallicWeight> divided = unionSemiring.divide(currentElement.residual, arcWork.computedDivisor);
arcWork.pendingElements.set(i, currentElement.withResidual(divided));
// we aren't quantizing anything in jopenfst but we would want to quantize here if we add that in the future
}
} | java | private void normalizeArcWork(final DetArcWork arcWork) {
Collections.sort(arcWork.pendingElements);
ArrayList<DetElement> deduped = Lists.newArrayList();
for (int i = 0; i < arcWork.pendingElements.size(); i++) {
// first update the running common divisor that we'll use later
DetElement currentElement = arcWork.pendingElements.get(i);
arcWork.computedDivisor = unionSemiring.commonDivisor(arcWork.computedDivisor, currentElement.residual);
// now we want to add and dedup at the same time (this is ok because we sorted)
if (deduped.isEmpty() || deduped.get(deduped.size() - 1).inputStateId != currentElement.inputStateId) {
deduped.add(currentElement);
} else {
// merge this next one into the existing one
int lastIndex = deduped.size() - 1;
DetElement lastElement = deduped.get(lastIndex);
UnionWeight<GallicWeight> merged = unionSemiring.plus(lastElement.residual, currentElement.residual);
deduped.set(lastIndex, lastElement.withResidual(merged));
}
}
arcWork.pendingElements = deduped;
// dividing out the weights with the divisor across all elements
for (int i = 0; i < arcWork.pendingElements.size(); i++) {
DetElement currentElement = arcWork.pendingElements.get(i);
UnionWeight<GallicWeight> divided = unionSemiring.divide(currentElement.residual, arcWork.computedDivisor);
arcWork.pendingElements.set(i, currentElement.withResidual(divided));
// we aren't quantizing anything in jopenfst but we would want to quantize here if we add that in the future
}
} | [
"private",
"void",
"normalizeArcWork",
"(",
"final",
"DetArcWork",
"arcWork",
")",
"{",
"Collections",
".",
"sort",
"(",
"arcWork",
".",
"pendingElements",
")",
";",
"ArrayList",
"<",
"DetElement",
">",
"deduped",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arcWork",
".",
"pendingElements",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"// first update the running common divisor that we'll use later",
"DetElement",
"currentElement",
"=",
"arcWork",
".",
"pendingElements",
".",
"get",
"(",
"i",
")",
";",
"arcWork",
".",
"computedDivisor",
"=",
"unionSemiring",
".",
"commonDivisor",
"(",
"arcWork",
".",
"computedDivisor",
",",
"currentElement",
".",
"residual",
")",
";",
"// now we want to add and dedup at the same time (this is ok because we sorted)",
"if",
"(",
"deduped",
".",
"isEmpty",
"(",
")",
"||",
"deduped",
".",
"get",
"(",
"deduped",
".",
"size",
"(",
")",
"-",
"1",
")",
".",
"inputStateId",
"!=",
"currentElement",
".",
"inputStateId",
")",
"{",
"deduped",
".",
"add",
"(",
"currentElement",
")",
";",
"}",
"else",
"{",
"// merge this next one into the existing one",
"int",
"lastIndex",
"=",
"deduped",
".",
"size",
"(",
")",
"-",
"1",
";",
"DetElement",
"lastElement",
"=",
"deduped",
".",
"get",
"(",
"lastIndex",
")",
";",
"UnionWeight",
"<",
"GallicWeight",
">",
"merged",
"=",
"unionSemiring",
".",
"plus",
"(",
"lastElement",
".",
"residual",
",",
"currentElement",
".",
"residual",
")",
";",
"deduped",
".",
"set",
"(",
"lastIndex",
",",
"lastElement",
".",
"withResidual",
"(",
"merged",
")",
")",
";",
"}",
"}",
"arcWork",
".",
"pendingElements",
"=",
"deduped",
";",
"// dividing out the weights with the divisor across all elements",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arcWork",
".",
"pendingElements",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"DetElement",
"currentElement",
"=",
"arcWork",
".",
"pendingElements",
".",
"get",
"(",
"i",
")",
";",
"UnionWeight",
"<",
"GallicWeight",
">",
"divided",
"=",
"unionSemiring",
".",
"divide",
"(",
"currentElement",
".",
"residual",
",",
"arcWork",
".",
"computedDivisor",
")",
";",
"arcWork",
".",
"pendingElements",
".",
"set",
"(",
"i",
",",
"currentElement",
".",
"withResidual",
"(",
"divided",
")",
")",
";",
"// we aren't quantizing anything in jopenfst but we would want to quantize here if we add that in the future",
"}",
"}"
] | and compute new resulting arc weights | [
"and",
"compute",
"new",
"resulting",
"arc",
"weights"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Determinize.java#L244-L271 |
591 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Determinize.java | Determinize.computeFinalWeight | private double computeFinalWeight(final int outputStateId,
final DetStateTuple targetTuple,
Deque<DetElement> finalQueue) {
UnionWeight<GallicWeight> result = this.unionSemiring.zero();
for (DetElement detElement : targetTuple.getElements()) {
State inputState = this.getInputStateForId(detElement.inputStateId);
if (this.semiring.isZero(inputState.getFinalWeight())) {
continue; // not final so it wont contribute
}
UnionWeight<GallicWeight> origFinal = UnionWeight.createSingle(GallicWeight.createEmptyLabels(
inputState.getFinalWeight()));
result = this.unionSemiring.plus(result, this.unionSemiring.times(detElement.residual, origFinal));
}
if (this.unionSemiring.isZero(result)) {
return this.semiring.zero();
}
if (result.size() == 1 && result.get(0).getLabels().isEmpty()) {
// by good fortune the residual is just a weight, no path to expand so this new state can have a final weight
// set now! with nothing to enqueue
return result.get(0).getWeight();
}
// this state can't be a final state because we have more path to emit so defer until later; we know that we cant
// have any duplicate elements in the finalQueue since we only call computeFinalWeight once for each outputStateId
finalQueue.addLast(new DetElement(outputStateId, result));
return this.semiring.zero(); // since we're deferring this weight can't be a final weight
} | java | private double computeFinalWeight(final int outputStateId,
final DetStateTuple targetTuple,
Deque<DetElement> finalQueue) {
UnionWeight<GallicWeight> result = this.unionSemiring.zero();
for (DetElement detElement : targetTuple.getElements()) {
State inputState = this.getInputStateForId(detElement.inputStateId);
if (this.semiring.isZero(inputState.getFinalWeight())) {
continue; // not final so it wont contribute
}
UnionWeight<GallicWeight> origFinal = UnionWeight.createSingle(GallicWeight.createEmptyLabels(
inputState.getFinalWeight()));
result = this.unionSemiring.plus(result, this.unionSemiring.times(detElement.residual, origFinal));
}
if (this.unionSemiring.isZero(result)) {
return this.semiring.zero();
}
if (result.size() == 1 && result.get(0).getLabels().isEmpty()) {
// by good fortune the residual is just a weight, no path to expand so this new state can have a final weight
// set now! with nothing to enqueue
return result.get(0).getWeight();
}
// this state can't be a final state because we have more path to emit so defer until later; we know that we cant
// have any duplicate elements in the finalQueue since we only call computeFinalWeight once for each outputStateId
finalQueue.addLast(new DetElement(outputStateId, result));
return this.semiring.zero(); // since we're deferring this weight can't be a final weight
} | [
"private",
"double",
"computeFinalWeight",
"(",
"final",
"int",
"outputStateId",
",",
"final",
"DetStateTuple",
"targetTuple",
",",
"Deque",
"<",
"DetElement",
">",
"finalQueue",
")",
"{",
"UnionWeight",
"<",
"GallicWeight",
">",
"result",
"=",
"this",
".",
"unionSemiring",
".",
"zero",
"(",
")",
";",
"for",
"(",
"DetElement",
"detElement",
":",
"targetTuple",
".",
"getElements",
"(",
")",
")",
"{",
"State",
"inputState",
"=",
"this",
".",
"getInputStateForId",
"(",
"detElement",
".",
"inputStateId",
")",
";",
"if",
"(",
"this",
".",
"semiring",
".",
"isZero",
"(",
"inputState",
".",
"getFinalWeight",
"(",
")",
")",
")",
"{",
"continue",
";",
"// not final so it wont contribute",
"}",
"UnionWeight",
"<",
"GallicWeight",
">",
"origFinal",
"=",
"UnionWeight",
".",
"createSingle",
"(",
"GallicWeight",
".",
"createEmptyLabels",
"(",
"inputState",
".",
"getFinalWeight",
"(",
")",
")",
")",
";",
"result",
"=",
"this",
".",
"unionSemiring",
".",
"plus",
"(",
"result",
",",
"this",
".",
"unionSemiring",
".",
"times",
"(",
"detElement",
".",
"residual",
",",
"origFinal",
")",
")",
";",
"}",
"if",
"(",
"this",
".",
"unionSemiring",
".",
"isZero",
"(",
"result",
")",
")",
"{",
"return",
"this",
".",
"semiring",
".",
"zero",
"(",
")",
";",
"}",
"if",
"(",
"result",
".",
"size",
"(",
")",
"==",
"1",
"&&",
"result",
".",
"get",
"(",
"0",
")",
".",
"getLabels",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"// by good fortune the residual is just a weight, no path to expand so this new state can have a final weight",
"// set now! with nothing to enqueue",
"return",
"result",
".",
"get",
"(",
"0",
")",
".",
"getWeight",
"(",
")",
";",
"}",
"// this state can't be a final state because we have more path to emit so defer until later; we know that we cant",
"// have any duplicate elements in the finalQueue since we only call computeFinalWeight once for each outputStateId",
"finalQueue",
".",
"addLast",
"(",
"new",
"DetElement",
"(",
"outputStateId",
",",
"result",
")",
")",
";",
"return",
"this",
".",
"semiring",
".",
"zero",
"(",
")",
";",
"// since we're deferring this weight can't be a final weight",
"}"
] | _this_ new outState a final state, and instead we queue it into a separate queue for later expansion | [
"_this_",
"new",
"outState",
"a",
"final",
"state",
"and",
"instead",
"we",
"queue",
"it",
"into",
"a",
"separate",
"queue",
"for",
"later",
"expansion"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Determinize.java#L278-L303 |
592 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/Determinize.java | Determinize.expandDeferredFinalStates | private void expandDeferredFinalStates(Deque<DetElement> finalQueue) {
HashBiMap<Integer, GallicWeight> outputStateIdToFinalSuffix = HashBiMap.create();
while (!finalQueue.isEmpty()) {
DetElement element = finalQueue.removeFirst();
for (GallicWeight gallicWeight : element.residual.getWeights()) {
// factorization is like a simple version of the divisor/divide calculation earlier
Pair<GallicWeight, GallicWeight> factorized = gallicSemiring.factorize(gallicWeight);
GallicWeight prefix = factorized.getLeft();
GallicWeight suffix = factorized.getRight();
if (!outputStateIdToFinalSuffix.inverse().containsKey(suffix)) {
// we don't have a synthetic state for this suffix yet
MutableState newOutputState = outputFst.newState();
outputStateIdToFinalSuffix.put(newOutputState.getId(), suffix);
if (suffix.getLabels().isEmpty()) {
// this suffix is a real final state, and there's no more work to do
newOutputState.setFinalWeight(suffix.getWeight());
} else {
// this suffix still has more labels to emit, so leave final weight as zero and enqueue for expansion
finalQueue.addLast(new DetElement(newOutputState.getId(), suffix));
}
}
Integer outputStateId = outputStateIdToFinalSuffix.inverse().get(suffix);
MutableState nextState = checkNotNull(outputFst.getState(outputStateId), "state should exist", outputStateId);
MutableState thisState = checkNotNull(outputFst.getState(element.inputStateId));
Preconditions.checkArgument(prefix.getLabels().size() == 1, "prefix size should be 1", prefix);
int oLabel = prefix.getLabels().get(0);
// note that openfst has an 'increment subsequent epsilons' feature so that these paths can still be
// guarenteed to be deterministic (with just multiple definitions of <EPS>; this feature would go here
// if we decide to implement it in the future
outputFst.addArc(thisState, this.outputEps, oLabel, nextState, prefix.getWeight());
}
}
} | java | private void expandDeferredFinalStates(Deque<DetElement> finalQueue) {
HashBiMap<Integer, GallicWeight> outputStateIdToFinalSuffix = HashBiMap.create();
while (!finalQueue.isEmpty()) {
DetElement element = finalQueue.removeFirst();
for (GallicWeight gallicWeight : element.residual.getWeights()) {
// factorization is like a simple version of the divisor/divide calculation earlier
Pair<GallicWeight, GallicWeight> factorized = gallicSemiring.factorize(gallicWeight);
GallicWeight prefix = factorized.getLeft();
GallicWeight suffix = factorized.getRight();
if (!outputStateIdToFinalSuffix.inverse().containsKey(suffix)) {
// we don't have a synthetic state for this suffix yet
MutableState newOutputState = outputFst.newState();
outputStateIdToFinalSuffix.put(newOutputState.getId(), suffix);
if (suffix.getLabels().isEmpty()) {
// this suffix is a real final state, and there's no more work to do
newOutputState.setFinalWeight(suffix.getWeight());
} else {
// this suffix still has more labels to emit, so leave final weight as zero and enqueue for expansion
finalQueue.addLast(new DetElement(newOutputState.getId(), suffix));
}
}
Integer outputStateId = outputStateIdToFinalSuffix.inverse().get(suffix);
MutableState nextState = checkNotNull(outputFst.getState(outputStateId), "state should exist", outputStateId);
MutableState thisState = checkNotNull(outputFst.getState(element.inputStateId));
Preconditions.checkArgument(prefix.getLabels().size() == 1, "prefix size should be 1", prefix);
int oLabel = prefix.getLabels().get(0);
// note that openfst has an 'increment subsequent epsilons' feature so that these paths can still be
// guarenteed to be deterministic (with just multiple definitions of <EPS>; this feature would go here
// if we decide to implement it in the future
outputFst.addArc(thisState, this.outputEps, oLabel, nextState, prefix.getWeight());
}
}
} | [
"private",
"void",
"expandDeferredFinalStates",
"(",
"Deque",
"<",
"DetElement",
">",
"finalQueue",
")",
"{",
"HashBiMap",
"<",
"Integer",
",",
"GallicWeight",
">",
"outputStateIdToFinalSuffix",
"=",
"HashBiMap",
".",
"create",
"(",
")",
";",
"while",
"(",
"!",
"finalQueue",
".",
"isEmpty",
"(",
")",
")",
"{",
"DetElement",
"element",
"=",
"finalQueue",
".",
"removeFirst",
"(",
")",
";",
"for",
"(",
"GallicWeight",
"gallicWeight",
":",
"element",
".",
"residual",
".",
"getWeights",
"(",
")",
")",
"{",
"// factorization is like a simple version of the divisor/divide calculation earlier",
"Pair",
"<",
"GallicWeight",
",",
"GallicWeight",
">",
"factorized",
"=",
"gallicSemiring",
".",
"factorize",
"(",
"gallicWeight",
")",
";",
"GallicWeight",
"prefix",
"=",
"factorized",
".",
"getLeft",
"(",
")",
";",
"GallicWeight",
"suffix",
"=",
"factorized",
".",
"getRight",
"(",
")",
";",
"if",
"(",
"!",
"outputStateIdToFinalSuffix",
".",
"inverse",
"(",
")",
".",
"containsKey",
"(",
"suffix",
")",
")",
"{",
"// we don't have a synthetic state for this suffix yet",
"MutableState",
"newOutputState",
"=",
"outputFst",
".",
"newState",
"(",
")",
";",
"outputStateIdToFinalSuffix",
".",
"put",
"(",
"newOutputState",
".",
"getId",
"(",
")",
",",
"suffix",
")",
";",
"if",
"(",
"suffix",
".",
"getLabels",
"(",
")",
".",
"isEmpty",
"(",
")",
")",
"{",
"// this suffix is a real final state, and there's no more work to do",
"newOutputState",
".",
"setFinalWeight",
"(",
"suffix",
".",
"getWeight",
"(",
")",
")",
";",
"}",
"else",
"{",
"// this suffix still has more labels to emit, so leave final weight as zero and enqueue for expansion",
"finalQueue",
".",
"addLast",
"(",
"new",
"DetElement",
"(",
"newOutputState",
".",
"getId",
"(",
")",
",",
"suffix",
")",
")",
";",
"}",
"}",
"Integer",
"outputStateId",
"=",
"outputStateIdToFinalSuffix",
".",
"inverse",
"(",
")",
".",
"get",
"(",
"suffix",
")",
";",
"MutableState",
"nextState",
"=",
"checkNotNull",
"(",
"outputFst",
".",
"getState",
"(",
"outputStateId",
")",
",",
"\"state should exist\"",
",",
"outputStateId",
")",
";",
"MutableState",
"thisState",
"=",
"checkNotNull",
"(",
"outputFst",
".",
"getState",
"(",
"element",
".",
"inputStateId",
")",
")",
";",
"Preconditions",
".",
"checkArgument",
"(",
"prefix",
".",
"getLabels",
"(",
")",
".",
"size",
"(",
")",
"==",
"1",
",",
"\"prefix size should be 1\"",
",",
"prefix",
")",
";",
"int",
"oLabel",
"=",
"prefix",
".",
"getLabels",
"(",
")",
".",
"get",
"(",
"0",
")",
";",
"// note that openfst has an 'increment subsequent epsilons' feature so that these paths can still be",
"// guarenteed to be deterministic (with just multiple definitions of <EPS>; this feature would go here",
"// if we decide to implement it in the future",
"outputFst",
".",
"addArc",
"(",
"thisState",
",",
"this",
".",
"outputEps",
",",
"oLabel",
",",
"nextState",
",",
"prefix",
".",
"getWeight",
"(",
")",
")",
";",
"}",
"}",
"}"
] | residual primitive weight early in the path) | [
"residual",
"primitive",
"weight",
"early",
"in",
"the",
"path",
")"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/Determinize.java#L308-L340 |
593 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/FstInputOutput.java | FstInputOutput.readStringMap | public static MutableSymbolTable readStringMap(ObjectInput in)
throws IOException, ClassNotFoundException {
int mapSize = in.readInt();
MutableSymbolTable syms = new MutableSymbolTable();
for (int i = 0; i < mapSize; i++) {
String sym = in.readUTF();
int index = in.readInt();
syms.put(sym, index);
}
return syms;
} | java | public static MutableSymbolTable readStringMap(ObjectInput in)
throws IOException, ClassNotFoundException {
int mapSize = in.readInt();
MutableSymbolTable syms = new MutableSymbolTable();
for (int i = 0; i < mapSize; i++) {
String sym = in.readUTF();
int index = in.readInt();
syms.put(sym, index);
}
return syms;
} | [
"public",
"static",
"MutableSymbolTable",
"readStringMap",
"(",
"ObjectInput",
"in",
")",
"throws",
"IOException",
",",
"ClassNotFoundException",
"{",
"int",
"mapSize",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"MutableSymbolTable",
"syms",
"=",
"new",
"MutableSymbolTable",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mapSize",
";",
"i",
"++",
")",
"{",
"String",
"sym",
"=",
"in",
".",
"readUTF",
"(",
")",
";",
"int",
"index",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"syms",
".",
"put",
"(",
"sym",
",",
"index",
")",
";",
"}",
"return",
"syms",
";",
"}"
] | Deserializes a symbol map from an java.io.ObjectInput
@param in the java.io.ObjectInput. It should be already be initialized by the caller.
@return the deserialized symbol map | [
"Deserializes",
"a",
"symbol",
"map",
"from",
"an",
"java",
".",
"io",
".",
"ObjectInput"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/FstInputOutput.java#L59-L70 |
594 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/FstInputOutput.java | FstInputOutput.readFstFromBinaryStream | public static MutableFst readFstFromBinaryStream(ObjectInput in) throws IOException,
ClassNotFoundException {
int version = in.readInt();
if (version < FIRST_VERSION && version > CURRENT_VERSION) {
throw new IllegalArgumentException("cant read version fst model " + version);
}
MutableSymbolTable is = readStringMap(in);
MutableSymbolTable os = readStringMap(in);
MutableSymbolTable ss = null;
if (in.readBoolean()) {
ss = readStringMap(in);
}
return readFstWithTables(in, is, os, ss);
} | java | public static MutableFst readFstFromBinaryStream(ObjectInput in) throws IOException,
ClassNotFoundException {
int version = in.readInt();
if (version < FIRST_VERSION && version > CURRENT_VERSION) {
throw new IllegalArgumentException("cant read version fst model " + version);
}
MutableSymbolTable is = readStringMap(in);
MutableSymbolTable os = readStringMap(in);
MutableSymbolTable ss = null;
if (in.readBoolean()) {
ss = readStringMap(in);
}
return readFstWithTables(in, is, os, ss);
} | [
"public",
"static",
"MutableFst",
"readFstFromBinaryStream",
"(",
"ObjectInput",
"in",
")",
"throws",
"IOException",
",",
"ClassNotFoundException",
"{",
"int",
"version",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"if",
"(",
"version",
"<",
"FIRST_VERSION",
"&&",
"version",
">",
"CURRENT_VERSION",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"cant read version fst model \"",
"+",
"version",
")",
";",
"}",
"MutableSymbolTable",
"is",
"=",
"readStringMap",
"(",
"in",
")",
";",
"MutableSymbolTable",
"os",
"=",
"readStringMap",
"(",
"in",
")",
";",
"MutableSymbolTable",
"ss",
"=",
"null",
";",
"if",
"(",
"in",
".",
"readBoolean",
"(",
")",
")",
"{",
"ss",
"=",
"readStringMap",
"(",
"in",
")",
";",
"}",
"return",
"readFstWithTables",
"(",
"in",
",",
"is",
",",
"os",
",",
"ss",
")",
";",
"}"
] | Deserializes an Fst from an ObjectInput
@param in the ObjectInput. It should be already be initialized by the caller. | [
"Deserializes",
"an",
"Fst",
"from",
"an",
"ObjectInput"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/FstInputOutput.java#L77-L92 |
595 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/FstInputOutput.java | FstInputOutput.writeStringMap | private static void writeStringMap(SymbolTable map, ObjectOutput out)
throws IOException {
out.writeInt(map.size());
for (ObjectIntCursor<String> cursor : map) {
out.writeUTF(cursor.key);
out.writeInt(cursor.value);
}
} | java | private static void writeStringMap(SymbolTable map, ObjectOutput out)
throws IOException {
out.writeInt(map.size());
for (ObjectIntCursor<String> cursor : map) {
out.writeUTF(cursor.key);
out.writeInt(cursor.value);
}
} | [
"private",
"static",
"void",
"writeStringMap",
"(",
"SymbolTable",
"map",
",",
"ObjectOutput",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"writeInt",
"(",
"map",
".",
"size",
"(",
")",
")",
";",
"for",
"(",
"ObjectIntCursor",
"<",
"String",
">",
"cursor",
":",
"map",
")",
"{",
"out",
".",
"writeUTF",
"(",
"cursor",
".",
"key",
")",
";",
"out",
".",
"writeInt",
"(",
"cursor",
".",
"value",
")",
";",
"}",
"}"
] | Serializes a symbol map to an ObjectOutput
@param map the symbol map to serialize
@param out the ObjectOutput. It should be already be initialized by the caller. | [
"Serializes",
"a",
"symbol",
"map",
"to",
"an",
"ObjectOutput"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/FstInputOutput.java#L172-L179 |
596 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/FstInputOutput.java | FstInputOutput.writeFstToBinaryStream | public static void writeFstToBinaryStream(Fst fst, ObjectOutput out) throws IOException {
out.writeInt(CURRENT_VERSION);
writeStringMap(fst.getInputSymbols(), out);
writeStringMap(fst.getOutputSymbols(), out);
out.writeBoolean(fst.isUsingStateSymbols()); // whether or not we used a state symbol table
if (fst.isUsingStateSymbols()) {
writeStringMap(fst.getStateSymbols(), out);
}
out.writeInt(fst.getStartState().getId());
out.writeObject(fst.getSemiring());
out.writeInt(fst.getStateCount());
Map<State, Integer> stateMap = new IdentityHashMap<>(fst.getStateCount());
for (int i = 0; i < fst.getStateCount(); i++) {
State s = fst.getState(i);
out.writeInt(s.getArcCount());
out.writeDouble(s.getFinalWeight());
out.writeInt(s.getId());
stateMap.put(s, i);
}
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
int numArcs = s.getArcCount();
for (int j = 0; j < numArcs; j++) {
Arc a = s.getArc(j);
out.writeInt(a.getIlabel());
out.writeInt(a.getOlabel());
out.writeDouble(a.getWeight());
out.writeInt(stateMap.get(a.getNextState()));
}
}
} | java | public static void writeFstToBinaryStream(Fst fst, ObjectOutput out) throws IOException {
out.writeInt(CURRENT_VERSION);
writeStringMap(fst.getInputSymbols(), out);
writeStringMap(fst.getOutputSymbols(), out);
out.writeBoolean(fst.isUsingStateSymbols()); // whether or not we used a state symbol table
if (fst.isUsingStateSymbols()) {
writeStringMap(fst.getStateSymbols(), out);
}
out.writeInt(fst.getStartState().getId());
out.writeObject(fst.getSemiring());
out.writeInt(fst.getStateCount());
Map<State, Integer> stateMap = new IdentityHashMap<>(fst.getStateCount());
for (int i = 0; i < fst.getStateCount(); i++) {
State s = fst.getState(i);
out.writeInt(s.getArcCount());
out.writeDouble(s.getFinalWeight());
out.writeInt(s.getId());
stateMap.put(s, i);
}
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
int numArcs = s.getArcCount();
for (int j = 0; j < numArcs; j++) {
Arc a = s.getArc(j);
out.writeInt(a.getIlabel());
out.writeInt(a.getOlabel());
out.writeDouble(a.getWeight());
out.writeInt(stateMap.get(a.getNextState()));
}
}
} | [
"public",
"static",
"void",
"writeFstToBinaryStream",
"(",
"Fst",
"fst",
",",
"ObjectOutput",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"writeInt",
"(",
"CURRENT_VERSION",
")",
";",
"writeStringMap",
"(",
"fst",
".",
"getInputSymbols",
"(",
")",
",",
"out",
")",
";",
"writeStringMap",
"(",
"fst",
".",
"getOutputSymbols",
"(",
")",
",",
"out",
")",
";",
"out",
".",
"writeBoolean",
"(",
"fst",
".",
"isUsingStateSymbols",
"(",
")",
")",
";",
"// whether or not we used a state symbol table",
"if",
"(",
"fst",
".",
"isUsingStateSymbols",
"(",
")",
")",
"{",
"writeStringMap",
"(",
"fst",
".",
"getStateSymbols",
"(",
")",
",",
"out",
")",
";",
"}",
"out",
".",
"writeInt",
"(",
"fst",
".",
"getStartState",
"(",
")",
".",
"getId",
"(",
")",
")",
";",
"out",
".",
"writeObject",
"(",
"fst",
".",
"getSemiring",
"(",
")",
")",
";",
"out",
".",
"writeInt",
"(",
"fst",
".",
"getStateCount",
"(",
")",
")",
";",
"Map",
"<",
"State",
",",
"Integer",
">",
"stateMap",
"=",
"new",
"IdentityHashMap",
"<>",
"(",
"fst",
".",
"getStateCount",
"(",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"fst",
".",
"getStateCount",
"(",
")",
";",
"i",
"++",
")",
"{",
"State",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"out",
".",
"writeInt",
"(",
"s",
".",
"getArcCount",
"(",
")",
")",
";",
"out",
".",
"writeDouble",
"(",
"s",
".",
"getFinalWeight",
"(",
")",
")",
";",
"out",
".",
"writeInt",
"(",
"s",
".",
"getId",
"(",
")",
")",
";",
"stateMap",
".",
"put",
"(",
"s",
",",
"i",
")",
";",
"}",
"int",
"numStates",
"=",
"fst",
".",
"getStateCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numStates",
";",
"i",
"++",
")",
"{",
"State",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"int",
"numArcs",
"=",
"s",
".",
"getArcCount",
"(",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"numArcs",
";",
"j",
"++",
")",
"{",
"Arc",
"a",
"=",
"s",
".",
"getArc",
"(",
"j",
")",
";",
"out",
".",
"writeInt",
"(",
"a",
".",
"getIlabel",
"(",
")",
")",
";",
"out",
".",
"writeInt",
"(",
"a",
".",
"getOlabel",
"(",
")",
")",
";",
"out",
".",
"writeDouble",
"(",
"a",
".",
"getWeight",
"(",
")",
")",
";",
"out",
".",
"writeInt",
"(",
"stateMap",
".",
"get",
"(",
"a",
".",
"getNextState",
"(",
")",
")",
")",
";",
"}",
"}",
"}"
] | Serializes the current Fst instance to an ObjectOutput
@param out the ObjectOutput. It should be already be initialized by the caller. | [
"Serializes",
"the",
"current",
"Fst",
"instance",
"to",
"an",
"ObjectOutput"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/FstInputOutput.java#L186-L220 |
597 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/ArcSort.java | ArcSort.sortBy | public static void sortBy(MutableFst fst, Comparator<Arc> comparator) {
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
s.arcSort(comparator);
}
} | java | public static void sortBy(MutableFst fst, Comparator<Arc> comparator) {
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
MutableState s = fst.getState(i);
s.arcSort(comparator);
}
} | [
"public",
"static",
"void",
"sortBy",
"(",
"MutableFst",
"fst",
",",
"Comparator",
"<",
"Arc",
">",
"comparator",
")",
"{",
"int",
"numStates",
"=",
"fst",
".",
"getStateCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numStates",
";",
"i",
"++",
")",
"{",
"MutableState",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"s",
".",
"arcSort",
"(",
"comparator",
")",
";",
"}",
"}"
] | Applies the ArcSort on the provided fst. Sorting can be applied either on input or output label based on the
provided comparator.
@param fst the fst to sort it's arcs
@param comparator the provided Comparator | [
"Applies",
"the",
"ArcSort",
"on",
"the",
"provided",
"fst",
".",
"Sorting",
"can",
"be",
"applied",
"either",
"on",
"input",
"or",
"output",
"label",
"based",
"on",
"the",
"provided",
"comparator",
"."
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/ArcSort.java#L59-L65 |
598 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/operations/ArcSort.java | ArcSort.isSorted | public static boolean isSorted(State state, Comparator<Arc> comparator) {
return Ordering.from(comparator).isOrdered(state.getArcs());
} | java | public static boolean isSorted(State state, Comparator<Arc> comparator) {
return Ordering.from(comparator).isOrdered(state.getArcs());
} | [
"public",
"static",
"boolean",
"isSorted",
"(",
"State",
"state",
",",
"Comparator",
"<",
"Arc",
">",
"comparator",
")",
"{",
"return",
"Ordering",
".",
"from",
"(",
"comparator",
")",
".",
"isOrdered",
"(",
"state",
".",
"getArcs",
"(",
")",
")",
";",
"}"
] | Returns true if the given state is sorted by the comparator
@param state
@param comparator
@return | [
"Returns",
"true",
"if",
"the",
"given",
"state",
"is",
"sorted",
"by",
"the",
"comparator"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/operations/ArcSort.java#L73-L75 |
599 | steveash/jopenfst | src/main/java/com/github/steveash/jopenfst/io/Convert.java | Convert.exportFst | private static void exportFst(Fst fst, String filename) {
FileWriter file;
try {
file = new FileWriter(filename);
PrintWriter out = new PrintWriter(file);
// print start first
State start = fst.getStartState();
out.println(start.getId() + "\t" + start.getFinalWeight());
// print all states
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
if (s.getId() == fst.getStartState().getId()) {
continue;
}
if (fst.getSemiring().isNotZero(s.getFinalWeight()) || !omitZeroStates) {
out.println(s.getId() + "\t" + s.getFinalWeight());
}
}
MutableSymbolTable.InvertedSymbolTable inputIds = fst.getInputSymbols().invert();
MutableSymbolTable.InvertedSymbolTable outputIds = fst.getOutputSymbols().invert();
numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
int numArcs = s.getArcCount();
for (int j = 0; j < numArcs; j++) {
Arc arc = s.getArc(j);
String isym;
String osym;
if (useSymbolIdsInText) {
isym = Integer.toString(arc.getIlabel());
osym = Integer.toString(arc.getOlabel());
} else {
isym = inputIds.keyForId(arc.getIlabel());
osym = outputIds.keyForId(arc.getOlabel());
}
out.println(s.getId() + "\t" + arc.getNextState().getId()
+ "\t" + isym + "\t" + osym + "\t"
+ arc.getWeight());
}
}
out.close();
} catch (IOException e) {
throw Throwables.propagate(e);
}
} | java | private static void exportFst(Fst fst, String filename) {
FileWriter file;
try {
file = new FileWriter(filename);
PrintWriter out = new PrintWriter(file);
// print start first
State start = fst.getStartState();
out.println(start.getId() + "\t" + start.getFinalWeight());
// print all states
int numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
if (s.getId() == fst.getStartState().getId()) {
continue;
}
if (fst.getSemiring().isNotZero(s.getFinalWeight()) || !omitZeroStates) {
out.println(s.getId() + "\t" + s.getFinalWeight());
}
}
MutableSymbolTable.InvertedSymbolTable inputIds = fst.getInputSymbols().invert();
MutableSymbolTable.InvertedSymbolTable outputIds = fst.getOutputSymbols().invert();
numStates = fst.getStateCount();
for (int i = 0; i < numStates; i++) {
State s = fst.getState(i);
int numArcs = s.getArcCount();
for (int j = 0; j < numArcs; j++) {
Arc arc = s.getArc(j);
String isym;
String osym;
if (useSymbolIdsInText) {
isym = Integer.toString(arc.getIlabel());
osym = Integer.toString(arc.getOlabel());
} else {
isym = inputIds.keyForId(arc.getIlabel());
osym = outputIds.keyForId(arc.getOlabel());
}
out.println(s.getId() + "\t" + arc.getNextState().getId()
+ "\t" + isym + "\t" + osym + "\t"
+ arc.getWeight());
}
}
out.close();
} catch (IOException e) {
throw Throwables.propagate(e);
}
} | [
"private",
"static",
"void",
"exportFst",
"(",
"Fst",
"fst",
",",
"String",
"filename",
")",
"{",
"FileWriter",
"file",
";",
"try",
"{",
"file",
"=",
"new",
"FileWriter",
"(",
"filename",
")",
";",
"PrintWriter",
"out",
"=",
"new",
"PrintWriter",
"(",
"file",
")",
";",
"// print start first",
"State",
"start",
"=",
"fst",
".",
"getStartState",
"(",
")",
";",
"out",
".",
"println",
"(",
"start",
".",
"getId",
"(",
")",
"+",
"\"\\t\"",
"+",
"start",
".",
"getFinalWeight",
"(",
")",
")",
";",
"// print all states",
"int",
"numStates",
"=",
"fst",
".",
"getStateCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numStates",
";",
"i",
"++",
")",
"{",
"State",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"if",
"(",
"s",
".",
"getId",
"(",
")",
"==",
"fst",
".",
"getStartState",
"(",
")",
".",
"getId",
"(",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"fst",
".",
"getSemiring",
"(",
")",
".",
"isNotZero",
"(",
"s",
".",
"getFinalWeight",
"(",
")",
")",
"||",
"!",
"omitZeroStates",
")",
"{",
"out",
".",
"println",
"(",
"s",
".",
"getId",
"(",
")",
"+",
"\"\\t\"",
"+",
"s",
".",
"getFinalWeight",
"(",
")",
")",
";",
"}",
"}",
"MutableSymbolTable",
".",
"InvertedSymbolTable",
"inputIds",
"=",
"fst",
".",
"getInputSymbols",
"(",
")",
".",
"invert",
"(",
")",
";",
"MutableSymbolTable",
".",
"InvertedSymbolTable",
"outputIds",
"=",
"fst",
".",
"getOutputSymbols",
"(",
")",
".",
"invert",
"(",
")",
";",
"numStates",
"=",
"fst",
".",
"getStateCount",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"numStates",
";",
"i",
"++",
")",
"{",
"State",
"s",
"=",
"fst",
".",
"getState",
"(",
"i",
")",
";",
"int",
"numArcs",
"=",
"s",
".",
"getArcCount",
"(",
")",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"numArcs",
";",
"j",
"++",
")",
"{",
"Arc",
"arc",
"=",
"s",
".",
"getArc",
"(",
"j",
")",
";",
"String",
"isym",
";",
"String",
"osym",
";",
"if",
"(",
"useSymbolIdsInText",
")",
"{",
"isym",
"=",
"Integer",
".",
"toString",
"(",
"arc",
".",
"getIlabel",
"(",
")",
")",
";",
"osym",
"=",
"Integer",
".",
"toString",
"(",
"arc",
".",
"getOlabel",
"(",
")",
")",
";",
"}",
"else",
"{",
"isym",
"=",
"inputIds",
".",
"keyForId",
"(",
"arc",
".",
"getIlabel",
"(",
")",
")",
";",
"osym",
"=",
"outputIds",
".",
"keyForId",
"(",
"arc",
".",
"getOlabel",
"(",
")",
")",
";",
"}",
"out",
".",
"println",
"(",
"s",
".",
"getId",
"(",
")",
"+",
"\"\\t\"",
"+",
"arc",
".",
"getNextState",
"(",
")",
".",
"getId",
"(",
")",
"+",
"\"\\t\"",
"+",
"isym",
"+",
"\"\\t\"",
"+",
"osym",
"+",
"\"\\t\"",
"+",
"arc",
".",
"getWeight",
"(",
")",
")",
";",
"}",
"}",
"out",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"Throwables",
".",
"propagate",
"(",
"e",
")",
";",
"}",
"}"
] | Exports an fst to the openfst text format
@param fst the fst to export
@param filename the openfst's fst.txt filename | [
"Exports",
"an",
"fst",
"to",
"the",
"openfst",
"text",
"format"
] | 4c675203015c1cfad2072556cb532b6edc73261d | https://github.com/steveash/jopenfst/blob/4c675203015c1cfad2072556cb532b6edc73261d/src/main/java/com/github/steveash/jopenfst/io/Convert.java#L156-L207 |