code
stringlengths
73
34.1k
label
stringclasses
1 value
public Set<String> getNames() { if (parent == null) { return getLocalNames(); } Set<String> result = new TreeSet<>(); result.addAll(parent.getNames()); result.addAll(getLocalNames()); return result; }
java
public Collection<Variable> getVariables() { if (parent == null) { return getLocalVariables(); } List<Variable> result = new ArrayList<>(); result.addAll(parent.getVariables()); result.addAll(getLocalVariables()); return result; }
java
public static <T> T ifNull(final T reference, final T defaultValue) { if (reference == null) { return defaultValue; } return reference; }
java
private Buffer consumeUntil(final Buffer name) { try { while (this.params.hasReadableBytes()) { SipParser.consumeSEMI(this.params); final Buffer[] keyValue = SipParser.consumeGenericParam(this.params); ensureParamsMap(); final Buffer va...
java
private void ensureParams() { if (this.isDirty) { // note, it would only be dirty if we actually have inserted a value // so therefore no need to check that the parammap is null final Buffer restOfParams = this.params; this.params = allcoateNewParamBuffer(); ...
java
public static void basicExample001() throws IOException { final String rawMessage = new StringBuilder("BYE sip:bob@127.0.0.1:5060 SIP/2.0\r\n") .append("Via: SIP/2.0/UDP 127.0.1.1:5061;branch=z9hG4bK-28976-1-7\r\n") .append("From: alice <sip:alice@127.0.1.1:5061>;tag=28976SIPpTag...
java
public static void basicExample003() throws Exception { // Generate a request again final SipRequest invite = SipRequest.invite("sip:alice@aboutsip.com") .withFromHeader("sip:bob@pkts.io") .build(); // Create a 200 OK to that INVITE and also add a generic ...
java
private void init() { this.currentState = CallState.START; this.callTransitions = new ArrayList<CallState>(); this.messages = new TreeSet<SipPacket>(new PacketComparator()); }
java
private void handleInCancellingState(final SipPacket msg) throws SipPacketParseException { // we don't move over to cancelled state even if // we receive a 200 OK to the cancel request. // therefore, not even checking it... if (msg.isCancel()) { transition(CallState.CANCELLI...
java
private void handleInCompletedState(final SipPacket msg) throws SipPacketParseException { if (msg.isRequest()) { // TODO: } else { if (msg.isBye()) { transition(CallState.COMPLETED, msg); } } }
java
private void handleInConfirmedState(final SipPacket msg) throws SipPacketParseException { if (msg.isRequest()) { if (msg.isBye()) { if (this.byeRequest == null) { this.byeRequest = msg.toRequest(); } transition(CallState.COMPLETED, ...
java
private void transition(final CallState nextState, final SipPacket msg) { final CallState previousState = this.currentState; this.currentState = nextState; if (previousState != nextState) { // don't add the same transition twice this.callTransitions.add(nextState); ...
java
private void setMacAddress(final String macAddress, final boolean setSourceMacAddress) throws IllegalArgumentException { if (macAddress == null || macAddress.isEmpty()) { throw new IllegalArgumentException("Null or empty string cannot be a valid MAC Address."); } // very ...
java
private int calculateChecksum() { long sum = 0; for (int i = 0; i < this.headers.capacity() - 1; i += 2) { if (i != 10) { sum += this.headers.getUnsignedShort(i); } } while (sum >> 16 != 0) { sum = (sum & 0xffff) + (sum >> 16); ...
java
private void setIP(final int startIndex, final String address) { final String[] parts = address.split("\\."); this.headers.setByte(startIndex + 0, (byte) Integer.parseInt(parts[0])); this.headers.setByte(startIndex + 1, (byte) Integer.parseInt(parts[1])); this.headers.setByte(startIndex ...
java
@Override public int getHeaderLength() { try { final byte b = this.headers.getByte(0); // length is encoded as the number of 32-bit words, so to get number of bytes we must multiply by 4 return (b & 0x0F) * 4; } catch (final IOException e) { throw new ...
java
public static Function<SipHeader, ? extends SipHeader> getFramer(final Buffer b) { // For headers that have the expected capitalization, do a quick case-sensitive // search. If that fails do a slower case-insensitive search. final Function<SipHeader, ? extends SipHeader> framer = framers.get(b);...
java
public static boolean isUDP(final Buffer t) { try { return t.capacity() == 3 && t.getByte(0) == 'U' && t.getByte(1) == 'D' && t.getByte(2) == 'P'; } catch (final IOException e) { return false; } }
java
public static boolean isUDPLower(final Buffer t) { try { return t.capacity() == 3 && t.getByte(0) == 'u' && t.getByte(1) == 'd' && t.getByte(2) == 'p'; } catch (final IOException e) { return false; } }
java
public static boolean isNext(final Buffer buffer, final byte b) throws IOException { if (buffer.hasReadableBytes()) { final byte actual = buffer.peekByte(); return actual == b; } return false; }
java
public static boolean isNextDigit(final Buffer buffer) throws IndexOutOfBoundsException, IOException { if (buffer.hasReadableBytes()) { final char next = (char) buffer.peekByte(); return next >= 48 && next <= 57; } return false; }
java
public static Buffer expectDigit(final Buffer buffer) throws SipParseException { final int start = buffer.getReaderIndex(); try { while (buffer.hasReadableBytes() && isNextDigit(buffer)) { // consume it buffer.readByte(); } if (start ...
java
public static int expectWS(final Buffer buffer) throws SipParseException { int consumed = 0; try { if (buffer.hasReadableBytes()) { final byte b = buffer.getByte(buffer.getReaderIndex()); if (b == SP || b == HTAB) { // ok, it was a WS so co...
java
public static Buffer consumeAlphaNum(final Buffer buffer) throws IOException { final int count = getAlphaNumCount(buffer); if (count == 0) { return null; } return buffer.readBytes(count); }
java
public static int getAlphaNumCount(final Buffer buffer) throws IndexOutOfBoundsException, IOException { boolean done = false; int count = 0; final int index = buffer.getReaderIndex(); while (buffer.hasReadableBytes() && !done) { final byte b = buffer.readByte(); i...
java
public static boolean isNextAlphaNum(final Buffer buffer) throws IndexOutOfBoundsException, IOException { if (buffer.hasReadableBytes()) { final byte b = buffer.peekByte(); return isAlphaNum(b); } return false; }
java
public static boolean isHostPortCharacter(final char ch) { return isAlphaNum(ch) || ch == DASH || ch == PERIOD || ch == COLON; }
java
public static int consumeCRLF(final Buffer buffer) throws SipParseException { try { buffer.markReaderIndex(); final byte cr = buffer.readByte(); final byte lf = buffer.readByte(); if (cr == CR && lf == LF) { return 2; } } catch ...
java
private static boolean isHeaderAllowingMultipleValues(final Buffer headerName) { final int size = headerName.getReadableBytes(); if (size == 7) { return !isSubjectHeader(headerName); } else if (size == 5) { return !isAllowHeader(headerName); } else if (size == 4) ...
java
private static boolean isDateHeader(final Buffer name) { try { return name.getByte(0) == 'D' && name.getByte(1) == 'a' && name.getByte(2) == 't' && name.getByte(3) == 'e'; } catch (final IOException e) { return false; } }
java
public static SipHeader nextHeader(final Buffer buffer) throws SipParseException { try { final int startIndex = buffer.getReaderIndex(); int nameIndex = 0; while (buffer.hasReadableBytes() && nameIndex == 0) { if (isNext(buffer, SP) || isNext(buffer, HTAB) |...
java
public static Buffer wrap(final byte[] buffer) { if (buffer == null || buffer.length == 0) { throw new IllegalArgumentException("the buffer cannot be null or empty"); } return new ByteBuffer(buffer); }
java
public static Buffer wrap(final Buffer one, final Buffer two) { // TODO: create an actual composite buffer. final int size1 = one != null ? one.getReadableBytes() : 0; final int size2 = two != null ? two.getReadableBytes() : 0; if (size1 == 0 && size2 > 0) { return two.slice...
java
public static Buffer wrap(final byte[] buffer, final int lowerBoundary, final int upperBoundary) { if (buffer == null || buffer.length == 0) { throw new IllegalArgumentException("the buffer cannot be null or empty"); } if (upperBoundary > buffer.length) { throw new Illega...
java
public void write(final OutputStream out) throws IOException { if (this.byteOrder == ByteOrder.BIG_ENDIAN) { out.write(MAGIC_BIG_ENDIAN); } else { out.write(MAGIC_LITTLE_ENDIAN); } out.write(this.body); }
java
public static PcapRecordHeader createDefaultHeader(final long timestamp) { final byte[] body = new byte[SIZE]; // time stamp seconds // body[0] = (byte) 0x00; // body[1] = (byte) 0x00; // body[2] = (byte) 0x00; // body[3] = (byte) 0x00; // Time stamp microsecond...
java
public boolean process(final byte[] newData) { if (newData != null) { buffer.write(newData); } boolean done = false; while (!done) { final int index = buffer.getReaderIndex(); final State currentState = state; state = actions[state.ordinal...
java
private final State onInit(final Buffer buffer) { try { while (buffer.hasReadableBytes()) { final byte b = buffer.peekByte(); if (b == SipParser.SP || b == SipParser.HTAB || b == SipParser.CR || b == SipParser.LF) { buffer.readByte(); ...
java
private final State onInitialLine(final Buffer buffer) { try { buffer.markReaderIndex(); final Buffer part1 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser.SP); final Buffer part2 = buffer.readUntilSafe(config.getMaxAllowedInitialLineSize(), SipParser....
java
private final State onCheckEndHeaderSection(final Buffer buffer) { // can't tell. We need two bytes at least to check if there is // more headers or not if (buffer.getReadableBytes() < 2) { return State.CHECK_FOR_END_OF_HEADER_SECTION; } // ok, so there was a CRLF so...
java
private final State onPayload(final Buffer buffer) { if (contentLength == 0) { return State.DONE; } if (buffer.getReadableBytes() >= contentLength) { try { payload = buffer.readBytes(contentLength); } catch (final IOException e) { ...
java
private java.nio.ByteBuffer getWritingRow() { final int row = this.writerIndex / this.localCapacity; if (row >= this.storage.size()) { final java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(this.localCapacity); this.storage.add(buf); return buf; } ...
java
private java.nio.ByteBuffer getReadingRow() { final int row = this.readerIndex / this.localCapacity; return this.storage.get(row); }
java
@Override public boolean accept(final Buffer data) throws IOException { // a RTP packet has at least 12 bytes. Check that if (data.getReadableBytes() < 12) { // not enough bytes but see if we actually could // get another 12 bytes by forcing the underlying // impl...
java
@Override public final void write(final OutputStream out) throws IOException { if (this.nextPacket != null) { this.nextPacket.write(out); } else { this.write(out, this.payload); } }
java
private short addTrackedHeader(final short index, final SipHeader header) { if (index != -1) { headers.set(index, header.ensure()); return index; } return addHeader(header.ensure()); }
java
private <T> Consumer<T> chainConsumers(final Consumer<T> currentConsumer, final Consumer<T> consumer) { if (currentConsumer != null) { return currentConsumer.andThen(consumer); } return consumer; }
java
public EvolutionaryOperator<List<ColouredPolygon>> createEvolutionPipeline(PolygonImageFactory factory, Dimension canvasSize, Random rng) { List<Evolu...
java
private SwingBackgroundTask<List<String>> createTask(final Collection<String> cities) { final TravellingSalesmanStrategy strategy = strategyPanel.getStrategy(); return new SwingBackgroundTask<List<String>>() { private long elapsedTime = 0; @Override prote...
java
private String createResultString(String strategyDescription, List<String> shortestRoute, double distance, long elapsedTime) { StringBuilder buffer = new StringBuilder(); buffer.append('...
java
@Override public void setEnabled(boolean b) { itineraryPanel.setEnabled(b); strategyPanel.setEnabled(b); executionPanel.setEnabled(b); super.setEnabled(b); }
java
public double getFitness(String candidate, List<? extends String> population) { int errors = 0; for (int i = 0; i < candidate.length(); i++) { if (candidate.charAt(i) != targetString.charAt(i)) { ++errors; } ...
java
public List<Node> apply(List<Node> selectedCandidates, Random rng) { List<Node> evolved = new ArrayList<Node>(selectedCandidates.size()); for (Node node : selectedCandidates) { evolved.add(probability.nextEvent(rng) ? node.simplify() : node); } return evolved; ...
java
public <S> List<S> select(List<EvaluatedCandidate<S>> population, boolean naturalFitnessScores, int selectionSize, Random rng) { List<S> selection = new ArrayList<S>(selectionSize); double ratio = selectionRat...
java
protected void doReplacement(List<EvaluatedCandidate<T>> existingPopulation, List<EvaluatedCandidate<T>> newCandidates, int eliteCount, Random rng) { assert newCandidates.size() < existingPopulation.size() - e...
java
public Biomorph generateRandomCandidate(Random rng) { int[] genes = new int[Biomorph.GENE_COUNT]; for (int i = 0; i < Biomorph.GENE_COUNT - 1; i++) { // First 8 genes have values between -5 and 5. genes[i] = rng.nextInt(11) - 5; } // Last genes ha a va...
java
public static void main(String[] args) { String target = args.length == 0 ? "HELLO WORLD" : convertArgs(args); String result = evolveString(target); System.out.println("Evolution result: " + result); }
java
private static String convertArgs(String[] args) { StringBuilder result = new StringBuilder(); for (int i = 0; i < args.length; i++) { result.append(args[i]); if (i < args.length - 1) { result.append(' '); } } re...
java
public List<Biomorph> apply(List<Biomorph> selectedCandidates, Random rng) { List<Biomorph> mutatedPopulation = new ArrayList<Biomorph>(selectedCandidates.size()); for (Biomorph biomorph : selectedCandidates) { mutatedPopulation.add(mutateBiomorph(biomorph, rng)); } ...
java
private Biomorph mutateBiomorph(Biomorph biomorph, Random rng) { int[] genes = biomorph.getGenotype(); assert genes.length == Biomorph.GENE_COUNT : "Biomorphs must have " + Biomorph.GENE_COUNT + " genes."; for (int i = 0; i < Biomorph.GENE_COUNT - 1; i++) { if (mutationPr...
java
private Node makeNode(Random rng, int maxDepth) { if (functionProbability.nextEvent(rng) && maxDepth > 1) { // Max depth for sub-trees is one less than max depth for this node. int depth = maxDepth - 1; switch (rng.nextInt(5)) { case 0:...
java
public List<List<T>> apply(List<List<T>> selectedCandidates, Random rng) { List<List<T>> output = new ArrayList<List<T>>(selectedCandidates.size()); for (List<T> item : selectedCandidates) { output.add(delegate.apply(item, rng)); } return output; }
java
public List<Biomorph> apply(List<Biomorph> selectedCandidates, Random rng) { List<Biomorph> mutatedPopulation = new ArrayList<Biomorph>(selectedCandidates.size()); int mutatedGene = 0; int mutation = 1; for (Biomorph b : selectedCandidates) { int[] genes = b.getGe...
java
private Color mutateColour(Color colour, Random rng) { if (mutationProbability.nextValue().nextEvent(rng)) { return new Color(mutateColourComponent(colour.getRed()), mutateColourComponent(colour.getGreen()), mutateColourComponent(...
java
public Thread newThread(Runnable runnable) { Thread thread = new Thread(runnable, nameGenerator.nextID()); thread.setPriority(priority); thread.setDaemon(daemon); thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); return thread; }
java
public List<T> apply(List<T> selectedCandidates, Random rng) { List<T> output = new ArrayList<T>(selectedCandidates.size()); for (T candidate : selectedCandidates) { output.add(replacementProbability.nextValue().nextEvent(rng) ? factory.generateRandomCandid...
java
public void paintBorder(Component component, Graphics graphics, int x, int y, int width, int height) { if (top) { graphics.fillRect(x, y, width, thi...
java
private void updateDomainAxisRange() { int count = dataSet.getSeries(0).getItemCount(); if (count < SHOW_FIXED_GENERATIONS) { domainAxis.setRangeWithMargins(0, SHOW_FIXED_GENERATIONS); } else if (allDataButton.isSelected()) { domainAxis.setRang...
java
private BufferedImage convertImage(BufferedImage image) { if (image.getType() == BufferedImage.TYPE_INT_RGB) { return image; } else { BufferedImage newImage = new BufferedImage(image.getWidth(), im...
java
public double getFitness(List<ColouredPolygon> candidate, List<? extends List<ColouredPolygon>> population) { // Use one renderer per thread because they are not thread safe. Renderer<List<ColouredPolygon>, BufferedImage> renderer = threadLocalRenderer.get(); if ...
java
public List<T> apply(List<T> selectedCandidates, Random rng) { double ratio = weightVariable.nextValue(); int size = (int) Math.round(ratio * selectedCandidates.size()); // Shuffle the collection before applying each operation so that the // split is not influenced by any ordering a...
java
public static void main(String[] args) throws IOException { MonaLisaApplet gui = new MonaLisaApplet(); // If a URL is specified as an argument, use that image. Otherwise use the default Mona Lisa picture. URL imageURL = args.length > 0 ? new URL(args[0]) ...
java
public List<T> apply(List<T> selectedCandidates, Random rng) { return new ArrayList<T>(selectedCandidates); }
java
@Override protected List<Node> mate(Node parent1, Node parent2, int numberOfCrossoverPoints, Random rng) { List<Node> offspring = new ArrayList<Node>(2); Node offspring1 = parent1; Node offspring2 =...
java
public String generateRandomCandidate(Random rng) { char[] chars = new char[stringLength]; for (int i = 0; i < stringLength; i++) { chars[i] = alphabet[rng.nextInt(alphabet.length)]; } return new String(chars); }
java
public static Method findKnownMethod(Class<?> aClass, String name, Class<?>... paramTypes) { try { return aClass.getMethod(name, paramTypes); } catch (NoSuchMethodException ex) { ...
java
public static <T> Constructor<T> findKnownConstructor(Class<T> aClass, Class<?>... paramTypes) { try { return aClass.getConstructor(paramTypes); } catch (NoSuchMethodException ex) { // This cann...
java
private List<Callable<List<EvaluatedCandidate<T>>>> createEpochTasks(int populationSize, int eliteCount, int epochLength, ...
java
public List<T> apply(List<T> selectedCandidates, Random rng) { // Shuffle the collection before applying each operation so that the // evolution is not influenced by any ordering artifacts from previous // operations. List<T> selectionClone = new ArrayList<T>(selectedCandidates); ...
java
private Border getBorder(int row, int column) { if (row % 3 == 2) { switch (column % 3) { case 2: return BOTTOM_RIGHT_BORDER; case 0: return BOTTOM_LEFT_BORDER; default: return BOTTOM_BORDER; } } else...
java
public static <T> List<TerminationCondition> shouldContinue(PopulationData<T> data, TerminationCondition... conditions) { // If the thread has been interrupted, we should abort and return whatever // result we currently have. if...
java
public static <T> PopulationData<T> getPopulationData(List<EvaluatedCandidate<T>> evaluatedPopulation, boolean naturalFitness, int eliteCount, int...
java
public BufferedImage render(List<ColouredPolygon> entity) { // Need to set the background before applying the transform. graphics.setTransform(IDENTITY_TRANSFORM); graphics.setColor(Color.GRAY); graphics.fillRect(0, 0, targetSize.width, targetSize.height); if (transform != nu...
java
public <S extends Object> void migrate(List<List<EvaluatedCandidate<S>>> islandPopulations, int migrantCount, Random rng) { // The first batch of immigrants is from the last island to the first. List<EvaluatedCandidate<S>> lastIsland = islandPopulations.get(islandPopulations.size() - 1); Col...
java
public Collection<String> getSelectedCities() { Set<String> cities = new TreeSet<String>(); for (JCheckBox checkBox : checkBoxes) { if (checkBox.isSelected()) { cities.add(checkBox.getText()); } } return cities; }
java
@Override protected List<Point> mutateVertices(List<Point> vertices, Random rng) { // A single point is added with the configured probability, unless // we already have the maximum permitted number of points. if (vertices.size() < MAX_VERTEX_COUNT && getMutationProbability().nextValue()....
java
public int[][] getPatternPhenotype() { if (phenotype == null) { // Decode the genes as per Dawkins' rules. int[] dx = new int[GENE_COUNT - 1]; dx[3] = genes[0]; dx[4] = genes[1]; dx[5] = genes[2]; dx[1] = -dx[3]; dx...
java
private boolean isIntroducingFixedConflict(Sudoku sudoku, int row, int fromIndex, int toIndex) { return columnFixedValues[fromIndex][sudoku.getValue(row, toIndex) - 1]...
java
public List<T> apply(List<T> selectedCandidates, Random rng) { List<T> population = selectedCandidates; for (EvolutionaryOperator<T> operator : pipeline) { population = operator.apply(population, rng); } return population; }
java
public double getFitness(List<String> candidate, List<? extends List<String>> population) { int totalDistance = 0; int cityCount = candidate.size(); for (int i = 0; i < cityCount; i++) { int nextIndex = i < cityCount - 1 ? i + 1 : 0; ...
java
public static void main(String[] args) { Class<?> exampleClass = args.length > 0 ? EXAMPLES.get(args[0]) : null; if (exampleClass == null) { System.err.println("First argument must be the name of an example, i.e. one of " + Arrays.toString(EXAMPLES....
java
private String mutateString(String s, Random rng) { StringBuilder buffer = new StringBuilder(s); for (int i = 0; i < buffer.length(); i++) { if (mutationProbability.nextValue().nextEvent(rng)) { buffer.setCharAt(i, alphabet[rng.nextInt(alphabet.length)...
java
public static Node evolveProgram(Map<double[], Double> data) { TreeFactory factory = new TreeFactory(2, // Number of parameters passed into each program. 4, // Maximum depth of generated trees. Probability.EVENS, // ...
java
private void showWindow(Window newWindow) { if (window != null) { window.remove(getGUIComponent()); window.setVisible(false); window.dispose(); window = null; } newWindow.add(getGUIComponent(), BorderLayout.CENTER); newWindow.pa...
java
private void checkUnmappedElements(List<T> offspring, Map<T, T> mapping, int mappingStart, int mappingEnd) { for (int i = 0; i < offspring.size(); i++) { if (!isInsideMapp...
java
private boolean isInsideMappedRegion(int position, int startPoint, int endPoint) { boolean enclosed = (position < endPoint && position >= startPoint); boolean wrapAround = (startPoint > endPoint && (position >= startPo...
java
private void configure(final Container container) { try { // Use invokeAndWait so that we can be sure that initialisation is complete // before continuing. SwingUtilities.invokeAndWait(new Runnable() { public void run() ...
java
private BitString mutateBitString(BitString bitString, Random rng) { if (mutationProbability.nextValue().nextEvent(rng)) { BitString mutatedBitString = bitString.clone(); int mutations = mutationCount.nextValue(); for (int i = 0; i < mutations; i++) { ...
java
public static <T> T run(HTablePool pool, byte[] tableName, HTableRunnable<T> runnable) throws IOException { HTableInterface hTable = null; try { hTable = pool.getTable(tableName); return runnable.runWith(hTable); } catch (Exception e) { if (e insta...
java
public static void put(HTablePool pool, byte[] tableName, final Put put) throws IOException { run(pool, tableName, new HTableRunnable<Object>() { @Override public Object runWith(HTableInterface hTable) throws IOException { hTable.put(put); return null; ...
java