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
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
partition
stringclasses
1 value
milaboratory/milib
src/main/java/com/milaboratory/primitivio/PrimitivIO.java
PrimitivIO.dummySerializer
public static <T> Serializer<T> dummySerializer() { return new Serializer<T>() { @Override public void write(PrimitivO output, T object) { throw new RuntimeException("Dummy serializer."); } @Override public T read(PrimitivI input) { throw new RuntimeException("Dummy serializer."); } @Override public boolean isReference() { return true; } @Override public boolean handlesReference() { return false; } }; }
java
public static <T> Serializer<T> dummySerializer() { return new Serializer<T>() { @Override public void write(PrimitivO output, T object) { throw new RuntimeException("Dummy serializer."); } @Override public T read(PrimitivI input) { throw new RuntimeException("Dummy serializer."); } @Override public boolean isReference() { return true; } @Override public boolean handlesReference() { return false; } }; }
[ "public", "static", "<", "T", ">", "Serializer", "<", "T", ">", "dummySerializer", "(", ")", "{", "return", "new", "Serializer", "<", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "write", "(", "PrimitivO", "output", ",", "T", "object", ...
Serializer that throws exception for any serialization. Use for known objects.
[ "Serializer", "that", "throws", "exception", "for", "any", "serialization", ".", "Use", "for", "known", "objects", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/primitivio/PrimitivIO.java#L25-L47
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/AffineGapAlignmentScoring.java
AffineGapAlignmentScoring.getNucleotideBLASTScoring
public static AffineGapAlignmentScoring<NucleotideSequence> getNucleotideBLASTScoring(int gapOpenPenalty, int gapExtensionPenalty) { return new AffineGapAlignmentScoring<>(NucleotideSequence.ALPHABET, 5, -4, gapOpenPenalty, gapExtensionPenalty); }
java
public static AffineGapAlignmentScoring<NucleotideSequence> getNucleotideBLASTScoring(int gapOpenPenalty, int gapExtensionPenalty) { return new AffineGapAlignmentScoring<>(NucleotideSequence.ALPHABET, 5, -4, gapOpenPenalty, gapExtensionPenalty); }
[ "public", "static", "AffineGapAlignmentScoring", "<", "NucleotideSequence", ">", "getNucleotideBLASTScoring", "(", "int", "gapOpenPenalty", ",", "int", "gapExtensionPenalty", ")", "{", "return", "new", "AffineGapAlignmentScoring", "<>", "(", "NucleotideSequence", ".", "AL...
Returns Nucleotide BLAST scoring @param gapOpenPenalty penalty for opening gap to be used in system @param gapExtensionPenalty penalty for extending gap to be used in system @return Nucleotide BLAST scoring
[ "Returns", "Nucleotide", "BLAST", "scoring" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/AffineGapAlignmentScoring.java#L200-L202
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/AffineGapAlignmentScoring.java
AffineGapAlignmentScoring.getAminoAcidBLASTScoring
public static AffineGapAlignmentScoring<AminoAcidSequence> getAminoAcidBLASTScoring(BLASTMatrix matrix, int gapOpenPenalty, int gapExtensionPenalty) { return new AffineGapAlignmentScoring<>(AminoAcidSequence.ALPHABET, matrix.getMatrix(), gapOpenPenalty, gapExtensionPenalty); }
java
public static AffineGapAlignmentScoring<AminoAcidSequence> getAminoAcidBLASTScoring(BLASTMatrix matrix, int gapOpenPenalty, int gapExtensionPenalty) { return new AffineGapAlignmentScoring<>(AminoAcidSequence.ALPHABET, matrix.getMatrix(), gapOpenPenalty, gapExtensionPenalty); }
[ "public", "static", "AffineGapAlignmentScoring", "<", "AminoAcidSequence", ">", "getAminoAcidBLASTScoring", "(", "BLASTMatrix", "matrix", ",", "int", "gapOpenPenalty", ",", "int", "gapExtensionPenalty", ")", "{", "return", "new", "AffineGapAlignmentScoring", "<>", "(", ...
Returns AminoAcid BLAST scoring @param matrix BLAST substitution matrix to be used @param gapOpenPenalty penalty for opening gap to be used in system @param gapExtensionPenalty penalty for extending gap to be used in system @return AminoAcid BLAST scoring
[ "Returns", "AminoAcid", "BLAST", "scoring" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/AffineGapAlignmentScoring.java#L224-L228
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequencesUtils.java
SequencesUtils.belongsToAlphabet
public static boolean belongsToAlphabet(Alphabet<?> alphabet, String string) { for (int i = 0; i < string.length(); ++i) if (alphabet.symbolToCode(string.charAt(i)) == -1) return false; return true; }
java
public static boolean belongsToAlphabet(Alphabet<?> alphabet, String string) { for (int i = 0; i < string.length(); ++i) if (alphabet.symbolToCode(string.charAt(i)) == -1) return false; return true; }
[ "public", "static", "boolean", "belongsToAlphabet", "(", "Alphabet", "<", "?", ">", "alphabet", ",", "String", "string", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "string", ".", "length", "(", ")", ";", "++", "i", ")", "if", "(", ...
Check if a sequence contains letters only from specified alphabet. So in can be converted to corresponding type of sequence. @param alphabet alphabet @param string string to check @return {@literal true} if sequence belongs to alphabet, {@literal false} if does not
[ "Check", "if", "a", "sequence", "contains", "letters", "only", "from", "specified", "alphabet", ".", "So", "in", "can", "be", "converted", "to", "corresponding", "type", "of", "sequence", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequencesUtils.java#L39-L44
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequencesUtils.java
SequencesUtils.possibleAlphabets
public static Set<Alphabet<?>> possibleAlphabets(String string) { HashSet<Alphabet<?>> alphabets = new HashSet<>(); for (Alphabet alphabet : Alphabets.getAll()) { if (belongsToAlphabet(alphabet, string)) alphabets.add(alphabet); } return alphabets; }
java
public static Set<Alphabet<?>> possibleAlphabets(String string) { HashSet<Alphabet<?>> alphabets = new HashSet<>(); for (Alphabet alphabet : Alphabets.getAll()) { if (belongsToAlphabet(alphabet, string)) alphabets.add(alphabet); } return alphabets; }
[ "public", "static", "Set", "<", "Alphabet", "<", "?", ">", ">", "possibleAlphabets", "(", "String", "string", ")", "{", "HashSet", "<", "Alphabet", "<", "?", ">", ">", "alphabets", "=", "new", "HashSet", "<>", "(", ")", ";", "for", "(", "Alphabet", "...
Returns a set of possible alphabets for a given string. <p>Looks for alphabets registered in {@link com.milaboratory.core.sequence.Alphabets}.</p> @param string target string (sequence) @return set of possible alphabets for a given string
[ "Returns", "a", "set", "of", "possible", "alphabets", "for", "a", "given", "string", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequencesUtils.java#L54-L61
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequencesUtils.java
SequencesUtils.concatenate
public static <S extends Seq<S>> S concatenate(S... sequences) { if (sequences.length == 0) throw new IllegalArgumentException("Zero arguments"); if (sequences.length == 1) return sequences[0]; int size = 0; for (S s : sequences) size += s.size(); SeqBuilder<S> builder = sequences[0].getBuilder().ensureCapacity(size); for (S s : sequences) builder.append(s); return builder.createAndDestroy(); }
java
public static <S extends Seq<S>> S concatenate(S... sequences) { if (sequences.length == 0) throw new IllegalArgumentException("Zero arguments"); if (sequences.length == 1) return sequences[0]; int size = 0; for (S s : sequences) size += s.size(); SeqBuilder<S> builder = sequences[0].getBuilder().ensureCapacity(size); for (S s : sequences) builder.append(s); return builder.createAndDestroy(); }
[ "public", "static", "<", "S", "extends", "Seq", "<", "S", ">", ">", "S", "concatenate", "(", "S", "...", "sequences", ")", "{", "if", "(", "sequences", ".", "length", "==", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Zero arguments\"", ...
Returns a concatenation of several sequences. @param sequences array of sequences @param <S> type of sequences @return concatenation of several sequences
[ "Returns", "a", "concatenation", "of", "several", "sequences", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequencesUtils.java#L94-L111
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequencesUtils.java
SequencesUtils.convertNSequenceToBit2Array
public static Bit2Array convertNSequenceToBit2Array(NucleotideSequence seq) { if (seq.containWildcards()) throw new IllegalArgumentException("Sequences with wildcards are not supported."); Bit2Array bar = new Bit2Array(seq.size()); for (int i = 0; i < seq.size(); i++) bar.set(i, seq.codeAt(i)); return bar; }
java
public static Bit2Array convertNSequenceToBit2Array(NucleotideSequence seq) { if (seq.containWildcards()) throw new IllegalArgumentException("Sequences with wildcards are not supported."); Bit2Array bar = new Bit2Array(seq.size()); for (int i = 0; i < seq.size(); i++) bar.set(i, seq.codeAt(i)); return bar; }
[ "public", "static", "Bit2Array", "convertNSequenceToBit2Array", "(", "NucleotideSequence", "seq", ")", "{", "if", "(", "seq", ".", "containWildcards", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Sequences with wildcards are not supported.\"", ")", ...
Used to write legacy file formats. @return Bit2Array representation of nucleotide sequence
[ "Used", "to", "write", "legacy", "file", "formats", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequencesUtils.java#L144-L151
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequencesUtils.java
SequencesUtils.convertBit2ArrayToNSequence
public static NucleotideSequence convertBit2ArrayToNSequence(Bit2Array bar) { SequenceBuilder<NucleotideSequence> seq = NucleotideSequence.ALPHABET.createBuilder().ensureCapacity(bar.size()); for (int i = 0; i < bar.size(); i++) seq.append((byte) bar.get(i)); return seq.createAndDestroy(); }
java
public static NucleotideSequence convertBit2ArrayToNSequence(Bit2Array bar) { SequenceBuilder<NucleotideSequence> seq = NucleotideSequence.ALPHABET.createBuilder().ensureCapacity(bar.size()); for (int i = 0; i < bar.size(); i++) seq.append((byte) bar.get(i)); return seq.createAndDestroy(); }
[ "public", "static", "NucleotideSequence", "convertBit2ArrayToNSequence", "(", "Bit2Array", "bar", ")", "{", "SequenceBuilder", "<", "NucleotideSequence", ">", "seq", "=", "NucleotideSequence", ".", "ALPHABET", ".", "createBuilder", "(", ")", ".", "ensureCapacity", "("...
Used to read legacy file formats. @return NucleotideSequence constructed from Bit2Array
[ "Used", "to", "read", "legacy", "file", "formats", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequencesUtils.java#L158-L163
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/FileIndexBuilder.java
FileIndexBuilder.setStartingRecordNumber
public FileIndexBuilder setStartingRecordNumber(long recordNumber) { checkIfDestroyed(); if (index.size() != 1) throw new IllegalStateException("Initial record is already initialised to " + index.get(0)); startingRecordNumber = recordNumber; return this; }
java
public FileIndexBuilder setStartingRecordNumber(long recordNumber) { checkIfDestroyed(); if (index.size() != 1) throw new IllegalStateException("Initial record is already initialised to " + index.get(0)); startingRecordNumber = recordNumber; return this; }
[ "public", "FileIndexBuilder", "setStartingRecordNumber", "(", "long", "recordNumber", ")", "{", "checkIfDestroyed", "(", ")", ";", "if", "(", "index", ".", "size", "(", ")", "!=", "1", ")", "throw", "new", "IllegalStateException", "(", "\"Initial record is already...
Sets the starting record number to a specified one. @param recordNumber starting record number @return this
[ "Sets", "the", "starting", "record", "number", "to", "a", "specified", "one", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/FileIndexBuilder.java#L94-L100
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/FileIndexBuilder.java
FileIndexBuilder.putMetadata
public FileIndexBuilder putMetadata(String key, String value) { checkIfDestroyed(); metadata.put(key, value); return this; }
java
public FileIndexBuilder putMetadata(String key, String value) { checkIfDestroyed(); metadata.put(key, value); return this; }
[ "public", "FileIndexBuilder", "putMetadata", "(", "String", "key", ",", "String", "value", ")", "{", "checkIfDestroyed", "(", ")", ";", "metadata", ".", "put", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Puts metadata. @param key metadata key @param value metadata value @return this
[ "Puts", "metadata", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/FileIndexBuilder.java#L109-L113
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/FileIndexBuilder.java
FileIndexBuilder.appendNextRecord
public FileIndexBuilder appendNextRecord(long recordSize) { checkIfDestroyed(); if (recordSize < 0) throw new IllegalArgumentException("Size cannot be negative."); if (currentRecord == step) { index.add(startingByte + currentByte); currentRecord = 0; } currentByte += recordSize; ++currentRecord; return this; }
java
public FileIndexBuilder appendNextRecord(long recordSize) { checkIfDestroyed(); if (recordSize < 0) throw new IllegalArgumentException("Size cannot be negative."); if (currentRecord == step) { index.add(startingByte + currentByte); currentRecord = 0; } currentByte += recordSize; ++currentRecord; return this; }
[ "public", "FileIndexBuilder", "appendNextRecord", "(", "long", "recordSize", ")", "{", "checkIfDestroyed", "(", ")", ";", "if", "(", "recordSize", "<", "0", ")", "throw", "new", "IllegalArgumentException", "(", "\"Size cannot be negative.\"", ")", ";", "if", "(", ...
Appends next record to this index builder and returns this. @param recordSize size of record measured in bytes @return this
[ "Appends", "next", "record", "to", "this", "index", "builder", "and", "returns", "this", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/FileIndexBuilder.java#L121-L132
train
milaboratory/milib
src/main/java/com/milaboratory/core/io/util/IOUtil.java
IOUtil.computeRawVarint64Size
public static int computeRawVarint64Size(final long value) { if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; return 10; }
java
public static int computeRawVarint64Size(final long value) { if ((value & (0xffffffffffffffffL << 7)) == 0) return 1; if ((value & (0xffffffffffffffffL << 14)) == 0) return 2; if ((value & (0xffffffffffffffffL << 21)) == 0) return 3; if ((value & (0xffffffffffffffffL << 28)) == 0) return 4; if ((value & (0xffffffffffffffffL << 35)) == 0) return 5; if ((value & (0xffffffffffffffffL << 42)) == 0) return 6; if ((value & (0xffffffffffffffffL << 49)) == 0) return 7; if ((value & (0xffffffffffffffffL << 56)) == 0) return 8; if ((value & (0xffffffffffffffffL << 63)) == 0) return 9; return 10; }
[ "public", "static", "int", "computeRawVarint64Size", "(", "final", "long", "value", ")", "{", "if", "(", "(", "value", "&", "(", "0xffffffffffffffff", "L", "<<", "7", ")", ")", "==", "0", ")", "return", "1", ";", "if", "(", "(", "value", "&", "(", ...
Compute the number of bytes that would be needed to encode a varint. <p>Copied from com.google.protobuf.CodedOutputStream from Google's protobuf library.</p>
[ "Compute", "the", "number", "of", "bytes", "that", "would", "be", "needed", "to", "encode", "a", "varint", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/io/util/IOUtil.java#L132-L143
train
milaboratory/milib
src/main/java/com/milaboratory/util/LightFileDescriptor.java
LightFileDescriptor.checkModified
public boolean checkModified(LightFileDescriptor other) { if (isAlwaysModified() || other.isAlwaysModified()) return true; if (!name.equals(other.name)) return true; if (!(hasChecksum() && other.hasChecksum()) && !(hasModificationDate() && other.hasModificationDate())) // No intersecting characteristics, cant compare => file is modified return true; if (hasChecksum() && other.hasChecksum() && !Arrays.equals(checksum, other.checksum)) return true; if (hasModificationDate() && other.hasModificationDate() && !lastModified.equals(other.lastModified)) return true; return false; }
java
public boolean checkModified(LightFileDescriptor other) { if (isAlwaysModified() || other.isAlwaysModified()) return true; if (!name.equals(other.name)) return true; if (!(hasChecksum() && other.hasChecksum()) && !(hasModificationDate() && other.hasModificationDate())) // No intersecting characteristics, cant compare => file is modified return true; if (hasChecksum() && other.hasChecksum() && !Arrays.equals(checksum, other.checksum)) return true; if (hasModificationDate() && other.hasModificationDate() && !lastModified.equals(other.lastModified)) return true; return false; }
[ "public", "boolean", "checkModified", "(", "LightFileDescriptor", "other", ")", "{", "if", "(", "isAlwaysModified", "(", ")", "||", "other", ".", "isAlwaysModified", "(", ")", ")", "return", "true", ";", "if", "(", "!", "name", ".", "equals", "(", "other",...
Returns true if file modified
[ "Returns", "true", "if", "file", "modified" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/util/LightFileDescriptor.java#L86-L104
train
milaboratory/milib
src/main/java/com/milaboratory/util/LightFileDescriptor.java
LightFileDescriptor.toBase64
public String toBase64() { return name + (checksum == null ? "null" : Base64.getDecoder().decode(checksum)) + (lastModified == null ? "null" : lastModified); }
java
public String toBase64() { return name + (checksum == null ? "null" : Base64.getDecoder().decode(checksum)) + (lastModified == null ? "null" : lastModified); }
[ "public", "String", "toBase64", "(", ")", "{", "return", "name", "+", "(", "checksum", "==", "null", "?", "\"null\"", ":", "Base64", ".", "getDecoder", "(", ")", ".", "decode", "(", "checksum", ")", ")", "+", "(", "lastModified", "==", "null", "?", "...
A string representation of this.
[ "A", "string", "representation", "of", "this", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/util/LightFileDescriptor.java#L200-L204
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequenceQuality.java
SequenceQuality.minValue
public byte minValue() { if (data.length == 0) return 0; byte min = Byte.MAX_VALUE; for (byte b : data) if (b < min) min = b; return min; }
java
public byte minValue() { if (data.length == 0) return 0; byte min = Byte.MAX_VALUE; for (byte b : data) if (b < min) min = b; return min; }
[ "public", "byte", "minValue", "(", ")", "{", "if", "(", "data", ".", "length", "==", "0", ")", "return", "0", ";", "byte", "min", "=", "Byte", ".", "MAX_VALUE", ";", "for", "(", "byte", "b", ":", "data", ")", "if", "(", "b", "<", "min", ")", ...
Returns the worst sequence quality value @return worst sequence quality value
[ "Returns", "the", "worst", "sequence", "quality", "value" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceQuality.java#L149-L158
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequenceQuality.java
SequenceQuality.meanValue
public byte meanValue() { if (data.length == 0) return 0; int sum = 0; for (byte b : data) sum += b; return (byte) (sum / data.length); }
java
public byte meanValue() { if (data.length == 0) return 0; int sum = 0; for (byte b : data) sum += b; return (byte) (sum / data.length); }
[ "public", "byte", "meanValue", "(", ")", "{", "if", "(", "data", ".", "length", "==", "0", ")", "return", "0", ";", "int", "sum", "=", "0", ";", "for", "(", "byte", "b", ":", "data", ")", "sum", "+=", ";", "return", "(", "byte", ")", "(", "su...
Returns average sequence quality value @return average sequence quality value
[ "Returns", "average", "sequence", "quality", "value" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceQuality.java#L165-L173
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequenceQuality.java
SequenceQuality.getRange
@Override public SequenceQuality getRange(Range range) { byte[] rdata = Arrays.copyOfRange(data, range.getLower(), range.getUpper()); if (range.isReverse()) ArraysUtils.reverse(rdata); return new SequenceQuality(rdata, true); }
java
@Override public SequenceQuality getRange(Range range) { byte[] rdata = Arrays.copyOfRange(data, range.getLower(), range.getUpper()); if (range.isReverse()) ArraysUtils.reverse(rdata); return new SequenceQuality(rdata, true); }
[ "@", "Override", "public", "SequenceQuality", "getRange", "(", "Range", "range", ")", "{", "byte", "[", "]", "rdata", "=", "Arrays", ".", "copyOfRange", "(", "data", ",", "range", ".", "getLower", "(", ")", ",", "range", ".", "getUpper", "(", ")", ")",...
Returns substring of current quality scores line. @param range range @return substring of current quality scores line
[ "Returns", "substring", "of", "current", "quality", "scores", "line", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceQuality.java#L202-L208
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequenceQuality.java
SequenceQuality.encodeTo
public void encodeTo(QualityFormat format, byte[] buffer, int offset) { byte vo = format.getOffset(); for (int i = 0; i < data.length; ++i) buffer[offset++] = (byte) (data[i] + vo); } /** * Encodes current quality line with given offset. Common values for offset are 33 and 64. * * @param offset offset * @return bytes encoded quality values */ public byte[] encode(int offset) { if (offset < 0 || offset > 70) throw new IllegalArgumentException(); byte[] copy = new byte[data.length]; for (int i = copy.length - 1; i >= 0; --i) copy[i] += data[i] + offset; return copy; }
java
public void encodeTo(QualityFormat format, byte[] buffer, int offset) { byte vo = format.getOffset(); for (int i = 0; i < data.length; ++i) buffer[offset++] = (byte) (data[i] + vo); } /** * Encodes current quality line with given offset. Common values for offset are 33 and 64. * * @param offset offset * @return bytes encoded quality values */ public byte[] encode(int offset) { if (offset < 0 || offset > 70) throw new IllegalArgumentException(); byte[] copy = new byte[data.length]; for (int i = copy.length - 1; i >= 0; --i) copy[i] += data[i] + offset; return copy; }
[ "public", "void", "encodeTo", "(", "QualityFormat", "format", ",", "byte", "[", "]", "buffer", ",", "int", "offset", ")", "{", "byte", "vo", "=", "format", ".", "getOffset", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ...
Encodes current quality line with given offset. Common values for offset are 33 and 64. @param offset offset @return bytes encoded quality values
[ "Encodes", "current", "quality", "line", "with", "given", "offset", ".", "Common", "values", "for", "offset", "are", "33", "and", "64", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceQuality.java#L246-L266
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/SequenceQuality.java
SequenceQuality.getUniformQuality
public static SequenceQuality getUniformQuality(byte qualityValue, int length) { byte[] data = new byte[length]; Arrays.fill(data, qualityValue); return new SequenceQuality(data, true); }
java
public static SequenceQuality getUniformQuality(byte qualityValue, int length) { byte[] data = new byte[length]; Arrays.fill(data, qualityValue); return new SequenceQuality(data, true); }
[ "public", "static", "SequenceQuality", "getUniformQuality", "(", "byte", "qualityValue", ",", "int", "length", ")", "{", "byte", "[", "]", "data", "=", "new", "byte", "[", "length", "]", ";", "Arrays", ".", "fill", "(", "data", ",", "qualityValue", ")", ...
Creates a phred sequence quality containing only given values of quality. @param qualityValue value to fill the quality values with @param length size of quality string
[ "Creates", "a", "phred", "sequence", "quality", "containing", "only", "given", "values", "of", "quality", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/SequenceQuality.java#L312-L316
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/BandedLinearAligner.java
BandedLinearAligner.alignLeftAdded
public static Alignment<NucleotideSequence> alignLeftAdded(LinearGapAlignmentScoring scoring, NucleotideSequence seq1, NucleotideSequence seq2, int offset1, int length1, int addedNucleotides1, int offset2, int length2, int addedNucleotides2, int width) { try { MutationsBuilder<NucleotideSequence> mutations = new MutationsBuilder<>(NucleotideSequence.ALPHABET); BandedSemiLocalResult result = alignLeftAdded0(scoring, seq1, seq2, offset1, length1, addedNucleotides1, offset2, length2, addedNucleotides2, width, mutations, AlignmentCache.get()); return new Alignment<>(seq1, mutations.createAndDestroy(), new Range(result.sequence1Stop, offset1 + length1), new Range(result.sequence2Stop, offset2 + length2), result.score); } finally { AlignmentCache.release(); } }
java
public static Alignment<NucleotideSequence> alignLeftAdded(LinearGapAlignmentScoring scoring, NucleotideSequence seq1, NucleotideSequence seq2, int offset1, int length1, int addedNucleotides1, int offset2, int length2, int addedNucleotides2, int width) { try { MutationsBuilder<NucleotideSequence> mutations = new MutationsBuilder<>(NucleotideSequence.ALPHABET); BandedSemiLocalResult result = alignLeftAdded0(scoring, seq1, seq2, offset1, length1, addedNucleotides1, offset2, length2, addedNucleotides2, width, mutations, AlignmentCache.get()); return new Alignment<>(seq1, mutations.createAndDestroy(), new Range(result.sequence1Stop, offset1 + length1), new Range(result.sequence2Stop, offset2 + length2), result.score); } finally { AlignmentCache.release(); } }
[ "public", "static", "Alignment", "<", "NucleotideSequence", ">", "alignLeftAdded", "(", "LinearGapAlignmentScoring", "scoring", ",", "NucleotideSequence", "seq1", ",", "NucleotideSequence", "seq2", ",", "int", "offset1", ",", "int", "length1", ",", "int", "addedNucleo...
Semi-semi-global alignment with artificially added letters. <p>Alignment where second sequence is aligned to the left part of first sequence.</p> <p>Whole second sequence must be highly similar to the first sequence, except last {@code width} letters, which are to be checked whether they can improve alignment or not.</p> @param scoring scoring system @param seq1 first sequence @param seq2 second sequence @param offset1 offset in first sequence @param length1 length of first sequence's part to be aligned @param addedNucleotides1 number of artificially added letters to the first sequence @param offset2 offset in second sequence @param length2 length of second sequence's part to be aligned @param addedNucleotides2 number of artificially added letters to the second sequence @param width width of banded alignment matrix. In other terms max allowed number of indels
[ "Semi", "-", "semi", "-", "global", "alignment", "with", "artificially", "added", "letters", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/BandedLinearAligner.java#L596-L610
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/kaligner2/KAligner2.java
KAligner2.addReference
public int addReference(NucleotideSequence sequence) { if (sequence.containWildcards()) throw new IllegalArgumentException("Reference sequences with wildcards not supported."); int id = mapper.addReference(sequence); assert sequences.size() == id; sequences.add(sequence); return id; }
java
public int addReference(NucleotideSequence sequence) { if (sequence.containWildcards()) throw new IllegalArgumentException("Reference sequences with wildcards not supported."); int id = mapper.addReference(sequence); assert sequences.size() == id; sequences.add(sequence); return id; }
[ "public", "int", "addReference", "(", "NucleotideSequence", "sequence", ")", "{", "if", "(", "sequence", ".", "containWildcards", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Reference sequences with wildcards not supported.\"", ")", ";", "int", ...
Adds new reference sequence to the base of this mapper and returns index assigned to it. @param sequence sequence @return index assigned to the sequence
[ "Adds", "new", "reference", "sequence", "to", "the", "base", "of", "this", "mapper", "and", "returns", "index", "assigned", "to", "it", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/kaligner2/KAligner2.java#L63-L70
train
milaboratory/milib
src/main/java/com/milaboratory/core/motif/Motif.java
Motif.or
public Motif<S> or(Motif<S> other) { if (other.size != size) throw new IllegalArgumentException("Supports only motifs with the same size as this."); BitArray result = data.clone(); result.or(other.data); return new Motif<>(alphabet, size, result); }
java
public Motif<S> or(Motif<S> other) { if (other.size != size) throw new IllegalArgumentException("Supports only motifs with the same size as this."); BitArray result = data.clone(); result.or(other.data); return new Motif<>(alphabet, size, result); }
[ "public", "Motif", "<", "S", ">", "or", "(", "Motif", "<", "S", ">", "other", ")", "{", "if", "(", "other", ".", "size", "!=", "size", ")", "throw", "new", "IllegalArgumentException", "(", "\"Supports only motifs with the same size as this.\"", ")", ";", "Bi...
Returns per-position or of two motifs. <p>e.g. ATGC or TTCC = WTSC</p> @param other @return
[ "Returns", "per", "-", "position", "or", "of", "two", "motifs", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/motif/Motif.java#L74-L82
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/BandedAligner.java
BandedAligner.alignGlobal
public static Alignment<NucleotideSequence> alignGlobal(final AlignmentScoring<NucleotideSequence> scoring, final NucleotideSequence seq1, final NucleotideSequence seq2, final int offset1, final int length1, final int offset2, final int length2, final int width) { if (scoring instanceof AffineGapAlignmentScoring) return BandedAffineAligner.align((AffineGapAlignmentScoring<NucleotideSequence>) scoring, seq1, seq2, offset1, length1, offset2, length2, width); else return BandedLinearAligner.align((LinearGapAlignmentScoring<NucleotideSequence>) scoring, seq1, seq2, offset1, length1, offset2, length2, width); }
java
public static Alignment<NucleotideSequence> alignGlobal(final AlignmentScoring<NucleotideSequence> scoring, final NucleotideSequence seq1, final NucleotideSequence seq2, final int offset1, final int length1, final int offset2, final int length2, final int width) { if (scoring instanceof AffineGapAlignmentScoring) return BandedAffineAligner.align((AffineGapAlignmentScoring<NucleotideSequence>) scoring, seq1, seq2, offset1, length1, offset2, length2, width); else return BandedLinearAligner.align((LinearGapAlignmentScoring<NucleotideSequence>) scoring, seq1, seq2, offset1, length1, offset2, length2, width); }
[ "public", "static", "Alignment", "<", "NucleotideSequence", ">", "alignGlobal", "(", "final", "AlignmentScoring", "<", "NucleotideSequence", ">", "scoring", ",", "final", "NucleotideSequence", "seq1", ",", "final", "NucleotideSequence", "seq2", ",", "final", "int", ...
Classical Banded Alignment. Both sequences must be highly similar. Align 2 sequence completely (i.e. while first sequence will be aligned against whole second sequence). @param scoring scoring system @param seq1 first sequence @param seq2 second sequence @param offset1 offset in first sequence @param length1 length of first sequence's part to be aligned @param offset2 offset in second sequence @param length2 length of second sequence's part to be aligned @param width width of banded alignment matrix. In other terms max allowed number of indels
[ "Classical", "Banded", "Alignment", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/BandedAligner.java#L27-L36
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/Aligner.java
Aligner.alignGlobal
public static <S extends Sequence<S>> Alignment<S> alignGlobal(AlignmentScoring<S> alignmentScoring, S seq1, S seq2) { if (alignmentScoring instanceof AffineGapAlignmentScoring) return alignGlobalAffine((AffineGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); if (alignmentScoring instanceof LinearGapAlignmentScoring) return alignGlobalLinear((LinearGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); throw new RuntimeException("Unknown scoring type."); }
java
public static <S extends Sequence<S>> Alignment<S> alignGlobal(AlignmentScoring<S> alignmentScoring, S seq1, S seq2) { if (alignmentScoring instanceof AffineGapAlignmentScoring) return alignGlobalAffine((AffineGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); if (alignmentScoring instanceof LinearGapAlignmentScoring) return alignGlobalLinear((LinearGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); throw new RuntimeException("Unknown scoring type."); }
[ "public", "static", "<", "S", "extends", "Sequence", "<", "S", ">", ">", "Alignment", "<", "S", ">", "alignGlobal", "(", "AlignmentScoring", "<", "S", ">", "alignmentScoring", ",", "S", "seq1", ",", "S", "seq2", ")", "{", "if", "(", "alignmentScoring", ...
Performs global alignment @param alignmentScoring scoring system @param seq1 first sequence @param seq2 second sequence @return array of mutations
[ "Performs", "global", "alignment" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/Aligner.java#L91-L98
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/Aligner.java
Aligner.alignLocal
public static <S extends Sequence<S>> Alignment<S> alignLocal(AlignmentScoring<S> alignmentScoring, S seq1, S seq2) { if (alignmentScoring instanceof AffineGapAlignmentScoring) return alignLocalAffine((AffineGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); if (alignmentScoring instanceof LinearGapAlignmentScoring) return alignLocalLinear((LinearGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); throw new RuntimeException("Unknown scoring type."); }
java
public static <S extends Sequence<S>> Alignment<S> alignLocal(AlignmentScoring<S> alignmentScoring, S seq1, S seq2) { if (alignmentScoring instanceof AffineGapAlignmentScoring) return alignLocalAffine((AffineGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); if (alignmentScoring instanceof LinearGapAlignmentScoring) return alignLocalLinear((LinearGapAlignmentScoring<S>) alignmentScoring, seq1, seq2); throw new RuntimeException("Unknown scoring type."); }
[ "public", "static", "<", "S", "extends", "Sequence", "<", "S", ">", ">", "Alignment", "<", "S", ">", "alignLocal", "(", "AlignmentScoring", "<", "S", ">", "alignmentScoring", ",", "S", "seq1", ",", "S", "seq2", ")", "{", "if", "(", "alignmentScoring", ...
Performs local alignment @param alignmentScoring scoring system @param seq1 first sequence @param seq2 second sequence @return result of alignment with information about alignment positions in both sequences and array of mutations
[ "Performs", "local", "alignment" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/Aligner.java#L331-L338
train
milaboratory/milib
src/main/java/com/milaboratory/core/clustering/Cluster.java
Cluster.processAllChildren
public void processAllChildren(TObjectProcedure<Cluster<T>> procedure) { if (children == null) return; for (Cluster<T> child : children) { procedure.execute(child); child.processAllChildren(procedure); } }
java
public void processAllChildren(TObjectProcedure<Cluster<T>> procedure) { if (children == null) return; for (Cluster<T> child : children) { procedure.execute(child); child.processAllChildren(procedure); } }
[ "public", "void", "processAllChildren", "(", "TObjectProcedure", "<", "Cluster", "<", "T", ">", ">", "procedure", ")", "{", "if", "(", "children", "==", "null", ")", "return", ";", "for", "(", "Cluster", "<", "T", ">", "child", ":", "children", ")", "{...
do not process this cluster
[ "do", "not", "process", "this", "cluster" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/clustering/Cluster.java#L73-L80
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/Alphabet.java
Alphabet.getEmptySequence
public S getEmptySequence() { if (empty == null) synchronized (this) { if (empty == null) empty = createBuilder().createAndDestroy(); } return empty; }
java
public S getEmptySequence() { if (empty == null) synchronized (this) { if (empty == null) empty = createBuilder().createAndDestroy(); } return empty; }
[ "public", "S", "getEmptySequence", "(", ")", "{", "if", "(", "empty", "==", "null", ")", "synchronized", "(", "this", ")", "{", "if", "(", "empty", "==", "null", ")", "empty", "=", "createBuilder", "(", ")", ".", "createAndDestroy", "(", ")", ";", "}...
Returns empty sequence singleton @return empty sequence singleton
[ "Returns", "empty", "sequence", "singleton" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/Alphabet.java#L280-L287
train
milaboratory/milib
src/main/java/com/milaboratory/core/sequence/Alphabet.java
Alphabet.parse
public final S parse(String string) { SequenceBuilder<S> builder = createBuilder().ensureCapacity(string.length()); for (int i = 0; i < string.length(); ++i) { byte code = symbolToCode(string.charAt(i)); if (code == -1) throw new IllegalArgumentException("Letter \'" + string.charAt(i) + "\' is not defined in \'" + toString() + "\'."); builder.append(code); } return builder.createAndDestroy(); }
java
public final S parse(String string) { SequenceBuilder<S> builder = createBuilder().ensureCapacity(string.length()); for (int i = 0; i < string.length(); ++i) { byte code = symbolToCode(string.charAt(i)); if (code == -1) throw new IllegalArgumentException("Letter \'" + string.charAt(i) + "\' is not defined in \'" + toString() + "\'."); builder.append(code); } return builder.createAndDestroy(); }
[ "public", "final", "S", "parse", "(", "String", "string", ")", "{", "SequenceBuilder", "<", "S", ">", "builder", "=", "createBuilder", "(", ")", ".", "ensureCapacity", "(", "string", ".", "length", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0"...
Parses string representation of sequence. @param string string representation of sequence @return sequence
[ "Parses", "string", "representation", "of", "sequence", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/sequence/Alphabet.java#L317-L326
train
milaboratory/milib
src/main/java/com/milaboratory/cli/PipelineConfiguration.java
PipelineConfiguration.compatibleWith
public boolean compatibleWith(PipelineConfiguration oth) { if (oth == null) return false; if (pipelineSteps.length != oth.pipelineSteps.length) return false; for (int i = 0; i < pipelineSteps.length; ++i) if (!pipelineSteps[i].compatibleWith(oth.pipelineSteps[i])) return false; return true; }
java
public boolean compatibleWith(PipelineConfiguration oth) { if (oth == null) return false; if (pipelineSteps.length != oth.pipelineSteps.length) return false; for (int i = 0; i < pipelineSteps.length; ++i) if (!pipelineSteps[i].compatibleWith(oth.pipelineSteps[i])) return false; return true; }
[ "public", "boolean", "compatibleWith", "(", "PipelineConfiguration", "oth", ")", "{", "if", "(", "oth", "==", "null", ")", "return", "false", ";", "if", "(", "pipelineSteps", ".", "length", "!=", "oth", ".", "pipelineSteps", ".", "length", ")", "return", "...
Whether configurations are fully compatible
[ "Whether", "configurations", "are", "fully", "compatible" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/cli/PipelineConfiguration.java#L54-L63
train
milaboratory/milib
src/main/java/com/milaboratory/cli/PipelineConfiguration.java
PipelineConfiguration.appendStep
public static PipelineConfiguration appendStep(PipelineConfiguration history, List<String> inputFiles, ActionConfiguration configuration, AppVersionInfo versionInfo) { LightFileDescriptor[] inputDescriptors = inputFiles .stream() .map(f -> LightFileDescriptor.calculate(Paths.get(f))) .toArray(LightFileDescriptor[]::new); return new PipelineConfiguration( Stream.concat( Stream.of(history.pipelineSteps), Stream.of(new PipelineStep(versionInfo, inputDescriptors, configuration)) ).toArray(PipelineStep[]::new)); }
java
public static PipelineConfiguration appendStep(PipelineConfiguration history, List<String> inputFiles, ActionConfiguration configuration, AppVersionInfo versionInfo) { LightFileDescriptor[] inputDescriptors = inputFiles .stream() .map(f -> LightFileDescriptor.calculate(Paths.get(f))) .toArray(LightFileDescriptor[]::new); return new PipelineConfiguration( Stream.concat( Stream.of(history.pipelineSteps), Stream.of(new PipelineStep(versionInfo, inputDescriptors, configuration)) ).toArray(PipelineStep[]::new)); }
[ "public", "static", "PipelineConfiguration", "appendStep", "(", "PipelineConfiguration", "history", ",", "List", "<", "String", ">", "inputFiles", ",", "ActionConfiguration", "configuration", ",", "AppVersionInfo", "versionInfo", ")", "{", "LightFileDescriptor", "[", "]...
Appends a new pipeline step
[ "Appends", "a", "new", "pipeline", "step" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/cli/PipelineConfiguration.java#L79-L95
train
milaboratory/milib
src/main/java/com/milaboratory/cli/PipelineConfiguration.java
PipelineConfiguration.mkInitial
public static PipelineConfiguration mkInitial(List<String> inputFiles, ActionConfiguration configuration, AppVersionInfo versionInfo) { LightFileDescriptor[] inputDescriptors = inputFiles.stream() .map(f -> LightFileDescriptor.calculate(Paths.get(f))).toArray(LightFileDescriptor[]::new); return new PipelineConfiguration( new PipelineStep[] { new PipelineStep(versionInfo, inputDescriptors, configuration) }); }
java
public static PipelineConfiguration mkInitial(List<String> inputFiles, ActionConfiguration configuration, AppVersionInfo versionInfo) { LightFileDescriptor[] inputDescriptors = inputFiles.stream() .map(f -> LightFileDescriptor.calculate(Paths.get(f))).toArray(LightFileDescriptor[]::new); return new PipelineConfiguration( new PipelineStep[] { new PipelineStep(versionInfo, inputDescriptors, configuration) }); }
[ "public", "static", "PipelineConfiguration", "mkInitial", "(", "List", "<", "String", ">", "inputFiles", ",", "ActionConfiguration", "configuration", ",", "AppVersionInfo", "versionInfo", ")", "{", "LightFileDescriptor", "[", "]", "inputDescriptors", "=", "inputFiles", ...
Creates initial history
[ "Creates", "initial", "history" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/cli/PipelineConfiguration.java#L98-L106
train
milaboratory/milib
src/main/java/com/milaboratory/core/alignment/AlignmentUtils.java
AlignmentUtils.shiftIndelsAtHomopolymers
public static <S extends Sequence<S>> Alignment<S> shiftIndelsAtHomopolymers(Alignment<S> alignment) { return new Alignment<>(alignment.sequence1, MutationsUtil.shiftIndelsAtHomopolymers(alignment.sequence1, alignment.sequence1Range.getFrom(), alignment.mutations), alignment.sequence1Range, alignment.sequence2Range, alignment.score); }
java
public static <S extends Sequence<S>> Alignment<S> shiftIndelsAtHomopolymers(Alignment<S> alignment) { return new Alignment<>(alignment.sequence1, MutationsUtil.shiftIndelsAtHomopolymers(alignment.sequence1, alignment.sequence1Range.getFrom(), alignment.mutations), alignment.sequence1Range, alignment.sequence2Range, alignment.score); }
[ "public", "static", "<", "S", "extends", "Sequence", "<", "S", ">", ">", "Alignment", "<", "S", ">", "shiftIndelsAtHomopolymers", "(", "Alignment", "<", "S", ">", "alignment", ")", "{", "return", "new", "Alignment", "<>", "(", "alignment", ".", "sequence1"...
Shifts indels to the left at homopolymer regions
[ "Shifts", "indels", "to", "the", "left", "at", "homopolymer", "regions" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/alignment/AlignmentUtils.java#L164-L168
train
milaboratory/milib
src/main/java/com/milaboratory/core/mutations/MutationsUtil.java
MutationsUtil.btopDecode
public static int[] btopDecode(String alignment, Alphabet alphabet) { Matcher matcher = btopPattern.matcher(alignment); IntArrayList mutations = new IntArrayList(); int sPosition = 0; while (matcher.find()) { String g = matcher.group(); if (isPositiveInteger(g)) sPosition += Integer.parseInt(g); else if (g.charAt(0) == '-') { mutations.add(createDeletion(sPosition, alphabet.symbolToCodeWithException(g.charAt(1)))); ++sPosition; } else if (g.charAt(1) == '-') mutations.add(createInsertion(sPosition, alphabet.symbolToCodeWithException(g.charAt(0)))); else { mutations.add(createSubstitution(sPosition, alphabet.symbolToCodeWithException(g.charAt(1)), alphabet.symbolToCodeWithException(g.charAt(0)))); ++sPosition; } } return mutations.toArray(); }
java
public static int[] btopDecode(String alignment, Alphabet alphabet) { Matcher matcher = btopPattern.matcher(alignment); IntArrayList mutations = new IntArrayList(); int sPosition = 0; while (matcher.find()) { String g = matcher.group(); if (isPositiveInteger(g)) sPosition += Integer.parseInt(g); else if (g.charAt(0) == '-') { mutations.add(createDeletion(sPosition, alphabet.symbolToCodeWithException(g.charAt(1)))); ++sPosition; } else if (g.charAt(1) == '-') mutations.add(createInsertion(sPosition, alphabet.symbolToCodeWithException(g.charAt(0)))); else { mutations.add(createSubstitution(sPosition, alphabet.symbolToCodeWithException(g.charAt(1)), alphabet.symbolToCodeWithException(g.charAt(0)))); ++sPosition; } } return mutations.toArray(); }
[ "public", "static", "int", "[", "]", "btopDecode", "(", "String", "alignment", ",", "Alphabet", "alphabet", ")", "{", "Matcher", "matcher", "=", "btopPattern", ".", "matcher", "(", "alignment", ")", ";", "IntArrayList", "mutations", "=", "new", "IntArrayList",...
Decodes btop-encoded mutations. @param alignment btop-encoded mutations @return MiLib mutations
[ "Decodes", "btop", "-", "encoded", "mutations", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/mutations/MutationsUtil.java#L339-L358
train
milaboratory/milib
src/main/java/com/milaboratory/core/mutations/MutationsUtil.java
MutationsUtil.nt2aaDetailed
public static MutationNt2AADescriptor[] nt2aaDetailed(NucleotideSequence seq1, Mutations<NucleotideSequence> mutations, TranslationParameters translationParameters, int maxShiftedTriplets) { MutationsWitMapping mutationsWitMapping = nt2aaWithMapping(seq1, mutations, translationParameters, maxShiftedTriplets); int[] individualMutations = nt2IndividualAA(seq1, mutations, translationParameters); MutationNt2AADescriptor[] result = new MutationNt2AADescriptor[mutations.size()]; for (int i = 0; i < mutations.size(); i++) { result[i] = new MutationNt2AADescriptor(mutations.getMutation(i), individualMutations[i], mutationsWitMapping.mapping[i] == -1 ? NON_MUTATION : mutationsWitMapping.mutations.getMutation(mutationsWitMapping.mapping[i])); } return result; }
java
public static MutationNt2AADescriptor[] nt2aaDetailed(NucleotideSequence seq1, Mutations<NucleotideSequence> mutations, TranslationParameters translationParameters, int maxShiftedTriplets) { MutationsWitMapping mutationsWitMapping = nt2aaWithMapping(seq1, mutations, translationParameters, maxShiftedTriplets); int[] individualMutations = nt2IndividualAA(seq1, mutations, translationParameters); MutationNt2AADescriptor[] result = new MutationNt2AADescriptor[mutations.size()]; for (int i = 0; i < mutations.size(); i++) { result[i] = new MutationNt2AADescriptor(mutations.getMutation(i), individualMutations[i], mutationsWitMapping.mapping[i] == -1 ? NON_MUTATION : mutationsWitMapping.mutations.getMutation(mutationsWitMapping.mapping[i])); } return result; }
[ "public", "static", "MutationNt2AADescriptor", "[", "]", "nt2aaDetailed", "(", "NucleotideSequence", "seq1", ",", "Mutations", "<", "NucleotideSequence", ">", "mutations", ",", "TranslationParameters", "translationParameters", ",", "int", "maxShiftedTriplets", ")", "{", ...
Performs a comprehensive translation of mutations present in a nucleotide sequence to effective mutations in corresponding amino acid sequence. <p>The resulting array contains:</p> <ul> <li>the original nucleotide mutation</li> <li>"individual" amino acid mutation, i.e. an expected amino acid mutation given no other mutations have occurred</li> <li>"cumulative" amino acid mutation, i.e. the observed amino acid mutation combining effect from all other nucleotide mutations</li> </ul> @param seq1 the reference nucleotide sequence @param mutations nucleotide mutations in the reference nucleotide sequence @param translationParameters translation parameters @param maxShiftedTriplets max number of shifted triplets for computing the cumulative effect from indels @return an array of nucleotide mutations with their amino acid translations
[ "Performs", "a", "comprehensive", "translation", "of", "mutations", "present", "in", "a", "nucleotide", "sequence", "to", "effective", "mutations", "in", "corresponding", "amino", "acid", "sequence", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/mutations/MutationsUtil.java#L517-L529
train
milaboratory/milib
src/main/java/com/milaboratory/core/Range.java
Range.convertPointToRelativePosition
public int convertPointToRelativePosition(int absolutePosition) { if (absolutePosition < lower || absolutePosition >= upper) throw new IllegalArgumentException("Position outside this range (" + absolutePosition + ")."); if (reversed) return upper - 1 - absolutePosition; else return absolutePosition - lower; }
java
public int convertPointToRelativePosition(int absolutePosition) { if (absolutePosition < lower || absolutePosition >= upper) throw new IllegalArgumentException("Position outside this range (" + absolutePosition + ")."); if (reversed) return upper - 1 - absolutePosition; else return absolutePosition - lower; }
[ "public", "int", "convertPointToRelativePosition", "(", "int", "absolutePosition", ")", "{", "if", "(", "absolutePosition", "<", "lower", "||", "absolutePosition", ">=", "upper", ")", "throw", "new", "IllegalArgumentException", "(", "\"Position outside this range (\"", ...
Returns relative point position inside this range. @param absolutePosition absolute point position (in the same coordinates as this range boundaries) @return relative point position inside this range
[ "Returns", "relative", "point", "position", "inside", "this", "range", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/Range.java#L284-L292
train
milaboratory/milib
src/main/java/com/milaboratory/core/Range.java
Range.convertBoundaryToRelativePosition
public int convertBoundaryToRelativePosition(int absolutePosition) { if (absolutePosition < lower || absolutePosition > upper) throw new IllegalArgumentException("Position outside this range (" + absolutePosition + ") this=" + this + "."); if (reversed) return upper - absolutePosition; else return absolutePosition - lower; }
java
public int convertBoundaryToRelativePosition(int absolutePosition) { if (absolutePosition < lower || absolutePosition > upper) throw new IllegalArgumentException("Position outside this range (" + absolutePosition + ") this=" + this + "."); if (reversed) return upper - absolutePosition; else return absolutePosition - lower; }
[ "public", "int", "convertBoundaryToRelativePosition", "(", "int", "absolutePosition", ")", "{", "if", "(", "absolutePosition", "<", "lower", "||", "absolutePosition", ">", "upper", ")", "throw", "new", "IllegalArgumentException", "(", "\"Position outside this range (\"", ...
Returns relative boundary position inside this range. @param absolutePosition absolute boundary position (in the same coordinates as this range boundaries) @return relative boundary position inside this range
[ "Returns", "relative", "boundary", "position", "inside", "this", "range", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/Range.java#L300-L308
train
milaboratory/milib
src/main/java/com/milaboratory/core/Range.java
Range.without
@SuppressWarnings("unchecked") public List<Range> without(Range range) { if (!intersectsWith(range)) return Collections.singletonList(this); if (upper <= range.upper) return range.lower <= lower ? Collections.EMPTY_LIST : Collections.singletonList(new Range(lower, range.lower, reversed)); if (range.lower <= lower) return Collections.singletonList(new Range(range.upper, upper, reversed)); return Arrays.asList(new Range(lower, range.lower, reversed), new Range(range.upper, upper, reversed)); }
java
@SuppressWarnings("unchecked") public List<Range> without(Range range) { if (!intersectsWith(range)) return Collections.singletonList(this); if (upper <= range.upper) return range.lower <= lower ? Collections.EMPTY_LIST : Collections.singletonList(new Range(lower, range.lower, reversed)); if (range.lower <= lower) return Collections.singletonList(new Range(range.upper, upper, reversed)); return Arrays.asList(new Range(lower, range.lower, reversed), new Range(range.upper, upper, reversed)); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "List", "<", "Range", ">", "without", "(", "Range", "range", ")", "{", "if", "(", "!", "intersectsWith", "(", "range", ")", ")", "return", "Collections", ".", "singletonList", "(", "this", ")", ...
Subtract provided range and return list of ranges contained in current range and not intersecting with other range. @param range range to subtract @return list of ranges contained in current range and not intersecting with other range
[ "Subtract", "provided", "range", "and", "return", "list", "of", "ranges", "contained", "in", "current", "range", "and", "not", "intersecting", "with", "other", "range", "." ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/Range.java#L317-L329
train
milaboratory/milib
src/main/java/com/milaboratory/core/Range.java
Range.convertPointToAbsolutePosition
public int convertPointToAbsolutePosition(int relativePosition) { if (relativePosition < 0 || relativePosition >= length()) throw new IllegalArgumentException("Relative position outside this range (" + relativePosition + ")."); if (reversed) return upper - 1 - relativePosition; else return relativePosition + lower; }
java
public int convertPointToAbsolutePosition(int relativePosition) { if (relativePosition < 0 || relativePosition >= length()) throw new IllegalArgumentException("Relative position outside this range (" + relativePosition + ")."); if (reversed) return upper - 1 - relativePosition; else return relativePosition + lower; }
[ "public", "int", "convertPointToAbsolutePosition", "(", "int", "relativePosition", ")", "{", "if", "(", "relativePosition", "<", "0", "||", "relativePosition", ">=", "length", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Relative position outside...
Converts relative point position to absolute position @param relativePosition relative point position @return absolute point position
[ "Converts", "relative", "point", "position", "to", "absolute", "position" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/Range.java#L363-L371
train
milaboratory/milib
src/main/java/com/milaboratory/core/Range.java
Range.convertBoundaryToAbsolutePosition
public int convertBoundaryToAbsolutePosition(int relativePosition) { if (relativePosition < 0 || relativePosition > length()) throw new IllegalArgumentException("Relative position outside this range (" + relativePosition + ")."); if (reversed) return upper - relativePosition; else return relativePosition + lower; }
java
public int convertBoundaryToAbsolutePosition(int relativePosition) { if (relativePosition < 0 || relativePosition > length()) throw new IllegalArgumentException("Relative position outside this range (" + relativePosition + ")."); if (reversed) return upper - relativePosition; else return relativePosition + lower; }
[ "public", "int", "convertBoundaryToAbsolutePosition", "(", "int", "relativePosition", ")", "{", "if", "(", "relativePosition", "<", "0", "||", "relativePosition", ">", "length", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Relative position outsi...
Converts relative boundary position to absolute position @param relativePosition relative boundary position @return absolute point position
[ "Converts", "relative", "boundary", "position", "to", "absolute", "position" ]
2349b3dccdd3c7948643760e570238d6e30d5a34
https://github.com/milaboratory/milib/blob/2349b3dccdd3c7948643760e570238d6e30d5a34/src/main/java/com/milaboratory/core/Range.java#L379-L387
train
aeshell/aesh-readline
terminal-telnet/src/main/java/org/aesh/terminal/telnet/TelnetConnection.java
TelnetConnection.write
public final void write(byte[] data) { if (sendBinary) { int prev = 0; for (int i = 0;i < data.length;i++) { if (data[i] == -1) { rawWrite(data, prev, i - prev); send(new byte[]{-1, -1}); prev = i + 1; } } rawWrite(data, prev, data.length - prev); } else { for (int i = 0;i < data.length;i++) { data[i] = (byte)(data[i] & 0x7F); } send(data); } }
java
public final void write(byte[] data) { if (sendBinary) { int prev = 0; for (int i = 0;i < data.length;i++) { if (data[i] == -1) { rawWrite(data, prev, i - prev); send(new byte[]{-1, -1}); prev = i + 1; } } rawWrite(data, prev, data.length - prev); } else { for (int i = 0;i < data.length;i++) { data[i] = (byte)(data[i] & 0x7F); } send(data); } }
[ "public", "final", "void", "write", "(", "byte", "[", "]", "data", ")", "{", "if", "(", "sendBinary", ")", "{", "int", "prev", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", ...
Write data to the client, escaping data if necessary or truncating it. The original buffer can be mutated if incorrect data is provided. @param data the data to write
[ "Write", "data", "to", "the", "client", "escaping", "data", "if", "necessary", "or", "truncating", "it", ".", "The", "original", "buffer", "can", "be", "mutated", "if", "incorrect", "data", "is", "provided", "." ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/terminal-telnet/src/main/java/org/aesh/terminal/telnet/TelnetConnection.java#L122-L139
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/history/FileHistory.java
FileHistory.readFile
private void readFile() { if(historyFile.exists()) { try (BufferedReader reader = new BufferedReader(new FileReader(historyFile))) { String line; while((line = reader.readLine()) != null) push(Parser.toCodePoints(line)); } catch(FileNotFoundException ignored) { //AESH-205 } catch (IOException e) { if(logging) LOGGER.log(Level.WARNING, "Failed to read from history file, ", e); } } }
java
private void readFile() { if(historyFile.exists()) { try (BufferedReader reader = new BufferedReader(new FileReader(historyFile))) { String line; while((line = reader.readLine()) != null) push(Parser.toCodePoints(line)); } catch(FileNotFoundException ignored) { //AESH-205 } catch (IOException e) { if(logging) LOGGER.log(Level.WARNING, "Failed to read from history file, ", e); } } }
[ "private", "void", "readFile", "(", ")", "{", "if", "(", "historyFile", ".", "exists", "(", ")", ")", "{", "try", "(", "BufferedReader", "reader", "=", "new", "BufferedReader", "(", "new", "FileReader", "(", "historyFile", ")", ")", ")", "{", "String", ...
Read specified history file to history buffer
[ "Read", "specified", "history", "file", "to", "history", "buffer" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/history/FileHistory.java#L68-L81
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/history/FileHistory.java
FileHistory.writeFile
private void writeFile() throws IOException { historyFile.delete(); try (FileWriter fw = new FileWriter(historyFile)) { for(int i=0; i < size();i++) fw.write(Parser.fromCodePoints(get(i)) + (Config.getLineSeparator())); } if (historyFilePermission != null) { historyFile.setReadable(false, false); historyFile.setReadable(historyFilePermission.isReadable(), historyFilePermission.isReadableOwnerOnly()); historyFile.setWritable(false, false); historyFile.setWritable(historyFilePermission.isWritable(), historyFilePermission.isWritableOwnerOnly()); historyFile.setExecutable(false, false); historyFile.setExecutable(historyFilePermission.isExecutable(), historyFilePermission.isExecutableOwnerOnly()); } }
java
private void writeFile() throws IOException { historyFile.delete(); try (FileWriter fw = new FileWriter(historyFile)) { for(int i=0; i < size();i++) fw.write(Parser.fromCodePoints(get(i)) + (Config.getLineSeparator())); } if (historyFilePermission != null) { historyFile.setReadable(false, false); historyFile.setReadable(historyFilePermission.isReadable(), historyFilePermission.isReadableOwnerOnly()); historyFile.setWritable(false, false); historyFile.setWritable(historyFilePermission.isWritable(), historyFilePermission.isWritableOwnerOnly()); historyFile.setExecutable(false, false); historyFile.setExecutable(historyFilePermission.isExecutable(), historyFilePermission.isExecutableOwnerOnly()); } }
[ "private", "void", "writeFile", "(", ")", "throws", "IOException", "{", "historyFile", ".", "delete", "(", ")", ";", "try", "(", "FileWriter", "fw", "=", "new", "FileWriter", "(", "historyFile", ")", ")", "{", "for", "(", "int", "i", "=", "0", ";", "...
Write the content of the history buffer to file @throws IOException io
[ "Write", "the", "content", "of", "the", "history", "buffer", "to", "file" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/history/FileHistory.java#L88-L103
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/terminal/impl/WinSysTerminal.java
WinSysTerminal.setVTMode
private static boolean setVTMode() { long console = GetStdHandle(STD_OUTPUT_HANDLE); int[] mode = new int[1]; if (Kernel32.GetConsoleMode(console, mode) == 0) { // No need to go further, not supported. return false; } if (Kernel32.SetConsoleMode(console, mode[0] | VIRTUAL_TERMINAL_PROCESSING) == 0) { // No need to go further, not supported. return false; } return true; }
java
private static boolean setVTMode() { long console = GetStdHandle(STD_OUTPUT_HANDLE); int[] mode = new int[1]; if (Kernel32.GetConsoleMode(console, mode) == 0) { // No need to go further, not supported. return false; } if (Kernel32.SetConsoleMode(console, mode[0] | VIRTUAL_TERMINAL_PROCESSING) == 0) { // No need to go further, not supported. return false; } return true; }
[ "private", "static", "boolean", "setVTMode", "(", ")", "{", "long", "console", "=", "GetStdHandle", "(", "STD_OUTPUT_HANDLE", ")", ";", "int", "[", "]", "mode", "=", "new", "int", "[", "1", "]", ";", "if", "(", "Kernel32", ".", "GetConsoleMode", "(", "...
This allows to take benefit from Windows 10+ new features.
[ "This", "allows", "to", "take", "benefit", "from", "Windows", "10", "+", "new", "features", "." ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/terminal/impl/WinSysTerminal.java#L130-L143
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.formatDisplayCompactListTerminalString
public static String formatDisplayCompactListTerminalString(List<TerminalString> displayList, int termWidth) { if (displayList == null || displayList.size() < 1) return ""; // make sure that termWidth is > 0 if (termWidth < 1) termWidth = 80; // setting it to default int numRows = 1; // increase numRows and check in loop if it's possible to format strings to columns while (!canDisplayColumns(displayList, numRows, termWidth) && numRows < displayList.size()) { numRows++; } int numColumns = displayList.size() / numRows; if (displayList.size() % numRows > 0) { numColumns++; } int[] columnsSizes = calculateColumnSizes(displayList, numColumns, numRows, termWidth); StringBuilder stringOutput = new StringBuilder(); for (int i = 0; i < numRows; i++) { for (int c = 0; c < numColumns; c++) { int fetch = i + (c * numRows); int nextFetch = i + ((c + 1) * numRows); if (fetch < displayList.size()) { // don't need to format last column of row = nextFetch doesn't exit if (nextFetch < displayList.size()) { stringOutput.append(padRight(columnsSizes[c] + displayList.get(i + (c * numRows)).getANSILength(), displayList.get(i + (c * numRows)).toString())); } else { stringOutput.append(displayList.get(i + (c * numRows)).toString()); } } else { break; } } stringOutput.append(Config.getLineSeparator()); } return stringOutput.toString(); }
java
public static String formatDisplayCompactListTerminalString(List<TerminalString> displayList, int termWidth) { if (displayList == null || displayList.size() < 1) return ""; // make sure that termWidth is > 0 if (termWidth < 1) termWidth = 80; // setting it to default int numRows = 1; // increase numRows and check in loop if it's possible to format strings to columns while (!canDisplayColumns(displayList, numRows, termWidth) && numRows < displayList.size()) { numRows++; } int numColumns = displayList.size() / numRows; if (displayList.size() % numRows > 0) { numColumns++; } int[] columnsSizes = calculateColumnSizes(displayList, numColumns, numRows, termWidth); StringBuilder stringOutput = new StringBuilder(); for (int i = 0; i < numRows; i++) { for (int c = 0; c < numColumns; c++) { int fetch = i + (c * numRows); int nextFetch = i + ((c + 1) * numRows); if (fetch < displayList.size()) { // don't need to format last column of row = nextFetch doesn't exit if (nextFetch < displayList.size()) { stringOutput.append(padRight(columnsSizes[c] + displayList.get(i + (c * numRows)).getANSILength(), displayList.get(i + (c * numRows)).toString())); } else { stringOutput.append(displayList.get(i + (c * numRows)).toString()); } } else { break; } } stringOutput.append(Config.getLineSeparator()); } return stringOutput.toString(); }
[ "public", "static", "String", "formatDisplayCompactListTerminalString", "(", "List", "<", "TerminalString", ">", "displayList", ",", "int", "termWidth", ")", "{", "if", "(", "displayList", "==", "null", "||", "displayList", ".", "size", "(", ")", "<", "1", ")"...
Format output to columns with flexible sizes and no redundant space between them @param displayList to format @param termWidth max width @return formatted string to be outputted
[ "Format", "output", "to", "columns", "with", "flexible", "sizes", "and", "no", "redundant", "space", "between", "them" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L196-L242
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.canDisplayColumns
private static boolean canDisplayColumns(List<TerminalString> displayList, int numRows, int terminalWidth) { int numColumns = displayList.size() / numRows; if (displayList.size() % numRows > 0) { numColumns++; } int[] columnSizes = calculateColumnSizes(displayList, numColumns, numRows, terminalWidth); int totalSize = 0; for (int columnSize : columnSizes) { totalSize += columnSize; } return totalSize <= terminalWidth; }
java
private static boolean canDisplayColumns(List<TerminalString> displayList, int numRows, int terminalWidth) { int numColumns = displayList.size() / numRows; if (displayList.size() % numRows > 0) { numColumns++; } int[] columnSizes = calculateColumnSizes(displayList, numColumns, numRows, terminalWidth); int totalSize = 0; for (int columnSize : columnSizes) { totalSize += columnSize; } return totalSize <= terminalWidth; }
[ "private", "static", "boolean", "canDisplayColumns", "(", "List", "<", "TerminalString", ">", "displayList", ",", "int", "numRows", ",", "int", "terminalWidth", ")", "{", "int", "numColumns", "=", "displayList", ".", "size", "(", ")", "/", "numRows", ";", "i...
Decides if it's possible to format provided Strings into calculated number of columns while the output will not exceed terminal width @param displayList @param numRows @param terminalWidth @return true if it's possible to format strings to columns and false otherwise.
[ "Decides", "if", "it", "s", "possible", "to", "format", "provided", "Strings", "into", "calculated", "number", "of", "columns", "while", "the", "output", "will", "not", "exceed", "terminal", "width" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L253-L267
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.trimOptionName
public static String trimOptionName(String word) { if (word.startsWith("--")) return word.substring(2); else if (word.startsWith("-")) return word.substring(1); else return word; }
java
public static String trimOptionName(String word) { if (word.startsWith("--")) return word.substring(2); else if (word.startsWith("-")) return word.substring(1); else return word; }
[ "public", "static", "String", "trimOptionName", "(", "String", "word", ")", "{", "if", "(", "word", ".", "startsWith", "(", "\"--\"", ")", ")", "return", "word", ".", "substring", "(", "2", ")", ";", "else", "if", "(", "word", ".", "startsWith", "(", ...
remove leading dashes from word
[ "remove", "leading", "dashes", "from", "word" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L319-L326
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.findStartsWithOperation
public static String findStartsWithOperation(List<? extends CompleteOperation> coList) { List<String> tmpList = new ArrayList<>(); for (CompleteOperation co : coList) { String s = findStartsWith(co.getFormattedCompletionCandidates()); if (s.length() > 0) tmpList.add(s); else return ""; } return findStartsWith(tmpList); }
java
public static String findStartsWithOperation(List<? extends CompleteOperation> coList) { List<String> tmpList = new ArrayList<>(); for (CompleteOperation co : coList) { String s = findStartsWith(co.getFormattedCompletionCandidates()); if (s.length() > 0) tmpList.add(s); else return ""; } return findStartsWith(tmpList); }
[ "public", "static", "String", "findStartsWithOperation", "(", "List", "<", "?", "extends", "CompleteOperation", ">", "coList", ")", "{", "List", "<", "String", ">", "tmpList", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "CompleteOperation", "co...
If there is any common start string in the completion list, return it @param coList completion list @return common start string
[ "If", "there", "is", "any", "common", "start", "string", "in", "the", "completion", "list", "return", "it" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L338-L348
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.findCurrentWordFromCursor
public static String findCurrentWordFromCursor(String text, int cursor) { if (text.length() <= cursor + 1) { // return last word if (text.contains(SPACE)) { if (doWordContainEscapedSpace(text)) { if (doWordContainOnlyEscapedSpace(text)) return switchEscapedSpacesToSpacesInWord(text); else { return switchEscapedSpacesToSpacesInWord(findEscapedSpaceWordCloseToEnd(text)); } } else { if (text.lastIndexOf(SPACE) >= cursor) // cant use lastIndexOf return text.substring(text.substring(0, cursor).lastIndexOf(SPACE)).trim(); else return text.substring(text.lastIndexOf(SPACE)).trim(); } } else return text.trim(); } else { String rest; if (text.length() > cursor + 1) rest = text.substring(0, cursor + 1); else rest = text; if (doWordContainOnlyEscapedSpace(rest)) { if (cursor > 1 && text.charAt(cursor) == SPACE_CHAR && text.charAt(cursor - 1) == SPACE_CHAR) return ""; else return switchEscapedSpacesToSpacesInWord(rest); } else { if (cursor > 1 && text.charAt(cursor) == SPACE_CHAR && text.charAt(cursor - 1) == SPACE_CHAR) return ""; // only if it contains a ' ' and its not at the end of the string if (rest.trim().contains(SPACE)) return rest.substring(rest.trim().lastIndexOf(" ")).trim(); else return rest.trim(); } } }
java
public static String findCurrentWordFromCursor(String text, int cursor) { if (text.length() <= cursor + 1) { // return last word if (text.contains(SPACE)) { if (doWordContainEscapedSpace(text)) { if (doWordContainOnlyEscapedSpace(text)) return switchEscapedSpacesToSpacesInWord(text); else { return switchEscapedSpacesToSpacesInWord(findEscapedSpaceWordCloseToEnd(text)); } } else { if (text.lastIndexOf(SPACE) >= cursor) // cant use lastIndexOf return text.substring(text.substring(0, cursor).lastIndexOf(SPACE)).trim(); else return text.substring(text.lastIndexOf(SPACE)).trim(); } } else return text.trim(); } else { String rest; if (text.length() > cursor + 1) rest = text.substring(0, cursor + 1); else rest = text; if (doWordContainOnlyEscapedSpace(rest)) { if (cursor > 1 && text.charAt(cursor) == SPACE_CHAR && text.charAt(cursor - 1) == SPACE_CHAR) return ""; else return switchEscapedSpacesToSpacesInWord(rest); } else { if (cursor > 1 && text.charAt(cursor) == SPACE_CHAR && text.charAt(cursor - 1) == SPACE_CHAR) return ""; // only if it contains a ' ' and its not at the end of the string if (rest.trim().contains(SPACE)) return rest.substring(rest.trim().lastIndexOf(" ")).trim(); else return rest.trim(); } } }
[ "public", "static", "String", "findCurrentWordFromCursor", "(", "String", "text", ",", "int", "cursor", ")", "{", "if", "(", "text", ".", "length", "(", ")", "<=", "cursor", "+", "1", ")", "{", "// return last word", "if", "(", "text", ".", "contains", "...
Return the word "connected" to cursor, the word ends at cursor position. Note that cursor position starts at 0 @param text to parse @param cursor position @return word connected to cursor
[ "Return", "the", "word", "connected", "to", "cursor", "the", "word", "ends", "at", "cursor", "position", ".", "Note", "that", "cursor", "position", "starts", "at", "0" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L470-L516
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.findEscapedSpaceWordCloseToEnd
public static String findEscapedSpaceWordCloseToEnd(String text) { int index; String originalText = text; while ((index = text.lastIndexOf(SPACE)) > -1) { if (index > 0 && text.charAt(index - 1) == BACK_SLASH) { text = text.substring(0, index - 1); } else return originalText.substring(index + 1); } return originalText; }
java
public static String findEscapedSpaceWordCloseToEnd(String text) { int index; String originalText = text; while ((index = text.lastIndexOf(SPACE)) > -1) { if (index > 0 && text.charAt(index - 1) == BACK_SLASH) { text = text.substring(0, index - 1); } else return originalText.substring(index + 1); } return originalText; }
[ "public", "static", "String", "findEscapedSpaceWordCloseToEnd", "(", "String", "text", ")", "{", "int", "index", ";", "String", "originalText", "=", "text", ";", "while", "(", "(", "index", "=", "text", ".", "lastIndexOf", "(", "SPACE", ")", ")", ">", "-",...
Search backwards for a non-escaped space and only return work containing non-escaped space @param text text @return text with only non-escaped space
[ "Search", "backwards", "for", "a", "non", "-", "escaped", "space", "and", "only", "return", "work", "containing", "non", "-", "escaped", "space" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L524-L535
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.doesStringContainOpenQuote
public static boolean doesStringContainOpenQuote(String text) { boolean doubleQuote = false; boolean singleQuote = false; boolean escapedByBackSlash = false; // do not parse comment if (commentPattern.matcher(text).find()) return false; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == BACK_SLASH || escapedByBackSlash) { escapedByBackSlash = !escapedByBackSlash; continue; } if (text.charAt(i) == SINGLE_QUOTE) { if (!doubleQuote) singleQuote = !singleQuote; } else if (text.charAt(i) == DOUBLE_QUOTE) { if (!singleQuote) doubleQuote = !doubleQuote; } } return doubleQuote || singleQuote; }
java
public static boolean doesStringContainOpenQuote(String text) { boolean doubleQuote = false; boolean singleQuote = false; boolean escapedByBackSlash = false; // do not parse comment if (commentPattern.matcher(text).find()) return false; for (int i = 0; i < text.length(); i++) { if (text.charAt(i) == BACK_SLASH || escapedByBackSlash) { escapedByBackSlash = !escapedByBackSlash; continue; } if (text.charAt(i) == SINGLE_QUOTE) { if (!doubleQuote) singleQuote = !singleQuote; } else if (text.charAt(i) == DOUBLE_QUOTE) { if (!singleQuote) doubleQuote = !doubleQuote; } } return doubleQuote || singleQuote; }
[ "public", "static", "boolean", "doesStringContainOpenQuote", "(", "String", "text", ")", "{", "boolean", "doubleQuote", "=", "false", ";", "boolean", "singleQuote", "=", "false", ";", "boolean", "escapedByBackSlash", "=", "false", ";", "// do not parse comment", "if...
Check if a string contain openBlocking quotes. Escaped quotes does not count. @param text text @return true if it contains openBlocking quotes, else false
[ "Check", "if", "a", "string", "contain", "openBlocking", "quotes", ".", "Escaped", "quotes", "does", "not", "count", "." ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L543-L566
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.findNumberOfSpacesInWord
public static int findNumberOfSpacesInWord(String word) { int count = 0; for (int i = 0; i < word.length(); i++) if (word.charAt(i) == SPACE_CHAR && (i == 0 || word.charAt(i - 1) != BACK_SLASH)) count++; return count; }
java
public static int findNumberOfSpacesInWord(String word) { int count = 0; for (int i = 0; i < word.length(); i++) if (word.charAt(i) == SPACE_CHAR && (i == 0 || word.charAt(i - 1) != BACK_SLASH)) count++; return count; }
[ "public", "static", "int", "findNumberOfSpacesInWord", "(", "String", "word", ")", "{", "int", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "word", ".", "length", "(", ")", ";", "i", "++", ")", "if", "(", "word", ".", ...
find number of spaces in the given word. escaped spaces are not counted @param word to check @return number of spaces
[ "find", "number", "of", "spaces", "in", "the", "given", "word", ".", "escaped", "spaces", "are", "not", "counted" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L582-L589
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/util/Parser.java
Parser.trimInFront
public static String trimInFront(String buffer) { // remove spaces in front int count = 0; for (int i = 0; i < buffer.length(); i++) { if (buffer.charAt(i) == SPACE_CHAR) count++; else break; } if (count > 0) return buffer.substring(count); else return buffer; }
java
public static String trimInFront(String buffer) { // remove spaces in front int count = 0; for (int i = 0; i < buffer.length(); i++) { if (buffer.charAt(i) == SPACE_CHAR) count++; else break; } if (count > 0) return buffer.substring(count); else return buffer; }
[ "public", "static", "String", "trimInFront", "(", "String", "buffer", ")", "{", "// remove spaces in front", "int", "count", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "buffer", ".", "length", "(", ")", ";", "i", "++", ")", "{", ...
Only trim space in front of the word @param buffer input @return trimmed buffer
[ "Only", "trim", "space", "in", "front", "of", "the", "word" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/util/Parser.java#L658-L671
train
aeshell/aesh-readline
readline/src/main/java/org/aesh/readline/editing/InputrcParser.java
InputrcParser.mapQuoteKeys
public static int[] mapQuoteKeys(String keys) { if(keys != null && keys.length() > 1) return mapKeys(keys.substring(1)); else return null; }
java
public static int[] mapQuoteKeys(String keys) { if(keys != null && keys.length() > 1) return mapKeys(keys.substring(1)); else return null; }
[ "public", "static", "int", "[", "]", "mapQuoteKeys", "(", "String", "keys", ")", "{", "if", "(", "keys", "!=", "null", "&&", "keys", ".", "length", "(", ")", ">", "1", ")", "return", "mapKeys", "(", "keys", ".", "substring", "(", "1", ")", ")", "...
Parse key mapping lines that start with " @param keys that need mapping @return int[] value of keys
[ "Parse", "key", "mapping", "lines", "that", "start", "with" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/readline/src/main/java/org/aesh/readline/editing/InputrcParser.java#L199-L204
train
aeshell/aesh-readline
terminal-api/src/main/java/org/aesh/utils/ANSI.java
ANSI.printAnsi
public static int[] printAnsi(char... out) { int[] ansi = new int[out.length+2]; ansi[0] = 27; ansi[1] = '['; int counter = 0; for (char anOut : out) { if (anOut == '\t') { Arrays.fill(ansi, counter + 2, counter + 2 + TAB, ' '); counter += TAB - 1; } else ansi[counter + 2] = anOut; counter++; } return ansi; }
java
public static int[] printAnsi(char... out) { int[] ansi = new int[out.length+2]; ansi[0] = 27; ansi[1] = '['; int counter = 0; for (char anOut : out) { if (anOut == '\t') { Arrays.fill(ansi, counter + 2, counter + 2 + TAB, ' '); counter += TAB - 1; } else ansi[counter + 2] = anOut; counter++; } return ansi; }
[ "public", "static", "int", "[", "]", "printAnsi", "(", "char", "...", "out", ")", "{", "int", "[", "]", "ansi", "=", "new", "int", "[", "out", ".", "length", "+", "2", "]", ";", "ansi", "[", "0", "]", "=", "27", ";", "ansi", "[", "1", "]", ...
Return a ansified string based on param @param out what will be ansified @return ansified string
[ "Return", "a", "ansified", "string", "based", "on", "param" ]
3d7258f6490a422658ec85c8457514390c03232d
https://github.com/aeshell/aesh-readline/blob/3d7258f6490a422658ec85c8457514390c03232d/terminal-api/src/main/java/org/aesh/utils/ANSI.java#L111-L127
train
osglworks/java-di
src/main/java/org/osgl/inject/util/AnnotationUtil.java
AnnotationUtil.createAnnotation
@SuppressWarnings("unchecked") public static <T extends Annotation> T createAnnotation(final Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz, Annotation.class}, new SimpleAnnoInvocationHandler(clazz)); }
java
@SuppressWarnings("unchecked") public static <T extends Annotation> T createAnnotation(final Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz, Annotation.class}, new SimpleAnnoInvocationHandler(clazz)); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", "extends", "Annotation", ">", "T", "createAnnotation", "(", "final", "Class", "<", "T", ">", "clazz", ")", "{", "return", "(", "T", ")", "Proxy", ".", "newProxyInstance", "("...
Create an annotation instance from annotation class. @param clazz the annotation class @param <T> the generic type of the annoation @return the annotation instance
[ "Create", "an", "annotation", "instance", "from", "annotation", "class", "." ]
d89871c62ff508733bfa645425596f6c917fd7ee
https://github.com/osglworks/java-di/blob/d89871c62ff508733bfa645425596f6c917fd7ee/src/main/java/org/osgl/inject/util/AnnotationUtil.java#L95-L98
train
osglworks/java-di
src/main/java/org/osgl/inject/util/AnnotationUtil.java
AnnotationUtil.hashMember
static int hashMember(String name, Object value) { int part1 = name.hashCode() * 127; if (value.getClass().isArray()) { return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value); } if (value instanceof Annotation) { return part1 ^ hashCode((Annotation) value); } return part1 ^ value.hashCode(); }
java
static int hashMember(String name, Object value) { int part1 = name.hashCode() * 127; if (value.getClass().isArray()) { return part1 ^ arrayMemberHash(value.getClass().getComponentType(), value); } if (value instanceof Annotation) { return part1 ^ hashCode((Annotation) value); } return part1 ^ value.hashCode(); }
[ "static", "int", "hashMember", "(", "String", "name", ",", "Object", "value", ")", "{", "int", "part1", "=", "name", ".", "hashCode", "(", ")", "*", "127", ";", "if", "(", "value", ".", "getClass", "(", ")", ".", "isArray", "(", ")", ")", "{", "r...
Helper method for generating a hash code for a member of an annotation. @param name the name of the member @param value the value of the member @return a hash code for this member
[ "Helper", "method", "for", "generating", "a", "hash", "code", "for", "a", "member", "of", "an", "annotation", "." ]
d89871c62ff508733bfa645425596f6c917fd7ee
https://github.com/osglworks/java-di/blob/d89871c62ff508733bfa645425596f6c917fd7ee/src/main/java/org/osgl/inject/util/AnnotationUtil.java#L144-L153
train
osglworks/java-di
src/main/java/org/osgl/inject/BeanSpec.java
BeanSpec.beanSpecOf
private BeanSpec beanSpecOf(Field field, Type genericType) { return of(field, genericType, injector); // int len = typeArgs.size(); // for (int i = 0; i < len; ++i) { // if (genericType.equals(typeArgs.get(i))) { // return of(field, typeImpls.get(i), injector()); // } // } // return of(field, injector); }
java
private BeanSpec beanSpecOf(Field field, Type genericType) { return of(field, genericType, injector); // int len = typeArgs.size(); // for (int i = 0; i < len; ++i) { // if (genericType.equals(typeArgs.get(i))) { // return of(field, typeImpls.get(i), injector()); // } // } // return of(field, injector); }
[ "private", "BeanSpec", "beanSpecOf", "(", "Field", "field", ",", "Type", "genericType", ")", "{", "return", "of", "(", "field", ",", "genericType", ",", "injector", ")", ";", "// int len = typeArgs.size();", "// for (int i = 0; i < len; ++i) {", "// ...
find the beanspec of a field with generic type
[ "find", "the", "beanspec", "of", "a", "field", "with", "generic", "type" ]
d89871c62ff508733bfa645425596f6c917fd7ee
https://github.com/osglworks/java-di/blob/d89871c62ff508733bfa645425596f6c917fd7ee/src/main/java/org/osgl/inject/BeanSpec.java#L707-L716
train
osglworks/java-di
src/main/java/org/osgl/inject/BeanSpec.java
BeanSpec.storeTagAnnotation
private void storeTagAnnotation(Annotation anno) { Class<? extends Annotation> annoType = anno.annotationType(); Annotation[] tags = annoType.getAnnotations(); for (Annotation tag : tags) { Class<? extends Annotation> tagType = tag.annotationType(); if (WAIVE_TAG_TYPES.contains(tagType)) { continue; } Set<Annotation> tagged = tagAnnotations.get(tagType); if (null == tagged) { tagged = new HashSet<>(); tagAnnotations.put(tagType, tagged); } tagged.add(anno); } }
java
private void storeTagAnnotation(Annotation anno) { Class<? extends Annotation> annoType = anno.annotationType(); Annotation[] tags = annoType.getAnnotations(); for (Annotation tag : tags) { Class<? extends Annotation> tagType = tag.annotationType(); if (WAIVE_TAG_TYPES.contains(tagType)) { continue; } Set<Annotation> tagged = tagAnnotations.get(tagType); if (null == tagged) { tagged = new HashSet<>(); tagAnnotations.put(tagType, tagged); } tagged.add(anno); } }
[ "private", "void", "storeTagAnnotation", "(", "Annotation", "anno", ")", "{", "Class", "<", "?", "extends", "Annotation", ">", "annoType", "=", "anno", ".", "annotationType", "(", ")", ";", "Annotation", "[", "]", "tags", "=", "annoType", ".", "getAnnotation...
Walk through anno's tag annotations @param anno the annotation
[ "Walk", "through", "anno", "s", "tag", "annotations" ]
d89871c62ff508733bfa645425596f6c917fd7ee
https://github.com/osglworks/java-di/blob/d89871c62ff508733bfa645425596f6c917fd7ee/src/main/java/org/osgl/inject/BeanSpec.java#L923-L938
train
att/openstacksdk
openstack-java-sdk/openstack-client/src/main/java/com/woorea/openstack/base/client/OpenStackRequest.java
OpenStackRequest.queryString
public OpenStackRequest<R> queryString(String queryString) { if (queryString != null) { String[] params = queryString.split("&"); for (String param : params) { String[] s = param.split("="); if (s[0] != null && s[1] != null) { queryParam(s[0], s[1]); } } } return this; }
java
public OpenStackRequest<R> queryString(String queryString) { if (queryString != null) { String[] params = queryString.split("&"); for (String param : params) { String[] s = param.split("="); if (s[0] != null && s[1] != null) { queryParam(s[0], s[1]); } } } return this; }
[ "public", "OpenStackRequest", "<", "R", ">", "queryString", "(", "String", "queryString", ")", "{", "if", "(", "queryString", "!=", "null", ")", "{", "String", "[", "]", "params", "=", "queryString", ".", "split", "(", "\"&\"", ")", ";", "for", "(", "S...
This method will parse the query string which is a collection of name value pairs and put then in queryParam hash map @param queryString The query string to be parsed @return The request object
[ "This", "method", "will", "parse", "the", "query", "string", "which", "is", "a", "collection", "of", "name", "value", "pairs", "and", "put", "then", "in", "queryParam", "hash", "map" ]
16a81c460a7186ebe1ea63b7682486ba147208b9
https://github.com/att/openstacksdk/blob/16a81c460a7186ebe1ea63b7682486ba147208b9/openstack-java-sdk/openstack-client/src/main/java/com/woorea/openstack/base/client/OpenStackRequest.java#L192-L203
train
att/openstacksdk
openstack-java-sdk/nova-client/src/main/java/com/woorea/openstack/nova/api/ServersResource.java
ServersResource.evacuate
public EvacuateAction evacuate(String serverId, String host) { return evacuate(serverId, host, null, null); }
java
public EvacuateAction evacuate(String serverId, String host) { return evacuate(serverId, host, null, null); }
[ "public", "EvacuateAction", "evacuate", "(", "String", "serverId", ",", "String", "host", ")", "{", "return", "evacuate", "(", "serverId", ",", "host", ",", "null", ",", "null", ")", ";", "}" ]
Evacuates the server to a new host. The caller can supply the host name or id. @param serverId The server to be evacuated @param host The host name or ID of the target host (where the server is to be moved to). @return The action to be performed @see #evacuate(String, String, String, Boolean)
[ "Evacuates", "the", "server", "to", "a", "new", "host", ".", "The", "caller", "can", "supply", "the", "host", "name", "or", "id", "." ]
16a81c460a7186ebe1ea63b7682486ba147208b9
https://github.com/att/openstacksdk/blob/16a81c460a7186ebe1ea63b7682486ba147208b9/openstack-java-sdk/nova-client/src/main/java/com/woorea/openstack/nova/api/ServersResource.java#L635-L637
train
att/openstacksdk
openstack-java-sdk/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyConnector.java
JerseyConnector.getSSLContext
private SSLContext getSSLContext() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // nop } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // nop } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }, new java.security.SecureRandom()); return sslContext; }
java
private SSLContext getSSLContext() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { // nop } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { // nop } @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }, new java.security.SecureRandom()); return sslContext; }
[ "private", "SSLContext", "getSSLContext", "(", ")", "throws", "NoSuchAlgorithmException", ",", "KeyManagementException", "{", "SSLContext", "sslContext", "=", "SSLContext", ".", "getInstance", "(", "\"SSL\"", ")", ";", "sslContext", ".", "init", "(", "null", ",", ...
This SSLContext is used only when the protocol is HTTPS AND a trusted hosts list has been provided. In that case, this SSLContext accepts all certificates, whether they are expired or not, and regardless of the CA that issued them. @return An SSL context that does not validate certificates @throws NoSuchAlgorithmException @throws KeyManagementException
[ "This", "SSLContext", "is", "used", "only", "when", "the", "protocol", "is", "HTTPS", "AND", "a", "trusted", "hosts", "list", "has", "been", "provided", ".", "In", "that", "case", "this", "SSLContext", "accepts", "all", "certificates", "whether", "they", "ar...
16a81c460a7186ebe1ea63b7682486ba147208b9
https://github.com/att/openstacksdk/blob/16a81c460a7186ebe1ea63b7682486ba147208b9/openstack-java-sdk/openstack-client-connectors/jersey-connector/src/main/java/com/woorea/openstack/connector/JerseyConnector.java#L335-L356
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSlaveTemplate.java
DockerSlaveTemplate.getRetentionStrategyCopy
public RetentionStrategy getRetentionStrategyCopy() { if (retentionStrategy instanceof DockerOnceRetentionStrategy) { DockerOnceRetentionStrategy onceRetention = (DockerOnceRetentionStrategy) retentionStrategy; return new DockerOnceRetentionStrategy(onceRetention.getIdleMinutes()); } return retentionStrategy; }
java
public RetentionStrategy getRetentionStrategyCopy() { if (retentionStrategy instanceof DockerOnceRetentionStrategy) { DockerOnceRetentionStrategy onceRetention = (DockerOnceRetentionStrategy) retentionStrategy; return new DockerOnceRetentionStrategy(onceRetention.getIdleMinutes()); } return retentionStrategy; }
[ "public", "RetentionStrategy", "getRetentionStrategyCopy", "(", ")", "{", "if", "(", "retentionStrategy", "instanceof", "DockerOnceRetentionStrategy", ")", "{", "DockerOnceRetentionStrategy", "onceRetention", "=", "(", "DockerOnceRetentionStrategy", ")", "retentionStrategy", ...
tmp fix for terminating boolean caching
[ "tmp", "fix", "for", "terminating", "boolean", "caching" ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSlaveTemplate.java#L96-L102
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSlaveTemplate.java
DockerSlaveTemplate.readResolve
@SuppressWarnings("unused") public Object readResolve() { if (configVersion < 1) { if (isNull(nodeProperties)) nodeProperties = new ArrayList<>(); nodeProperties.add(new DockerNodeProperty("DOCKER_CONTAINER_ID", "JENKINS_CLOUD_ID", "DOCKER_HOST")); configVersion = 1; } // real @Nonnull if (mode == null) { mode = Node.Mode.NORMAL; } if (retentionStrategy == null) { retentionStrategy = new DockerOnceRetentionStrategy(10); } try { labelSet = Label.parse(getLabelString()); // fails sometimes under debugger } catch (Throwable t) { LOG.error("Can't parse labels: {}", t); } return this; }
java
@SuppressWarnings("unused") public Object readResolve() { if (configVersion < 1) { if (isNull(nodeProperties)) nodeProperties = new ArrayList<>(); nodeProperties.add(new DockerNodeProperty("DOCKER_CONTAINER_ID", "JENKINS_CLOUD_ID", "DOCKER_HOST")); configVersion = 1; } // real @Nonnull if (mode == null) { mode = Node.Mode.NORMAL; } if (retentionStrategy == null) { retentionStrategy = new DockerOnceRetentionStrategy(10); } try { labelSet = Label.parse(getLabelString()); // fails sometimes under debugger } catch (Throwable t) { LOG.error("Can't parse labels: {}", t); } return this; }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "public", "Object", "readResolve", "(", ")", "{", "if", "(", "configVersion", "<", "1", ")", "{", "if", "(", "isNull", "(", "nodeProperties", ")", ")", "nodeProperties", "=", "new", "ArrayList", "<>", "(", ...
Initializes data structure that we don't persist.
[ "Initializes", "data", "structure", "that", "we", "don", "t", "persist", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerSlaveTemplate.java#L126-L150
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/launcher/DockerComputerJNLPLauncher.java
DockerComputerJNLPLauncher.getPreparedLauncher
@Override public DockerComputerLauncher getPreparedLauncher(String cloudId, DockerSlaveTemplate template, InspectContainerResponse containerInspectResponse) { final DockerComputerJNLPLauncher cloneJNLPlauncher = new DockerComputerJNLPLauncher(); cloneJNLPlauncher.setLaunchTimeout(getLaunchTimeout()); cloneJNLPlauncher.setUser(getUser()); cloneJNLPlauncher.setJvmOpts(getJvmOpts()); cloneJNLPlauncher.setSlaveOpts(getSlaveOpts()); cloneJNLPlauncher.setJenkinsUrl(getJenkinsUrl()); cloneJNLPlauncher.setNoCertificateCheck(isNoCertificateCheck()); cloneJNLPlauncher.setNoReconnect(isNoReconnect()); return cloneJNLPlauncher; }
java
@Override public DockerComputerLauncher getPreparedLauncher(String cloudId, DockerSlaveTemplate template, InspectContainerResponse containerInspectResponse) { final DockerComputerJNLPLauncher cloneJNLPlauncher = new DockerComputerJNLPLauncher(); cloneJNLPlauncher.setLaunchTimeout(getLaunchTimeout()); cloneJNLPlauncher.setUser(getUser()); cloneJNLPlauncher.setJvmOpts(getJvmOpts()); cloneJNLPlauncher.setSlaveOpts(getSlaveOpts()); cloneJNLPlauncher.setJenkinsUrl(getJenkinsUrl()); cloneJNLPlauncher.setNoCertificateCheck(isNoCertificateCheck()); cloneJNLPlauncher.setNoReconnect(isNoReconnect()); return cloneJNLPlauncher; }
[ "@", "Override", "public", "DockerComputerLauncher", "getPreparedLauncher", "(", "String", "cloudId", ",", "DockerSlaveTemplate", "template", ",", "InspectContainerResponse", "containerInspectResponse", ")", "{", "final", "DockerComputerJNLPLauncher", "cloneJNLPlauncher", "=", ...
Clone object.
[ "Clone", "object", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/launcher/DockerComputerJNLPLauncher.java#L320-L334
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java
DockerCloud.runContainer
public String runContainer(DockerSlaveTemplate slaveTemplate) throws DockerException, IOException { final DockerCreateContainer dockerCreateContainer = slaveTemplate.getDockerContainerLifecycle().getCreateContainer(); final String image = slaveTemplate.getDockerContainerLifecycle().getImage(); CreateContainerCmd containerConfig = getClient().createContainerCmd(image); // template specific options dockerCreateContainer.fillContainerConfig(containerConfig, null); // launcher specific options slaveTemplate.getLauncher().appendContainerConfig(slaveTemplate, containerConfig); // cloud specific options appendContainerConfig(slaveTemplate, containerConfig); // create CreateContainerResponse response = containerConfig.exec(); String containerId = response.getId(); LOG.debug("Created container {}, for {}", containerId, getDisplayName()); slaveTemplate.getLauncher().afterContainerCreate(getClient(), containerId); // start StartContainerCmd startCommand = getClient().startContainerCmd(containerId); try { startCommand.exec(); LOG.debug("Running container {}, for {}", containerId, getDisplayName()); } catch (Exception ex) { try { getClient().logContainerCmd(containerId) .withStdErr(true) .withStdOut(true) .exec(new MyLogContainerResultCallback()) .awaitCompletion(); } catch (Throwable t) { LOG.warn("Can't get logs for container start", t); } throw ex; } return containerId; }
java
public String runContainer(DockerSlaveTemplate slaveTemplate) throws DockerException, IOException { final DockerCreateContainer dockerCreateContainer = slaveTemplate.getDockerContainerLifecycle().getCreateContainer(); final String image = slaveTemplate.getDockerContainerLifecycle().getImage(); CreateContainerCmd containerConfig = getClient().createContainerCmd(image); // template specific options dockerCreateContainer.fillContainerConfig(containerConfig, null); // launcher specific options slaveTemplate.getLauncher().appendContainerConfig(slaveTemplate, containerConfig); // cloud specific options appendContainerConfig(slaveTemplate, containerConfig); // create CreateContainerResponse response = containerConfig.exec(); String containerId = response.getId(); LOG.debug("Created container {}, for {}", containerId, getDisplayName()); slaveTemplate.getLauncher().afterContainerCreate(getClient(), containerId); // start StartContainerCmd startCommand = getClient().startContainerCmd(containerId); try { startCommand.exec(); LOG.debug("Running container {}, for {}", containerId, getDisplayName()); } catch (Exception ex) { try { getClient().logContainerCmd(containerId) .withStdErr(true) .withStdOut(true) .exec(new MyLogContainerResultCallback()) .awaitCompletion(); } catch (Throwable t) { LOG.warn("Can't get logs for container start", t); } throw ex; } return containerId; }
[ "public", "String", "runContainer", "(", "DockerSlaveTemplate", "slaveTemplate", ")", "throws", "DockerException", ",", "IOException", "{", "final", "DockerCreateContainer", "dockerCreateContainer", "=", "slaveTemplate", ".", "getDockerContainerLifecycle", "(", ")", ".", ...
Run docker container for given template @return container id
[ "Run", "docker", "container", "for", "given", "template" ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java#L161-L203
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java
DockerCloud.appendContainerConfig
private void appendContainerConfig(DockerSlaveTemplate slaveTemplate, CreateContainerCmd containerConfig) { Map<String, String> labels = containerConfig.getLabels(); if (labels == null) labels = new HashMap<>(); labels.put(DOCKER_CLOUD_LABEL, getDisplayName()); labels.put(DOCKER_TEMPLATE_LABEL, slaveTemplate.getId()); containerConfig.withLabels(labels); }
java
private void appendContainerConfig(DockerSlaveTemplate slaveTemplate, CreateContainerCmd containerConfig) { Map<String, String> labels = containerConfig.getLabels(); if (labels == null) labels = new HashMap<>(); labels.put(DOCKER_CLOUD_LABEL, getDisplayName()); labels.put(DOCKER_TEMPLATE_LABEL, slaveTemplate.getId()); containerConfig.withLabels(labels); }
[ "private", "void", "appendContainerConfig", "(", "DockerSlaveTemplate", "slaveTemplate", ",", "CreateContainerCmd", "containerConfig", ")", "{", "Map", "<", "String", ",", "String", ">", "labels", "=", "containerConfig", ".", "getLabels", "(", ")", ";", "if", "(",...
Cloud specific container config options
[ "Cloud", "specific", "container", "config", "options" ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java#L209-L217
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java
DockerCloud.determineOsType
private OsType determineOsType(String imageId) { InspectImageResponse ir = getClient().inspectImageCmd(imageId).exec(); if ("linux".equalsIgnoreCase(ir.getOs())) { LOG.trace("Detected LINUX operating system for image: {}", imageId); return OsType.LINUX; } else if ("windows".equalsIgnoreCase(ir.getOs())) { LOG.trace("Detected WINDOWS operating system for image: {}", imageId); return OsType.WINDOWS; } else { LOG.trace("Detected OTHER operating system ({}) for image: {}", ir.getOs(), imageId); return OsType.OTHER; } }
java
private OsType determineOsType(String imageId) { InspectImageResponse ir = getClient().inspectImageCmd(imageId).exec(); if ("linux".equalsIgnoreCase(ir.getOs())) { LOG.trace("Detected LINUX operating system for image: {}", imageId); return OsType.LINUX; } else if ("windows".equalsIgnoreCase(ir.getOs())) { LOG.trace("Detected WINDOWS operating system for image: {}", imageId); return OsType.WINDOWS; } else { LOG.trace("Detected OTHER operating system ({}) for image: {}", ir.getOs(), imageId); return OsType.OTHER; } }
[ "private", "OsType", "determineOsType", "(", "String", "imageId", ")", "{", "InspectImageResponse", "ir", "=", "getClient", "(", ")", ".", "inspectImageCmd", "(", "imageId", ")", ".", "exec", "(", ")", ";", "if", "(", "\"linux\"", ".", "equalsIgnoreCase", "(...
Determine the operating system associated with an image.
[ "Determine", "the", "operating", "system", "associated", "with", "an", "image", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java#L272-L284
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java
DockerCloud.countCurrentDockerSlaves
public int countCurrentDockerSlaves(final DockerSlaveTemplate template) throws Exception { int count = 0; List<Container> containers = getClient().listContainersCmd().exec(); for (Container container : containers) { final Map<String, String> labels = container.getLabels(); if (labels.containsKey(DOCKER_CLOUD_LABEL) && labels.get(DOCKER_CLOUD_LABEL).equals(getDisplayName())) { if (template == null) { // count only total cloud capacity count++; } else if (labels.containsKey(DOCKER_TEMPLATE_LABEL) && labels.get(DOCKER_TEMPLATE_LABEL).equals(template.getId())) { count++; } } } return count; }
java
public int countCurrentDockerSlaves(final DockerSlaveTemplate template) throws Exception { int count = 0; List<Container> containers = getClient().listContainersCmd().exec(); for (Container container : containers) { final Map<String, String> labels = container.getLabels(); if (labels.containsKey(DOCKER_CLOUD_LABEL) && labels.get(DOCKER_CLOUD_LABEL).equals(getDisplayName())) { if (template == null) { // count only total cloud capacity count++; } else if (labels.containsKey(DOCKER_TEMPLATE_LABEL) && labels.get(DOCKER_TEMPLATE_LABEL).equals(template.getId())) { count++; } } } return count; }
[ "public", "int", "countCurrentDockerSlaves", "(", "final", "DockerSlaveTemplate", "template", ")", "throws", "Exception", "{", "int", "count", "=", "0", ";", "List", "<", "Container", ">", "containers", "=", "getClient", "(", ")", ".", "listContainersCmd", "(", ...
Counts the number of instances in Docker currently running that are using the specified template. @param template If null, then all instances are counted.
[ "Counts", "the", "number", "of", "instances", "in", "Docker", "currently", "running", "that", "are", "using", "the", "specified", "template", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java#L291-L310
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java
DockerCloud.addProvisionedSlave
private synchronized boolean addProvisionedSlave(DockerSlaveTemplate template) throws Exception { final DockerContainerLifecycle dockerCreateContainer = template.getDockerContainerLifecycle(); String dockerImageName = dockerCreateContainer.getImage(); int templateCapacity = template.getMaxCapacity(); int estimatedTotalSlaves = countCurrentDockerSlaves(null); int estimatedAmiSlaves = countCurrentDockerSlaves(template); synchronized (provisionedImages) { int currentProvisioning = 0; if (provisionedImages.containsKey(template)) { currentProvisioning = provisionedImages.get(template); } for (int amiCount : provisionedImages.values()) { estimatedTotalSlaves += amiCount; } estimatedAmiSlaves += currentProvisioning; if (estimatedTotalSlaves >= getContainerCap()) { LOG.info("Not Provisioning '{}'; Server '{}' full with '{}' container(s)", dockerImageName, name, getContainerCap()); return false; // maxed out } if (templateCapacity != 0 && estimatedAmiSlaves >= templateCapacity) { LOG.info("Not Provisioning '{}'. Instance limit of '{}' reached on server '{}'", dockerImageName, templateCapacity, name); return false; // maxed out } LOG.info("Provisioning '{}' number '{}' on '{}'; Total containers: '{}'", dockerImageName, estimatedAmiSlaves, name, estimatedTotalSlaves); provisionedImages.put(template, currentProvisioning + 1); return true; } }
java
private synchronized boolean addProvisionedSlave(DockerSlaveTemplate template) throws Exception { final DockerContainerLifecycle dockerCreateContainer = template.getDockerContainerLifecycle(); String dockerImageName = dockerCreateContainer.getImage(); int templateCapacity = template.getMaxCapacity(); int estimatedTotalSlaves = countCurrentDockerSlaves(null); int estimatedAmiSlaves = countCurrentDockerSlaves(template); synchronized (provisionedImages) { int currentProvisioning = 0; if (provisionedImages.containsKey(template)) { currentProvisioning = provisionedImages.get(template); } for (int amiCount : provisionedImages.values()) { estimatedTotalSlaves += amiCount; } estimatedAmiSlaves += currentProvisioning; if (estimatedTotalSlaves >= getContainerCap()) { LOG.info("Not Provisioning '{}'; Server '{}' full with '{}' container(s)", dockerImageName, name, getContainerCap()); return false; // maxed out } if (templateCapacity != 0 && estimatedAmiSlaves >= templateCapacity) { LOG.info("Not Provisioning '{}'. Instance limit of '{}' reached on server '{}'", dockerImageName, templateCapacity, name); return false; // maxed out } LOG.info("Provisioning '{}' number '{}' on '{}'; Total containers: '{}'", dockerImageName, estimatedAmiSlaves, name, estimatedTotalSlaves); provisionedImages.put(template, currentProvisioning + 1); return true; } }
[ "private", "synchronized", "boolean", "addProvisionedSlave", "(", "DockerSlaveTemplate", "template", ")", "throws", "Exception", "{", "final", "DockerContainerLifecycle", "dockerCreateContainer", "=", "template", ".", "getDockerContainerLifecycle", "(", ")", ";", "String", ...
Check not too many already running.
[ "Check", "not", "too", "many", "already", "running", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerCloud.java#L315-L353
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerFunctions.java
DockerFunctions.getDockerComputerLauncherDescriptors
public static List<Descriptor<ComputerLauncher>> getDockerComputerLauncherDescriptors() { List<Descriptor<ComputerLauncher>> launchers = new ArrayList<>(); launchers.add(getInstance().getDescriptor(DockerComputerSSHLauncher.class)); launchers.add(getInstance().getDescriptor(DockerComputerJNLPLauncher.class)); launchers.add(getInstance().getDescriptor(DockerComputerIOLauncher.class)); return launchers; }
java
public static List<Descriptor<ComputerLauncher>> getDockerComputerLauncherDescriptors() { List<Descriptor<ComputerLauncher>> launchers = new ArrayList<>(); launchers.add(getInstance().getDescriptor(DockerComputerSSHLauncher.class)); launchers.add(getInstance().getDescriptor(DockerComputerJNLPLauncher.class)); launchers.add(getInstance().getDescriptor(DockerComputerIOLauncher.class)); return launchers; }
[ "public", "static", "List", "<", "Descriptor", "<", "ComputerLauncher", ">", ">", "getDockerComputerLauncherDescriptors", "(", ")", "{", "List", "<", "Descriptor", "<", "ComputerLauncher", ">>", "launchers", "=", "new", "ArrayList", "<>", "(", ")", ";", "launche...
Only this plugin specific launchers.
[ "Only", "this", "plugin", "specific", "launchers", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerFunctions.java#L58-L66
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerFunctions.java
DockerFunctions.getDockerRetentionStrategyDescriptors
public static List<Descriptor<RetentionStrategy<?>>> getDockerRetentionStrategyDescriptors() { List<Descriptor<RetentionStrategy<?>>> strategies = new ArrayList<>(); strategies.add(getInstance().getDescriptor(DockerOnceRetentionStrategy.class)); strategies.add(getInstance().getDescriptor(DockerCloudRetentionStrategy.class)); strategies.add(getInstance().getDescriptor(DockerComputerIOLauncher.class)); return strategies; }
java
public static List<Descriptor<RetentionStrategy<?>>> getDockerRetentionStrategyDescriptors() { List<Descriptor<RetentionStrategy<?>>> strategies = new ArrayList<>(); strategies.add(getInstance().getDescriptor(DockerOnceRetentionStrategy.class)); strategies.add(getInstance().getDescriptor(DockerCloudRetentionStrategy.class)); strategies.add(getInstance().getDescriptor(DockerComputerIOLauncher.class)); return strategies; }
[ "public", "static", "List", "<", "Descriptor", "<", "RetentionStrategy", "<", "?", ">", ">", ">", "getDockerRetentionStrategyDescriptors", "(", ")", "{", "List", "<", "Descriptor", "<", "RetentionStrategy", "<", "?", ">", ">", ">", "strategies", "=", "new", ...
Only this plugin specific strategies.
[ "Only", "this", "plugin", "specific", "strategies", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerFunctions.java#L71-L79
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerFunctions.java
DockerFunctions.getAllDockerClouds
@Nonnull public static List<DockerCloud> getAllDockerClouds() { return getInstance().clouds.stream() .filter(Objects::nonNull) .filter(DockerCloud.class::isInstance) .map(cloud -> (DockerCloud) cloud) .collect(Collectors.toList()); }
java
@Nonnull public static List<DockerCloud> getAllDockerClouds() { return getInstance().clouds.stream() .filter(Objects::nonNull) .filter(DockerCloud.class::isInstance) .map(cloud -> (DockerCloud) cloud) .collect(Collectors.toList()); }
[ "@", "Nonnull", "public", "static", "List", "<", "DockerCloud", ">", "getAllDockerClouds", "(", ")", "{", "return", "getInstance", "(", ")", ".", "clouds", ".", "stream", "(", ")", ".", "filter", "(", "Objects", "::", "nonNull", ")", ".", "filter", "(", ...
Get the list of Docker servers. @return the list as a LinkedList of DockerCloud
[ "Get", "the", "list", "of", "Docker", "servers", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/DockerFunctions.java#L87-L94
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerContainerRestartPolicy.java
DockerContainerRestartPolicy.getRestartPolicy
@CheckForNull public RestartPolicy getRestartPolicy() { if (isNull(policyName)) return null; return RestartPolicy.parse(String.format("%s:%d", policyName.toString().toLowerCase(Locale.ENGLISH).replace("_", "-"), getMaximumRetryCount())); }
java
@CheckForNull public RestartPolicy getRestartPolicy() { if (isNull(policyName)) return null; return RestartPolicy.parse(String.format("%s:%d", policyName.toString().toLowerCase(Locale.ENGLISH).replace("_", "-"), getMaximumRetryCount())); }
[ "@", "CheckForNull", "public", "RestartPolicy", "getRestartPolicy", "(", ")", "{", "if", "(", "isNull", "(", "policyName", ")", ")", "return", "null", ";", "return", "RestartPolicy", ".", "parse", "(", "String", ".", "format", "(", "\"%s:%d\"", ",", "policyN...
runtime ABI dependency on docker-java
[ "runtime", "ABI", "dependency", "on", "docker", "-", "java" ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/commons/DockerContainerRestartPolicy.java#L60-L66
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/VariableUtils.java
VariableUtils.resolveVar
public static String resolveVar(String var, Run run, TaskListener taskListener) { String resolvedVar = var; try { final EnvVars envVars = run.getEnvironment(taskListener); resolvedVar = envVars.expand(var); } catch (IOException | InterruptedException e) { LOG.warn("Can't resolve variable " + var + " for {}", run, e); } return resolvedVar; }
java
public static String resolveVar(String var, Run run, TaskListener taskListener) { String resolvedVar = var; try { final EnvVars envVars = run.getEnvironment(taskListener); resolvedVar = envVars.expand(var); } catch (IOException | InterruptedException e) { LOG.warn("Can't resolve variable " + var + " for {}", run, e); } return resolvedVar; }
[ "public", "static", "String", "resolveVar", "(", "String", "var", ",", "Run", "run", ",", "TaskListener", "taskListener", ")", "{", "String", "resolvedVar", "=", "var", ";", "try", "{", "final", "EnvVars", "envVars", "=", "run", ".", "getEnvironment", "(", ...
Resolve on remoting side during execution. Because node may have some specific node vars.
[ "Resolve", "on", "remoting", "side", "during", "execution", ".", "Because", "node", "may", "have", "some", "specific", "node", "vars", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/utils/VariableUtils.java#L24-L33
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-its/src/main/java/hudson/cli/DockerCLI.java
DockerCLI.getCliTcpPort
protected CliPort getCliTcpPort(String jenkinsAddr) throws IOException { URL jenkinsUrl = new URL(jenkinsAddr); if (jenkinsUrl.getHost() == null || jenkinsUrl.getHost().length() == 0) { throw new IOException("Invalid URL: " + jenkinsAddr); } URLConnection head = jenkinsUrl.openConnection(); try { head.connect(); } catch (IOException e) { throw (IOException) new IOException("Failed to connect to " + jenkinsAddr).initCause(e); } String h = head.getHeaderField("X-Jenkins-CLI-Host"); if (h == null) h = head.getURL().getHost(); String identity = head.getHeaderField("X-Instance-Identity"); flushURLConnection(head); return new CliPort(new InetSocketAddress(h, exposedPort), identity, 2); }
java
protected CliPort getCliTcpPort(String jenkinsAddr) throws IOException { URL jenkinsUrl = new URL(jenkinsAddr); if (jenkinsUrl.getHost() == null || jenkinsUrl.getHost().length() == 0) { throw new IOException("Invalid URL: " + jenkinsAddr); } URLConnection head = jenkinsUrl.openConnection(); try { head.connect(); } catch (IOException e) { throw (IOException) new IOException("Failed to connect to " + jenkinsAddr).initCause(e); } String h = head.getHeaderField("X-Jenkins-CLI-Host"); if (h == null) h = head.getURL().getHost(); String identity = head.getHeaderField("X-Instance-Identity"); flushURLConnection(head); return new CliPort(new InetSocketAddress(h, exposedPort), identity, 2); }
[ "protected", "CliPort", "getCliTcpPort", "(", "String", "jenkinsAddr", ")", "throws", "IOException", "{", "URL", "jenkinsUrl", "=", "new", "URL", "(", "jenkinsAddr", ")", ";", "if", "(", "jenkinsUrl", ".", "getHost", "(", ")", "==", "null", "||", "jenkinsUrl...
If the server advertises CLI endpoint, returns its location.
[ "If", "the", "server", "advertises", "CLI", "endpoint", "returns", "its", "location", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/hudson/cli/DockerCLI.java#L178-L198
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-its/src/main/java/hudson/cli/DockerCLI.java
DockerCLI.close
public void close() throws IOException, InterruptedException { channel.close(); channel.join(); if (ownsPool) pool.shutdown(); for (Closeable c : closables) c.close(); }
java
public void close() throws IOException, InterruptedException { channel.close(); channel.join(); if (ownsPool) pool.shutdown(); for (Closeable c : closables) c.close(); }
[ "public", "void", "close", "(", ")", "throws", "IOException", ",", "InterruptedException", "{", "channel", ".", "close", "(", ")", ";", "channel", ".", "join", "(", ")", ";", "if", "(", "ownsPool", ")", "pool", ".", "shutdown", "(", ")", ";", "for", ...
Shuts down the channel and closes the underlying connection.
[ "Shuts", "down", "the", "channel", "and", "closes", "the", "underlying", "connection", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/hudson/cli/DockerCLI.java#L232-L239
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-its/src/main/java/hudson/cli/DockerCLI.java
DockerCLI.upgrade
public void upgrade() { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (execute(Arrays.asList("groovy", "="), new ByteArrayInputStream( "hudson.remoting.Channel.current().setRestricted(false)" .getBytes(defaultCharset())), out, out) != 0) { throw new SecurityException(out.toString()); // failed to upgrade } }
java
public void upgrade() { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (execute(Arrays.asList("groovy", "="), new ByteArrayInputStream( "hudson.remoting.Channel.current().setRestricted(false)" .getBytes(defaultCharset())), out, out) != 0) { throw new SecurityException(out.toString()); // failed to upgrade } }
[ "public", "void", "upgrade", "(", ")", "{", "ByteArrayOutputStream", "out", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "if", "(", "execute", "(", "Arrays", ".", "asList", "(", "\"groovy\"", ",", "\"=\"", ")", ",", "new", "ByteArrayInputStream", "(",...
Attempts to lift the security restriction on the underlying channel. This requires the administer privilege on the server. @throws SecurityException If we fail to upgrade the connection.
[ "Attempts", "to", "lift", "the", "security", "restriction", "on", "the", "underlying", "channel", ".", "This", "requires", "the", "administer", "privilege", "on", "the", "server", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/hudson/cli/DockerCLI.java#L258-L267
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/steps/DockerShellStep.java
DockerShellStep.getEnvVars
protected static EnvVars getEnvVars(Run run, TaskListener listener) throws IOException, InterruptedException { final EnvVars envVars = run.getCharacteristicEnvVars(); // from run.getEnvironment(listener) but without computer vars for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) { // job vars ec.buildEnvironmentFor(run.getParent(), envVars, listener); // build vars if (ec instanceof CoreEnvironmentContributor) { // exclude executor computer related vars envVars.put("BUILD_DISPLAY_NAME", run.getDisplayName()); String rootUrl = Jenkins.getInstance().getRootUrl(); if (rootUrl != null) { envVars.put("BUILD_URL", rootUrl + run.getUrl()); } // and remove useless job var from CoreEnvironmentContributor envVars.remove("JENKINS_HOME"); envVars.remove("HUDSON_HOME"); } else { ec.buildEnvironmentFor(run, envVars, listener); // build vars } } return envVars; }
java
protected static EnvVars getEnvVars(Run run, TaskListener listener) throws IOException, InterruptedException { final EnvVars envVars = run.getCharacteristicEnvVars(); // from run.getEnvironment(listener) but without computer vars for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) { // job vars ec.buildEnvironmentFor(run.getParent(), envVars, listener); // build vars if (ec instanceof CoreEnvironmentContributor) { // exclude executor computer related vars envVars.put("BUILD_DISPLAY_NAME", run.getDisplayName()); String rootUrl = Jenkins.getInstance().getRootUrl(); if (rootUrl != null) { envVars.put("BUILD_URL", rootUrl + run.getUrl()); } // and remove useless job var from CoreEnvironmentContributor envVars.remove("JENKINS_HOME"); envVars.remove("HUDSON_HOME"); } else { ec.buildEnvironmentFor(run, envVars, listener); // build vars } } return envVars; }
[ "protected", "static", "EnvVars", "getEnvVars", "(", "Run", "run", ",", "TaskListener", "listener", ")", "throws", "IOException", ",", "InterruptedException", "{", "final", "EnvVars", "envVars", "=", "run", ".", "getCharacteristicEnvVars", "(", ")", ";", "// from ...
Return all job related vars without executor vars. I.e. slave is running in osx, but docker image for shell is linux.
[ "Return", "all", "job", "related", "vars", "without", "executor", "vars", ".", "I", ".", "e", ".", "slave", "is", "running", "in", "osx", "but", "docker", "image", "for", "shell", "is", "linux", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/steps/DockerShellStep.java#L306-L334
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/steps/DockerShellStep.java
DockerShellStep.insertLabels
protected static void insertLabels(CreateContainerCmd containerConfig, Run run) { // add tags Map<String, String> labels = containerConfig.getLabels(); if (labels == null) labels = new HashMap<>(); labels.put("YAD_PLUGIN", DockerShellStep.class.getName()); labels.put("JENKINS_JOB_BASE_NAME", run.getParent().getName()); labels.put("JENKINS_INSTANCE_IDENTITY", new String(encodeBase64(InstanceIdentity.get().getPublic().getEncoded()), UTF_8)); containerConfig.withLabels(labels); }
java
protected static void insertLabels(CreateContainerCmd containerConfig, Run run) { // add tags Map<String, String> labels = containerConfig.getLabels(); if (labels == null) labels = new HashMap<>(); labels.put("YAD_PLUGIN", DockerShellStep.class.getName()); labels.put("JENKINS_JOB_BASE_NAME", run.getParent().getName()); labels.put("JENKINS_INSTANCE_IDENTITY", new String(encodeBase64(InstanceIdentity.get().getPublic().getEncoded()), UTF_8)); containerConfig.withLabels(labels); }
[ "protected", "static", "void", "insertLabels", "(", "CreateContainerCmd", "containerConfig", ",", "Run", "run", ")", "{", "// add tags", "Map", "<", "String", ",", "String", ">", "labels", "=", "containerConfig", ".", "getLabels", "(", ")", ";", "if", "(", "...
Append some tags to identify who created this container.
[ "Append", "some", "tags", "to", "identify", "who", "created", "this", "container", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/steps/DockerShellStep.java#L339-L350
train
KostyaSha/yet-another-docker-plugin
yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerProvisioningStrategy.java
DockerProvisioningStrategy.setEnabled
public void setEnabled(boolean enabled) { final ExtensionList<NodeProvisioner.Strategy> strategies = lookup(NodeProvisioner.Strategy.class); DockerProvisioningStrategy strategy = strategies.get(DockerProvisioningStrategy.class); if (isNull(strategy)) { LOG.debug("YAD strategy was null, creating new."); strategy = new DockerProvisioningStrategy(); } else { LOG.debug("Removing YAD strategy."); strategies.remove(strategy); } LOG.debug("Inserting YAD strategy at position 0"); strategies.add(0, strategy); }
java
public void setEnabled(boolean enabled) { final ExtensionList<NodeProvisioner.Strategy> strategies = lookup(NodeProvisioner.Strategy.class); DockerProvisioningStrategy strategy = strategies.get(DockerProvisioningStrategy.class); if (isNull(strategy)) { LOG.debug("YAD strategy was null, creating new."); strategy = new DockerProvisioningStrategy(); } else { LOG.debug("Removing YAD strategy."); strategies.remove(strategy); } LOG.debug("Inserting YAD strategy at position 0"); strategies.add(0, strategy); }
[ "public", "void", "setEnabled", "(", "boolean", "enabled", ")", "{", "final", "ExtensionList", "<", "NodeProvisioner", ".", "Strategy", ">", "strategies", "=", "lookup", "(", "NodeProvisioner", ".", "Strategy", ".", "class", ")", ";", "DockerProvisioningStrategy",...
For groovy.
[ "For", "groovy", "." ]
40b12e39ff94c3834cff7e028c3dd01c88e87d77
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-plugin/src/main/java/com/github/kostyasha/yad/DockerProvisioningStrategy.java#L38-L52
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/dht/Range.java
Range.isWrapAround
public static <T extends RingPosition<T>> boolean isWrapAround(T left, T right) { return left.compareTo(right) >= 0; }
java
public static <T extends RingPosition<T>> boolean isWrapAround(T left, T right) { return left.compareTo(right) >= 0; }
[ "public", "static", "<", "T", "extends", "RingPosition", "<", "T", ">", ">", "boolean", "isWrapAround", "(", "T", "left", ",", "T", "right", ")", "{", "return", "left", ".", "compareTo", "(", "right", ")", ">=", "0", ";", "}" ]
Tells if the given range is a wrap around.
[ "Tells", "if", "the", "given", "range", "is", "a", "wrap", "around", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/dht/Range.java#L258-L261
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/dht/Range.java
Range.subtractContained
private ArrayList<Range<T>> subtractContained(Range<T> contained) { ArrayList<Range<T>> difference = new ArrayList<Range<T>>(2); if (!left.equals(contained.left)) difference.add(new Range<T>(left, contained.left, partitioner)); if (!right.equals(contained.right)) difference.add(new Range<T>(contained.right, right, partitioner)); return difference; }
java
private ArrayList<Range<T>> subtractContained(Range<T> contained) { ArrayList<Range<T>> difference = new ArrayList<Range<T>>(2); if (!left.equals(contained.left)) difference.add(new Range<T>(left, contained.left, partitioner)); if (!right.equals(contained.right)) difference.add(new Range<T>(contained.right, right, partitioner)); return difference; }
[ "private", "ArrayList", "<", "Range", "<", "T", ">", ">", "subtractContained", "(", "Range", "<", "T", ">", "contained", ")", "{", "ArrayList", "<", "Range", "<", "T", ">>", "difference", "=", "new", "ArrayList", "<", "Range", "<", "T", ">", ">", "("...
Subtracts a portion of this range. @param contained The range to subtract from this. It must be totally contained by this range. @return An ArrayList of the Ranges left after subtracting contained from this.
[ "Subtracts", "a", "portion", "of", "this", "range", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/dht/Range.java#L285-L294
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/dht/Range.java
Range.deoverlap
private static <T extends RingPosition<T>> List<Range<T>> deoverlap(List<Range<T>> ranges) { if (ranges.isEmpty()) return ranges; List<Range<T>> output = new ArrayList<Range<T>>(); Iterator<Range<T>> iter = ranges.iterator(); Range<T> current = iter.next(); @SuppressWarnings("unchecked") T min = (T) current.partitioner.minValue(current.left.getClass()); while (iter.hasNext()) { // If current goes to the end of the ring, we're done if (current.right.equals(min)) { // If one range is the full range, we return only that if (current.left.equals(min)) return Collections.<Range<T>>singletonList(current); output.add(new Range<T>(current.left, min)); return output; } Range<T> next = iter.next(); // if next left is equal to current right, we do not intersect per se, but replacing (A, B] and (B, C] by (A, C] is // legit, and since this avoid special casing and will result in more "optimal" ranges, we do the transformation if (next.left.compareTo(current.right) <= 0) { // We do overlap // (we've handled current.right.equals(min) already) if (next.right.equals(min) || current.right.compareTo(next.right) < 0) current = new Range<T>(current.left, next.right); } else { output.add(current); current = next; } } output.add(current); return output; }
java
private static <T extends RingPosition<T>> List<Range<T>> deoverlap(List<Range<T>> ranges) { if (ranges.isEmpty()) return ranges; List<Range<T>> output = new ArrayList<Range<T>>(); Iterator<Range<T>> iter = ranges.iterator(); Range<T> current = iter.next(); @SuppressWarnings("unchecked") T min = (T) current.partitioner.minValue(current.left.getClass()); while (iter.hasNext()) { // If current goes to the end of the ring, we're done if (current.right.equals(min)) { // If one range is the full range, we return only that if (current.left.equals(min)) return Collections.<Range<T>>singletonList(current); output.add(new Range<T>(current.left, min)); return output; } Range<T> next = iter.next(); // if next left is equal to current right, we do not intersect per se, but replacing (A, B] and (B, C] by (A, C] is // legit, and since this avoid special casing and will result in more "optimal" ranges, we do the transformation if (next.left.compareTo(current.right) <= 0) { // We do overlap // (we've handled current.right.equals(min) already) if (next.right.equals(min) || current.right.compareTo(next.right) < 0) current = new Range<T>(current.left, next.right); } else { output.add(current); current = next; } } output.add(current); return output; }
[ "private", "static", "<", "T", "extends", "RingPosition", "<", "T", ">", ">", "List", "<", "Range", "<", "T", ">", ">", "deoverlap", "(", "List", "<", "Range", "<", "T", ">", ">", "ranges", ")", "{", "if", "(", "ranges", ".", "isEmpty", "(", ")",...
Given a list of unwrapped ranges sorted by left position, return an equivalent list of ranges but with no overlapping ranges.
[ "Given", "a", "list", "of", "unwrapped", "ranges", "sorted", "by", "left", "position", "return", "an", "equivalent", "list", "of", "ranges", "but", "with", "no", "overlapping", "ranges", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/dht/Range.java#L423-L467
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/dht/Range.java
Range.makeRowRange
public static Range<RowPosition> makeRowRange(Token left, Token right, IPartitioner partitioner) { return new Range<RowPosition>(left.maxKeyBound(partitioner), right.maxKeyBound(partitioner), partitioner); }
java
public static Range<RowPosition> makeRowRange(Token left, Token right, IPartitioner partitioner) { return new Range<RowPosition>(left.maxKeyBound(partitioner), right.maxKeyBound(partitioner), partitioner); }
[ "public", "static", "Range", "<", "RowPosition", ">", "makeRowRange", "(", "Token", "left", ",", "Token", "right", ",", "IPartitioner", "partitioner", ")", "{", "return", "new", "Range", "<", "RowPosition", ">", "(", "left", ".", "maxKeyBound", "(", "partiti...
Compute a range of keys corresponding to a given range of token.
[ "Compute", "a", "range", "of", "keys", "corresponding", "to", "a", "given", "range", "of", "token", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/dht/Range.java#L473-L476
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/AbstractNativeCell.java
AbstractNativeCell.compareTo
@Inline public final int compareTo(final Composite that) { if (isStatic() != that.isStatic()) { // Static sorts before non-static no matter what, except for empty which // always sort first if (isEmpty()) return that.isEmpty() ? 0 : -1; if (that.isEmpty()) return 1; return isStatic() ? -1 : 1; } int size = size(); int size2 = that.size(); int minSize = Math.min(size, size2); int startDelta = 0; int cellNamesOffset = nameDeltaOffset(size); for (int i = 0 ; i < minSize ; i++) { int endDelta = i < size - 1 ? getShort(nameDeltaOffset(i + 1)) : valueStartOffset() - cellNamesOffset; long offset = peer + cellNamesOffset + startDelta; int length = endDelta - startDelta; int cmp = FastByteOperations.UnsafeOperations.compareTo(null, offset, length, that.get(i)); if (cmp != 0) return cmp; startDelta = endDelta; } EOC eoc = that.eoc(); if (size == size2) return this.eoc().compareTo(eoc); return size < size2 ? this.eoc().prefixComparisonResult : -eoc.prefixComparisonResult; }
java
@Inline public final int compareTo(final Composite that) { if (isStatic() != that.isStatic()) { // Static sorts before non-static no matter what, except for empty which // always sort first if (isEmpty()) return that.isEmpty() ? 0 : -1; if (that.isEmpty()) return 1; return isStatic() ? -1 : 1; } int size = size(); int size2 = that.size(); int minSize = Math.min(size, size2); int startDelta = 0; int cellNamesOffset = nameDeltaOffset(size); for (int i = 0 ; i < minSize ; i++) { int endDelta = i < size - 1 ? getShort(nameDeltaOffset(i + 1)) : valueStartOffset() - cellNamesOffset; long offset = peer + cellNamesOffset + startDelta; int length = endDelta - startDelta; int cmp = FastByteOperations.UnsafeOperations.compareTo(null, offset, length, that.get(i)); if (cmp != 0) return cmp; startDelta = endDelta; } EOC eoc = that.eoc(); if (size == size2) return this.eoc().compareTo(eoc); return size < size2 ? this.eoc().prefixComparisonResult : -eoc.prefixComparisonResult; }
[ "@", "Inline", "public", "final", "int", "compareTo", "(", "final", "Composite", "that", ")", "{", "if", "(", "isStatic", "(", ")", "!=", "that", ".", "isStatic", "(", ")", ")", "{", "// Static sorts before non-static no matter what, except for empty which", "// a...
requires isByteOrderComparable to be true. Compares the name components only; ; may need to compare EOC etc still
[ "requires", "isByteOrderComparable", "to", "be", "true", ".", "Compares", "the", "name", "components", "only", ";", ";", "may", "need", "to", "compare", "EOC", "etc", "still" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/AbstractNativeCell.java#L662-L697
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/CounterMutation.java
CounterMutation.processModifications
private ColumnFamily processModifications(ColumnFamily changesCF) { ColumnFamilyStore cfs = Keyspace.open(getKeyspaceName()).getColumnFamilyStore(changesCF.id()); ColumnFamily resultCF = changesCF.cloneMeShallow(); List<CounterUpdateCell> counterUpdateCells = new ArrayList<>(changesCF.getColumnCount()); for (Cell cell : changesCF) { if (cell instanceof CounterUpdateCell) counterUpdateCells.add((CounterUpdateCell)cell); else resultCF.addColumn(cell); } if (counterUpdateCells.isEmpty()) return resultCF; // only DELETEs ClockAndCount[] currentValues = getCurrentValues(counterUpdateCells, cfs); for (int i = 0; i < counterUpdateCells.size(); i++) { ClockAndCount currentValue = currentValues[i]; CounterUpdateCell update = counterUpdateCells.get(i); long clock = currentValue.clock + 1L; long count = currentValue.count + update.delta(); resultCF.addColumn(new BufferCounterCell(update.name(), CounterContext.instance().createGlobal(CounterId.getLocalId(), clock, count), update.timestamp())); } return resultCF; }
java
private ColumnFamily processModifications(ColumnFamily changesCF) { ColumnFamilyStore cfs = Keyspace.open(getKeyspaceName()).getColumnFamilyStore(changesCF.id()); ColumnFamily resultCF = changesCF.cloneMeShallow(); List<CounterUpdateCell> counterUpdateCells = new ArrayList<>(changesCF.getColumnCount()); for (Cell cell : changesCF) { if (cell instanceof CounterUpdateCell) counterUpdateCells.add((CounterUpdateCell)cell); else resultCF.addColumn(cell); } if (counterUpdateCells.isEmpty()) return resultCF; // only DELETEs ClockAndCount[] currentValues = getCurrentValues(counterUpdateCells, cfs); for (int i = 0; i < counterUpdateCells.size(); i++) { ClockAndCount currentValue = currentValues[i]; CounterUpdateCell update = counterUpdateCells.get(i); long clock = currentValue.clock + 1L; long count = currentValue.count + update.delta(); resultCF.addColumn(new BufferCounterCell(update.name(), CounterContext.instance().createGlobal(CounterId.getLocalId(), clock, count), update.timestamp())); } return resultCF; }
[ "private", "ColumnFamily", "processModifications", "(", "ColumnFamily", "changesCF", ")", "{", "ColumnFamilyStore", "cfs", "=", "Keyspace", ".", "open", "(", "getKeyspaceName", "(", ")", ")", ".", "getColumnFamilyStore", "(", "changesCF", ".", "id", "(", ")", ")...
Replaces all the CounterUpdateCell-s with updated regular CounterCell-s
[ "Replaces", "all", "the", "CounterUpdateCell", "-", "s", "with", "updated", "regular", "CounterCell", "-", "s" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/CounterMutation.java#L179-L212
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/CounterMutation.java
CounterMutation.getCurrentValuesFromCache
private int getCurrentValuesFromCache(List<CounterUpdateCell> counterUpdateCells, ColumnFamilyStore cfs, ClockAndCount[] currentValues) { int cacheMisses = 0; for (int i = 0; i < counterUpdateCells.size(); i++) { ClockAndCount cached = cfs.getCachedCounter(key(), counterUpdateCells.get(i).name()); if (cached != null) currentValues[i] = cached; else cacheMisses++; } return cacheMisses; }
java
private int getCurrentValuesFromCache(List<CounterUpdateCell> counterUpdateCells, ColumnFamilyStore cfs, ClockAndCount[] currentValues) { int cacheMisses = 0; for (int i = 0; i < counterUpdateCells.size(); i++) { ClockAndCount cached = cfs.getCachedCounter(key(), counterUpdateCells.get(i).name()); if (cached != null) currentValues[i] = cached; else cacheMisses++; } return cacheMisses; }
[ "private", "int", "getCurrentValuesFromCache", "(", "List", "<", "CounterUpdateCell", ">", "counterUpdateCells", ",", "ColumnFamilyStore", "cfs", ",", "ClockAndCount", "[", "]", "currentValues", ")", "{", "int", "cacheMisses", "=", "0", ";", "for", "(", "int", "...
Returns the count of cache misses.
[ "Returns", "the", "count", "of", "cache", "misses", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/CounterMutation.java#L235-L249
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/db/CounterMutation.java
CounterMutation.getCurrentValuesFromCFS
private void getCurrentValuesFromCFS(List<CounterUpdateCell> counterUpdateCells, ColumnFamilyStore cfs, ClockAndCount[] currentValues) { SortedSet<CellName> names = new TreeSet<>(cfs.metadata.comparator); for (int i = 0; i < currentValues.length; i++) if (currentValues[i] == null) names.add(counterUpdateCells.get(i).name()); ReadCommand cmd = new SliceByNamesReadCommand(getKeyspaceName(), key(), cfs.metadata.cfName, Long.MIN_VALUE, new NamesQueryFilter(names)); Row row = cmd.getRow(cfs.keyspace); ColumnFamily cf = row == null ? null : row.cf; for (int i = 0; i < currentValues.length; i++) { if (currentValues[i] != null) continue; Cell cell = cf == null ? null : cf.getColumn(counterUpdateCells.get(i).name()); if (cell == null || !cell.isLive()) // absent or a tombstone. currentValues[i] = ClockAndCount.BLANK; else currentValues[i] = CounterContext.instance().getLocalClockAndCount(cell.value()); } }
java
private void getCurrentValuesFromCFS(List<CounterUpdateCell> counterUpdateCells, ColumnFamilyStore cfs, ClockAndCount[] currentValues) { SortedSet<CellName> names = new TreeSet<>(cfs.metadata.comparator); for (int i = 0; i < currentValues.length; i++) if (currentValues[i] == null) names.add(counterUpdateCells.get(i).name()); ReadCommand cmd = new SliceByNamesReadCommand(getKeyspaceName(), key(), cfs.metadata.cfName, Long.MIN_VALUE, new NamesQueryFilter(names)); Row row = cmd.getRow(cfs.keyspace); ColumnFamily cf = row == null ? null : row.cf; for (int i = 0; i < currentValues.length; i++) { if (currentValues[i] != null) continue; Cell cell = cf == null ? null : cf.getColumn(counterUpdateCells.get(i).name()); if (cell == null || !cell.isLive()) // absent or a tombstone. currentValues[i] = ClockAndCount.BLANK; else currentValues[i] = CounterContext.instance().getLocalClockAndCount(cell.value()); } }
[ "private", "void", "getCurrentValuesFromCFS", "(", "List", "<", "CounterUpdateCell", ">", "counterUpdateCells", ",", "ColumnFamilyStore", "cfs", ",", "ClockAndCount", "[", "]", "currentValues", ")", "{", "SortedSet", "<", "CellName", ">", "names", "=", "new", "Tre...
Reads the missing current values from the CFS.
[ "Reads", "the", "missing", "current", "values", "from", "the", "CFS", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/db/CounterMutation.java#L252-L276
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/functions/BytesConversionFcts.java
BytesConversionFcts.makeToBlobFunction
public static Function makeToBlobFunction(AbstractType<?> fromType) { String name = fromType.asCQL3Type() + "asblob"; return new AbstractFunction(name, BytesType.instance, fromType) { public ByteBuffer execute(List<ByteBuffer> parameters) { return parameters.get(0); } }; }
java
public static Function makeToBlobFunction(AbstractType<?> fromType) { String name = fromType.asCQL3Type() + "asblob"; return new AbstractFunction(name, BytesType.instance, fromType) { public ByteBuffer execute(List<ByteBuffer> parameters) { return parameters.get(0); } }; }
[ "public", "static", "Function", "makeToBlobFunction", "(", "AbstractType", "<", "?", ">", "fromType", ")", "{", "String", "name", "=", "fromType", ".", "asCQL3Type", "(", ")", "+", "\"asblob\"", ";", "return", "new", "AbstractFunction", "(", "name", ",", "By...
bytes internally. They only "trick" the type system.
[ "bytes", "internally", ".", "They", "only", "trick", "the", "type", "system", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/functions/BytesConversionFcts.java#L34-L44
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/cql3/CqlRecordWriter.java
RangeClient.run
public void run() { outer: while (run || !queue.isEmpty()) { List<ByteBuffer> bindVariables; try { bindVariables = queue.take(); } catch (InterruptedException e) { // re-check loop condition after interrupt continue; } Iterator<InetAddress> iter = endpoints.iterator(); while (true) { // send the mutation to the last-used endpoint. first time through, this will NPE harmlessly. try { int i = 0; int itemId = preparedStatement(client); while (bindVariables != null) { client.execute_prepared_cql3_query(itemId, bindVariables, ConsistencyLevel.ONE); i++; if (i >= batchThreshold) break; bindVariables = queue.poll(); } break; } catch (Exception e) { closeInternal(); if (!iter.hasNext()) { lastException = new IOException(e); break outer; } } // attempt to connect to a different endpoint try { InetAddress address = iter.next(); String host = address.getHostName(); int port = ConfigHelper.getOutputRpcPort(conf); client = CqlOutputFormat.createAuthenticatedClient(host, port, conf); } catch (Exception e) { closeInternal(); // TException means something unexpected went wrong to that endpoint, so // we should try again to another. Other exceptions (auth or invalid request) are fatal. if ((!(e instanceof TException)) || !iter.hasNext()) { lastException = new IOException(e); break outer; } } } } // close all our connections once we are done. closeInternal(); }
java
public void run() { outer: while (run || !queue.isEmpty()) { List<ByteBuffer> bindVariables; try { bindVariables = queue.take(); } catch (InterruptedException e) { // re-check loop condition after interrupt continue; } Iterator<InetAddress> iter = endpoints.iterator(); while (true) { // send the mutation to the last-used endpoint. first time through, this will NPE harmlessly. try { int i = 0; int itemId = preparedStatement(client); while (bindVariables != null) { client.execute_prepared_cql3_query(itemId, bindVariables, ConsistencyLevel.ONE); i++; if (i >= batchThreshold) break; bindVariables = queue.poll(); } break; } catch (Exception e) { closeInternal(); if (!iter.hasNext()) { lastException = new IOException(e); break outer; } } // attempt to connect to a different endpoint try { InetAddress address = iter.next(); String host = address.getHostName(); int port = ConfigHelper.getOutputRpcPort(conf); client = CqlOutputFormat.createAuthenticatedClient(host, port, conf); } catch (Exception e) { closeInternal(); // TException means something unexpected went wrong to that endpoint, so // we should try again to another. Other exceptions (auth or invalid request) are fatal. if ((!(e instanceof TException)) || !iter.hasNext()) { lastException = new IOException(e); break outer; } } } } // close all our connections once we are done. closeInternal(); }
[ "public", "void", "run", "(", ")", "{", "outer", ":", "while", "(", "run", "||", "!", "queue", ".", "isEmpty", "(", ")", ")", "{", "List", "<", "ByteBuffer", ">", "bindVariables", ";", "try", "{", "bindVariables", "=", "queue", ".", "take", "(", ")...
Loops collecting cql binded variable values from the queue and sending to Cassandra
[ "Loops", "collecting", "cql", "binded", "variable", "values", "from", "the", "queue", "and", "sending", "to", "Cassandra" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlRecordWriter.java#L218-L289
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/hadoop/cql3/CqlRecordWriter.java
RangeClient.preparedStatement
private int preparedStatement(Cassandra.Client client) { Integer itemId = preparedStatements.get(client); if (itemId == null) { CqlPreparedResult result; try { result = client.prepare_cql3_query(ByteBufferUtil.bytes(cql), Compression.NONE); } catch (InvalidRequestException e) { throw new RuntimeException("failed to prepare cql query " + cql, e); } catch (TException e) { throw new RuntimeException("failed to prepare cql query " + cql, e); } Integer previousId = preparedStatements.putIfAbsent(client, Integer.valueOf(result.itemId)); itemId = previousId == null ? result.itemId : previousId; } return itemId; }
java
private int preparedStatement(Cassandra.Client client) { Integer itemId = preparedStatements.get(client); if (itemId == null) { CqlPreparedResult result; try { result = client.prepare_cql3_query(ByteBufferUtil.bytes(cql), Compression.NONE); } catch (InvalidRequestException e) { throw new RuntimeException("failed to prepare cql query " + cql, e); } catch (TException e) { throw new RuntimeException("failed to prepare cql query " + cql, e); } Integer previousId = preparedStatements.putIfAbsent(client, Integer.valueOf(result.itemId)); itemId = previousId == null ? result.itemId : previousId; } return itemId; }
[ "private", "int", "preparedStatement", "(", "Cassandra", ".", "Client", "client", ")", "{", "Integer", "itemId", "=", "preparedStatements", ".", "get", "(", "client", ")", ";", "if", "(", "itemId", "==", "null", ")", "{", "CqlPreparedResult", "result", ";", ...
get prepared statement id from cache, otherwise prepare it from Cassandra server
[ "get", "prepared", "statement", "id", "from", "cache", "otherwise", "prepare", "it", "from", "Cassandra", "server" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/hadoop/cql3/CqlRecordWriter.java#L292-L315
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/repair/Validator.java
Validator.complete
public void complete() { completeTree(); StageManager.getStage(Stage.ANTI_ENTROPY).execute(this); if (logger.isDebugEnabled()) { // log distribution of rows in tree logger.debug("Validated {} partitions for {}. Partitions per leaf are:", validated, desc.sessionId); tree.histogramOfRowCountPerLeaf().log(logger); logger.debug("Validated {} partitions for {}. Partition sizes are:", validated, desc.sessionId); tree.histogramOfRowSizePerLeaf().log(logger); } }
java
public void complete() { completeTree(); StageManager.getStage(Stage.ANTI_ENTROPY).execute(this); if (logger.isDebugEnabled()) { // log distribution of rows in tree logger.debug("Validated {} partitions for {}. Partitions per leaf are:", validated, desc.sessionId); tree.histogramOfRowCountPerLeaf().log(logger); logger.debug("Validated {} partitions for {}. Partition sizes are:", validated, desc.sessionId); tree.histogramOfRowSizePerLeaf().log(logger); } }
[ "public", "void", "complete", "(", ")", "{", "completeTree", "(", ")", ";", "StageManager", ".", "getStage", "(", "Stage", ".", "ANTI_ENTROPY", ")", ".", "execute", "(", "this", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", ...
Registers the newly created tree for rendezvous in Stage.ANTIENTROPY.
[ "Registers", "the", "newly", "created", "tree", "for", "rendezvous", "in", "Stage", ".", "ANTIENTROPY", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/Validator.java#L208-L222
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/repair/Validator.java
Validator.fail
public void fail() { logger.error("Failed creating a merkle tree for {}, {} (see log for details)", desc, initiator); // send fail message only to nodes >= version 2.0 MessagingService.instance().sendOneWay(new ValidationComplete(desc).createMessage(), initiator); }
java
public void fail() { logger.error("Failed creating a merkle tree for {}, {} (see log for details)", desc, initiator); // send fail message only to nodes >= version 2.0 MessagingService.instance().sendOneWay(new ValidationComplete(desc).createMessage(), initiator); }
[ "public", "void", "fail", "(", ")", "{", "logger", ".", "error", "(", "\"Failed creating a merkle tree for {}, {} (see log for details)\"", ",", "desc", ",", "initiator", ")", ";", "// send fail message only to nodes >= version 2.0", "MessagingService", ".", "instance", "("...
Called when some error during the validation happened. This sends RepairStatus to inform the initiator that the validation has failed. The actual reason for failure should be looked up in the log of the host calling this function.
[ "Called", "when", "some", "error", "during", "the", "validation", "happened", ".", "This", "sends", "RepairStatus", "to", "inform", "the", "initiator", "that", "the", "validation", "has", "failed", ".", "The", "actual", "reason", "for", "failure", "should", "b...
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/Validator.java#L243-L248
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/repair/Validator.java
Validator.run
public void run() { // respond to the request that triggered this validation if (!initiator.equals(FBUtilities.getBroadcastAddress())) logger.info(String.format("[repair #%s] Sending completed merkle tree to %s for %s/%s", desc.sessionId, initiator, desc.keyspace, desc.columnFamily)); MessagingService.instance().sendOneWay(new ValidationComplete(desc, tree).createMessage(), initiator); }
java
public void run() { // respond to the request that triggered this validation if (!initiator.equals(FBUtilities.getBroadcastAddress())) logger.info(String.format("[repair #%s] Sending completed merkle tree to %s for %s/%s", desc.sessionId, initiator, desc.keyspace, desc.columnFamily)); MessagingService.instance().sendOneWay(new ValidationComplete(desc, tree).createMessage(), initiator); }
[ "public", "void", "run", "(", ")", "{", "// respond to the request that triggered this validation", "if", "(", "!", "initiator", ".", "equals", "(", "FBUtilities", ".", "getBroadcastAddress", "(", ")", ")", ")", "logger", ".", "info", "(", "String", ".", "format...
Called after the validation lifecycle to respond with the now valid tree. Runs in Stage.ANTIENTROPY.
[ "Called", "after", "the", "validation", "lifecycle", "to", "respond", "with", "the", "now", "valid", "tree", ".", "Runs", "in", "Stage", ".", "ANTIENTROPY", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/Validator.java#L253-L259
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/concurrent/SEPExecutor.java
SEPExecutor.maybeSchedule
boolean maybeSchedule() { if (pool.spinningCount.get() > 0 || !takeWorkPermit(true)) return false; pool.schedule(new Work(this)); return true; }
java
boolean maybeSchedule() { if (pool.spinningCount.get() > 0 || !takeWorkPermit(true)) return false; pool.schedule(new Work(this)); return true; }
[ "boolean", "maybeSchedule", "(", ")", "{", "if", "(", "pool", ".", "spinningCount", ".", "get", "(", ")", ">", "0", "||", "!", "takeWorkPermit", "(", "true", ")", ")", "return", "false", ";", "pool", ".", "schedule", "(", "new", "Work", "(", "this", ...
will self-assign to it in the immediate future
[ "will", "self", "-", "assign", "to", "it", "in", "the", "immediate", "future" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/SEPExecutor.java#L71-L78
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/concurrent/SEPExecutor.java
SEPExecutor.returnWorkPermit
void returnWorkPermit() { while (true) { long current = permits.get(); int workPermits = workPermits(current); if (permits.compareAndSet(current, updateWorkPermits(current, workPermits + 1))) return; } }
java
void returnWorkPermit() { while (true) { long current = permits.get(); int workPermits = workPermits(current); if (permits.compareAndSet(current, updateWorkPermits(current, workPermits + 1))) return; } }
[ "void", "returnWorkPermit", "(", ")", "{", "while", "(", "true", ")", "{", "long", "current", "=", "permits", ".", "get", "(", ")", ";", "int", "workPermits", "=", "workPermits", "(", "current", ")", ";", "if", "(", "permits", ".", "compareAndSet", "("...
gives up a work permit
[ "gives", "up", "a", "work", "permit" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/concurrent/SEPExecutor.java#L169-L178
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/ErrorCollector.java
ErrorCollector.areTokensValid
private static boolean areTokensValid(Token... tokens) { for (Token token : tokens) { if (!isTokenValid(token)) return false; } return true; }
java
private static boolean areTokensValid(Token... tokens) { for (Token token : tokens) { if (!isTokenValid(token)) return false; } return true; }
[ "private", "static", "boolean", "areTokensValid", "(", "Token", "...", "tokens", ")", "{", "for", "(", "Token", "token", ":", "tokens", ")", "{", "if", "(", "!", "isTokenValid", "(", "token", ")", ")", "return", "false", ";", "}", "return", "true", ";"...
Checks if the specified tokens are valid. @param tokens the tokens to check @return <code>true</code> if all the specified tokens are valid ones, <code>false</code> otherwise.
[ "Checks", "if", "the", "specified", "tokens", "are", "valid", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/ErrorCollector.java#L168-L176
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/cql3/ErrorCollector.java
ErrorCollector.highlightToken
private static String highlightToken(String line, Token token) { String newLine = insertChar(line, getLastCharPositionInLine(token), ']'); return insertChar(newLine, token.getCharPositionInLine(), '['); }
java
private static String highlightToken(String line, Token token) { String newLine = insertChar(line, getLastCharPositionInLine(token), ']'); return insertChar(newLine, token.getCharPositionInLine(), '['); }
[ "private", "static", "String", "highlightToken", "(", "String", "line", ",", "Token", "token", ")", "{", "String", "newLine", "=", "insertChar", "(", "line", ",", "getLastCharPositionInLine", "(", "token", ")", ",", "'", "'", ")", ";", "return", "insertChar"...
Puts the specified token within square brackets. @param line the line containing the token @param token the token to put within square brackets
[ "Puts", "the", "specified", "token", "within", "square", "brackets", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/cql3/ErrorCollector.java#L210-L214
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/repair/Differencer.java
Differencer.run
public void run() { // compare trees, and collect differences differences.addAll(MerkleTree.difference(r1.tree, r2.tree)); // choose a repair method based on the significance of the difference String format = String.format("[repair #%s] Endpoints %s and %s %%s for %s", desc.sessionId, r1.endpoint, r2.endpoint, desc.columnFamily); if (differences.isEmpty()) { logger.info(String.format(format, "are consistent")); // send back sync complete message MessagingService.instance().sendOneWay(new SyncComplete(desc, r1.endpoint, r2.endpoint, true).createMessage(), FBUtilities.getLocalAddress()); return; } // non-0 difference: perform streaming repair logger.info(String.format(format, "have " + differences.size() + " range(s) out of sync")); performStreamingRepair(); }
java
public void run() { // compare trees, and collect differences differences.addAll(MerkleTree.difference(r1.tree, r2.tree)); // choose a repair method based on the significance of the difference String format = String.format("[repair #%s] Endpoints %s and %s %%s for %s", desc.sessionId, r1.endpoint, r2.endpoint, desc.columnFamily); if (differences.isEmpty()) { logger.info(String.format(format, "are consistent")); // send back sync complete message MessagingService.instance().sendOneWay(new SyncComplete(desc, r1.endpoint, r2.endpoint, true).createMessage(), FBUtilities.getLocalAddress()); return; } // non-0 difference: perform streaming repair logger.info(String.format(format, "have " + differences.size() + " range(s) out of sync")); performStreamingRepair(); }
[ "public", "void", "run", "(", ")", "{", "// compare trees, and collect differences", "differences", ".", "addAll", "(", "MerkleTree", ".", "difference", "(", "r1", ".", "tree", ",", "r2", ".", "tree", ")", ")", ";", "// choose a repair method based on the significan...
Compares our trees, and triggers repairs for any ranges that mismatch.
[ "Compares", "our", "trees", "and", "triggers", "repairs", "for", "any", "ranges", "that", "mismatch", "." ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/Differencer.java#L58-L76
train
Stratio/stratio-cassandra
src/java/org/apache/cassandra/repair/Differencer.java
Differencer.minEndpoint
private InetAddress minEndpoint() { return FBUtilities.compareUnsigned(r1.endpoint.getAddress(), r2.endpoint.getAddress()) < 0 ? r1.endpoint : r2.endpoint; }
java
private InetAddress minEndpoint() { return FBUtilities.compareUnsigned(r1.endpoint.getAddress(), r2.endpoint.getAddress()) < 0 ? r1.endpoint : r2.endpoint; }
[ "private", "InetAddress", "minEndpoint", "(", ")", "{", "return", "FBUtilities", ".", "compareUnsigned", "(", "r1", ".", "endpoint", ".", "getAddress", "(", ")", ",", "r2", ".", "endpoint", ".", "getAddress", "(", ")", ")", "<", "0", "?", "r1", ".", "e...
So we just order endpoint deterministically to simplify this
[ "So", "we", "just", "order", "endpoint", "deterministically", "to", "simplify", "this" ]
f6416b43ad5309083349ad56266450fa8c6a2106
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/repair/Differencer.java#L118-L123
train