/**
 * Copyright 2007-2015, Kaazing Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kaazing.nuklei.tcp.internal.types.stream;

public final class Types
{
    public static final int TYPE_ID_RESET = 0x00000000;
    public static final int TYPE_ID_BEGIN = 0x00000001;
    public static final int TYPE_ID_DATA = 0x00000002;
    public static final int TYPE_ID_END = 0x00000003;

    private Types()
    {
        // no instances
    }
}

/**
 * Copyright 2007-2015, Kaazing Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.kaazing.nuklei.tcp.internal.types.stream;

public final class Types
{
    public static final int TYPE_ID_BEGIN = 0x00000001;
    public static final int TYPE_ID_DATA = 0x00000002;
    public static final int TYPE_ID_END = 0x00000003;
    public static final int TYPE_ID_RESET = 0x00000004;

    private Types()
    {
        // no instances
    }
}

Use 0x04 for reset event since 0x00 is not supported


package com.vaguehope.onosendai.model;

public class TweetBuilder {

	private long id;
	private String username;
	private String body;
	private long unitTimeSeconds;
	private String avatarUrl;
	// TODO include metas?

	public TweetBuilder () {
		reset();
	}

	public void reset () {
		this.id = 0L;
		this.username = null;
		this.body = null;
		this.unitTimeSeconds = 0L;
		this.avatarUrl = null;
	}

	public TweetBuilder id (final long v) {
		this.id = v;
		return this;
	}

	public TweetBuilder username (final String v) {
		this.username = v;
		return this;
	}

	public TweetBuilder body (final String v) {
		this.body = v;
		return this;
	}

	public TweetBuilder unitTimeSeconds (final long v) {
		this.unitTimeSeconds = v;
		return this;
	}

	public TweetBuilder avatarUrl (final String v) {
		this.avatarUrl = v;
		return this;
	}

	public Tweet build () {
		Tweet t = new Tweet(this.id, this.username, this.body, this.unitTimeSeconds, this.avatarUrl);
		reset();
		return t;
	}

}

package com.vaguehope.onosendai.model;

public class TweetBuilder {

	private long id;
	private String username;
	private String body;
	private long unitTimeSeconds;
	private String avatarUrl;
	// TODO include metas?

	public TweetBuilder () {
		reset();
	}

	public final void reset () {
		this.id = 0L;
		this.username = null;
		this.body = null;
		this.unitTimeSeconds = 0L;
		this.avatarUrl = null;
	}

	public TweetBuilder id (final long v) {
		this.id = v;
		return this;
	}

	public TweetBuilder username (final String v) {
		this.username = v;
		return this;
	}

	public TweetBuilder body (final String v) {
		this.body = v;
		return this;
	}

	public TweetBuilder unitTimeSeconds (final long v) {
		this.unitTimeSeconds = v;
		return this;
	}

	public TweetBuilder avatarUrl (final String v) {
		this.avatarUrl = v;
		return this;
	}

	public Tweet build () {
		Tweet t = new Tweet(this.id, this.username, this.body, this.unitTimeSeconds, this.avatarUrl);
		reset();
		return t;
	}

}

Fix Constructor Calls Overridable Method.


package io.teknek.intravert.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

import com.google.common.cache.ForwardingCache;
import com.google.common.cache.LoadingCache;

public class RequestContext {

  private static final AtomicLong SESSION_ID = new AtomicLong(0);
  private static Map<Long,Session> SAVED = new HashMap<Long,Session>();
  //private static LoadingCache<Long,Session> CACHE;
  private Session session;

  public RequestContext(){

  }

  public Session recoverSession(Long l){
    session = SAVED.get(l);
    return session;
  }

  public Long saveSession(){
    Long id = SESSION_ID.getAndIncrement();
    SAVED.put(id, getSession());
    return id;
  }

  public Session getSession(){
    if (session == null){
      session = new Session();
    }
    return session;
  }

}

package io.teknek.intravert.service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import org.mortbay.io.BufferCache.CachedBuffer;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.ForwardingCache;
import com.google.common.cache.LoadingCache;

public class RequestContext {

  private static final AtomicLong SESSION_ID = new AtomicLong(0);
  private static LoadingCache<Long,Session> CACHE;
  private Session session;

  static {
    CacheLoader <Long,Session> loader = new CacheLoader<Long,Session>(){
      @Override
      public Session load(Long id) throws Exception {
        return new Session();
      }
    };
    CACHE = CacheBuilder.newBuilder()
            .maximumSize(10000)
            .expireAfterAccess(60, TimeUnit.SECONDS)
            .build(loader);
  }

  public RequestContext(){

  }

  public Session recoverSession(Long l){
    try {
      session = CACHE.get(l);
    } catch (ExecutionException e) {
      throw new RuntimeException(e);
    }
    return session;
  }

  public Long saveSession(){
    Long id = SESSION_ID.getAndIncrement();
    CACHE.put(id, getSession());
    return id;
  }

  public Session getSession(){
    if (session == null){
      session = new Session();
    }
    return session;
  }

}

Use loading cache to manage sessions


import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by TUDelft SID on 8-5-2017.
 */
public class GraphDrawer {

    private int Xsize = 10;
    private int Ysize = 6;
    private int lengthEdge = 2;
    private int yBase = 40;

    private SequenceGraph graph;
    private GraphicsContext gc;

    public GraphDrawer(SequenceGraph graph, GraphicsContext gc) {
        this.graph = graph;
        this.gc = gc;
        graph.initialize();
        graph.layerizeGraph();
    }

    public void drawShapes() throws IOException {
        HashMap<Integer, SequenceNode> nodes = graph.getNodes();

        for(int i = 1; i <= nodes.size(); i++) {
            SequenceNode node = nodes.get(i);
            gc.setFill(Color.BLUE);
            gc.fillRoundRect((node.getColumn() * (Xsize + lengthEdge)) + 50, yBase, Xsize, Ysize, 10, 10);
//            gc.setStroke(Color.BLACK);
//            gc.setLineWidth(1);
//            gc.strokeLine((node.getColumn() * (Xsize + lengthEdge)) + Xsize + 50,43, node.getColumn() * (Xsize + Xsize + lengthEdge) + 50, 43);
        }
    }
}

import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;

import java.io.IOException;
import java.util.HashMap;

/**
 * Created by TUDelft SID on 8-5-2017.
 */
public class GraphDrawer {

    public static final int X_SIZE = 10;
    public static final int Y_SIZE = 6;
    public static final int EDGE_LENGTH = 2;
    public static final int Y_BASE = 40;

    private SequenceGraph graph;
    private GraphicsContext gc;

    public GraphDrawer(SequenceGraph graph, GraphicsContext gc) {
        this.graph = graph;
        this.gc = gc;
        graph.initialize();
        graph.layerizeGraph();
    }

    public void drawShapes() throws IOException {
        HashMap<Integer, SequenceNode> nodes = graph.getNodes();

        for(int i = 1; i <= nodes.size(); i++) {
            SequenceNode node = nodes.get(i);
            gc.setFill(Color.BLUE);
            gc.fillRoundRect((node.getColumn() * (X_SIZE + EDGE_LENGTH)) + 50, Y_BASE, X_SIZE, Y_SIZE, 10, 10);
//            gc.setStroke(Color.BLACK);
//            gc.setLineWidth(1);
//            gc.strokeLine((node.getColumn() * (Xsize + lengthEdge)) + Xsize + 50,43, node.getColumn() * (Xsize + Xsize + lengthEdge) + 50, 43);
        }
    }
}

Use final number instead of magic numbers


package com.cwainner.chris.recipecentral.adapters;

import android.content.Context;
import android.widget.ArrayAdapter;

/**
 * Created by Chris on 5/26/2017.
 */

public class RecipePagerAdapter extends ArrayAdapter {
    private Context context;
    private String[] recipes;

    public RecipePagerAdapter(Context context, int resource, String[] recipes){
        super(context, resource);
        this.context = context;
        this.recipes = recipes;
    }

    @Override
    public Object getItem(int position){
        String recipe = recipes[position];
        return recipe;
    }

    @Override
    public int getCount(){
        return recipes.length;
    }
}

package com.cwainner.chris.recipecentral.adapters;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.cwainner.chris.recipecentral.models.Recipe;
import com.cwainner.chris.recipecentral.ui.RecipeDetailFragment;

import java.util.ArrayList;

public class RecipePagerAdapter extends FragmentPagerAdapter {
    private ArrayList<Recipe> recipes;

    public RecipePagerAdapter(FragmentManager fm, ArrayList<Recipe> recipes){
        super(fm);
        this.recipes = recipes;
    }

    @Override
    public Fragment getItem(int position){
        return RecipeDetailFragment.newInstance(recipes.get(position));
    }

    @Override
    public int getCount(){
        return recipes.size();
    }

    @Override
    public CharSequence getPageTitle(int position){
        return recipes.get(position).getTitle();
    }
}

Update Recipe Pager Adapter to handle fragments


package uk.ac.cam.gpe21.droidssl.mitm;

import uk.ac.cam.gpe21.droidssl.mitm.util.HexFormat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public final class IoCopyRunnable implements Runnable {
	private final InputStream in;
	private final OutputStream out;

	public IoCopyRunnable(InputStream in, OutputStream out) {
		this.in = in;
		this.out = out;
	}

	@Override
	public void run() {
		try {
			byte[] buf = new byte[4096];
			int n;
			while ((n = in.read(buf, 0, buf.length)) != -1) {
				System.out.println(HexFormat.format(buf, n));
				out.write(buf, 0, n);
			}
		} catch (IOException ex) {
			// TODO deal with properly (print warning, close socket?)
		}
	}
}

package uk.ac.cam.gpe21.droidssl.mitm;

import uk.ac.cam.gpe21.droidssl.mitm.util.HexFormat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public final class IoCopyRunnable implements Runnable {
	private final InputStream in;
	private final OutputStream out;

	public IoCopyRunnable(InputStream in, OutputStream out) {
		this.in = in;
		this.out = out;
	}

	@Override
	public void run() {
		try {
			byte[] buf = new byte[4096];
			int n;
			while ((n = in.read(buf, 0, buf.length)) != -1) {
				System.out.println(HexFormat.format(buf, n) + "\n");
				out.write(buf, 0, n);
			}
		} catch (IOException ex) {
			// TODO deal with properly (print warning, close socket?)
		}
	}
}

Add blank line between HexFormat chunks.


package uk.ac.ebi.atlas.profiles;

import uk.ac.ebi.atlas.commons.streams.ObjectInputStream;

import java.util.Iterator;

// Used to make ObjectInputStream iterable
// TODO: implement iterator() on all ObjectInputStream classes then this adapter won't be needed
public class IterableObjectInputStream<T> implements Iterable<T> {

    private final ObjectInputStream<T> inputStream;

    public IterableObjectInputStream(ObjectInputStream<T> inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public Iterator<T> iterator() {
        return new ObjectInputStreamIterator();
    }

    // buffers next object input stream result so we can
    // provide a hasNext method
    private final class ObjectInputStreamIterator implements Iterator<T> {

        private T next;

        private ObjectInputStreamIterator() {
            storeNext();
        }

        private void storeNext() {
            next = inputStream.readNext();
        }

        @Override
        public boolean hasNext() {
            return (next != null);
        }

        @Override
        public T next() {
            T result = next;
            storeNext();
            return result;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}

package uk.ac.ebi.atlas.profiles;

import uk.ac.ebi.atlas.commons.streams.ObjectInputStream;

import java.util.Iterator;

// Used to make ObjectInputStream iterable
public class IterableObjectInputStream<T> implements Iterable<T> {

    private final ObjectInputStream<T> inputStream;

    public IterableObjectInputStream(ObjectInputStream<T> inputStream) {
        this.inputStream = inputStream;
    }

    @Override
    public Iterator<T> iterator() {
        return new ObjectInputStreamIterator();
    }

    // buffers next object input stream result so we can provide a hasNext method
    private final class ObjectInputStreamIterator implements Iterator<T> {

        private T next;

        private ObjectInputStreamIterator() {
            storeNext();
        }

        private void storeNext() {
            next = inputStream.readNext();
        }

        @Override
        public boolean hasNext() {
            return (next != null);
        }

        @Override
        public T next() {
            T result = next;
            storeNext();
            return result;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

}

Remove TODO note, this class has value!


package com.mpalourdio.hello.model;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * This implementation MUST have the 'impl'
 * suffix in order to be discovered !
 */

public class TaskRepositoryImpl implements CustomRepository<Task> {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @SuppressWarnings("unchecked")
    public List<Task> customFindByPriority(final String priority) {
        return entityManager
                .createQuery("select e from Task e where e.taskPriority = :taskPriority")
                .setParameter("taskPriority", priority)
                .getResultList();
    }
}

package com.mpalourdio.hello.model;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * This implementation MUST have the 'impl'
 * suffix in order to be discovered !
 */

public class TaskRepositoryImpl implements CustomRepository<Task> {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<Task> customFindByPriority(final String priority) {
        return entityManager
                .createQuery("select e from Task e where e.taskPriority = :taskPriority", Task.class)
                .setParameter("taskPriority", priority)
                .getResultList();
    }
}

Use TypeQuery to avoid uncheck warning


/*
 * Copyright (c) 2012-2013 Continuuity Inc. All rights reserved.
 */

package com.continuuity.api.data.batch;

import com.continuuity.api.annotation.Beta;

import java.util.List;

/**
 * Interface for datasets that can be input to a batch job.
 *

 *   In order to feed a dataset into a batch job, the dataset must be splittable into chunks so that it's possible
 *   to process every part of the dataset in parallel. Every chunk must be readable as a collection of {key,value} records.
 *

 * @param <KEY> The key type.
 * @param <VALUE> The value type.
 */
@Beta
public interface BatchReadable<KEY, VALUE> {
  /**
   * Returns all splits of the dataset.
   *

   *   For feeding the whole dataset into a batch job.
   *

   * @return list A list of {@link Split}s.
   */
  List<Split> getSplits();

  /**
   * Creates a reader for the split of a dataset.
   * @param split The split to create a reader for.
   * @return instance The instance of a {@link SplitReader}.
   */
  SplitReader<KEY, VALUE> createSplitReader(Split split);
}

/*
 * Copyright (c) 2012-2013 Continuuity Inc. All rights reserved.
 */

package com.continuuity.api.data.batch;

import com.continuuity.api.annotation.Beta;

import java.util.List;

/**
 * Interface for datasets that can be input to a batch job.
 *

 *   In order to feed a dataset into a batch job, the dataset must be splittable into chunks so that it's possible
 *   to process every part of the dataset in parallel. Every chunk must be readable as a collection of {key,value}
 *   records.
 *

 * @param <KEY> The key type.
 * @param <VALUE> The value type.
 */
@Beta
public interface BatchReadable<KEY, VALUE> {
  /**
   * Returns all splits of the dataset.
   *

   *   For feeding the whole dataset into a batch job.
   *

   * @return list A list of {@link Split}s.
   */
  List<Split> getSplits();

  /**
   * Creates a reader for the split of a dataset.
   * @param split The split to create a reader for.
   * @return instance The instance of a {@link SplitReader}.
   */
  SplitReader<KEY, VALUE> createSplitReader(Split split);
}

Fix checkstyle from javadocs-changes PR


/*
 * Copyright 2015 Delft University of Technology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.tudelft.graphalytics.util;

import java.util.UUID;

/**
 * @author Wing Lung Ngai
 */
public class UuidUtil {

    public static String getRandomUUID() {
        return String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
    }

    public static String getRandomUUID(String prefix, int length) {
        return prefix + String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l).substring(0, length);
    }

    public static String getRandomUUID(int length) {
        return getRandomUUID("", length);
    }

}

/*
 * Copyright 2015 Delft University of Technology
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package nl.tudelft.graphalytics.util;

import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

/**
 * @author Wing Lung Ngai
 */
public class UuidUtil {

    private static Set<String> usedUUIDs = new HashSet<>();

    public static String getRandomUUID() {
        String uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);

        while(usedUUIDs.contains(uuid)) {
            uuid = String.valueOf(UUID.randomUUID().getLeastSignificantBits() * -1l);
        }
        usedUUIDs.add(uuid);

        return uuid;
    }

    public static String getRandomUUID(String prefix, int length) {
        String uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));

        while(usedUUIDs.contains(uuid)) {
            uuid = prefix + String.valueOf(getRandomUUID().substring(0, length));
        }
        usedUUIDs.add(uuid);

        return uuid;
    }

    public static String getRandomUUID(int length) {
        return getRandomUUID("", length);
    }

}

Make sure short UUIDs are unique in the same benchmark.


/**
 * Provides interfaces and classes of basic data structures.
 *
 * @author Julian Mendez
 */
package org.wikidata.wdtk.storage.datastructure;

/*
 * #%L
 * Wikidata Toolkit Storage
 * %%
 * Copyright (C) 2014 Wikidata Toolkit Developers
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

Add comment with license information


package edu.northwestern.bioinformatics.studycalendar.domain;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * @author Rhett Sutphin
 */
@Entity
@Table(name = "ae_notifications")
@GenericGenerator(name="id-generator", strategy = "native",
    parameters = {
        @Parameter(name="sequence", value="seq_adverse_event_notifications_id")
    }
)
public class AdverseEventNotification extends AbstractDomainObject {
    private StudyParticipantAssignment assignment;
    private AdverseEvent adverseEvent;
    private boolean dismissed;

    ////// BEAN PROPERTIES

    @ManyToOne
    public StudyParticipantAssignment getAssignment() {
        return assignment;
    }

    public void setAssignment(StudyParticipantAssignment assignment) {
        this.assignment = assignment;
    }

    @OneToOne
    @JoinColumn(name="adverse_event_id")
    @Cascade(CascadeType.ALL)
    public AdverseEvent getAdverseEvent() {
        return adverseEvent;
    }

    public void setAdverseEvent(AdverseEvent adverseEvent) {
        this.adverseEvent = adverseEvent;
    }

    public boolean isDismissed() {
        return dismissed;
    }

    public void setDismissed(boolean dismissed) {
        this.dismissed = dismissed;
    }
}

package edu.northwestern.bioinformatics.studycalendar.domain;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

import javax.persistence.Entity;
import javax.persistence.OneToOne;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * @author Rhett Sutphin
 */
@Entity
@Table(name = "ae_notifications")
@GenericGenerator(name="id-generator", strategy = "native",
    parameters = {
        @Parameter(name="sequence", value="seq_ae_notifications_id")
    }
)
public class AdverseEventNotification extends AbstractDomainObject {
    private StudyParticipantAssignment assignment;
    private AdverseEvent adverseEvent;
    private boolean dismissed;

    ////// BEAN PROPERTIES

    @ManyToOne
    public StudyParticipantAssignment getAssignment() {
        return assignment;
    }

    public void setAssignment(StudyParticipantAssignment assignment) {
        this.assignment = assignment;
    }

    @OneToOne
    @JoinColumn(name="adverse_event_id")
    @Cascade(CascadeType.ALL)
    public AdverseEvent getAdverseEvent() {
        return adverseEvent;
    }

    public void setAdverseEvent(AdverseEvent adverseEvent) {
        this.adverseEvent = adverseEvent;
    }

    public boolean isDismissed() {
        return dismissed;
    }

    public void setDismissed(boolean dismissed) {
        this.dismissed = dismissed;
    }
}

Correct sequence name for oracle


package com.studio4plus.homerplayer;

import android.database.ContentObserver;
import android.os.Handler;

import com.studio4plus.homerplayer.events.MediaStoreUpdateEvent;

import de.greenrobot.event.EventBus;

public class MediaStoreUpdateObserver extends ContentObserver {

    private static final int RESCAN_DELAY_MS = 15000;

    private final Handler mainThreadHandler;

    public MediaStoreUpdateObserver(Handler mainThreadHandler) {
        super(mainThreadHandler);
        this.mainThreadHandler = mainThreadHandler;
    }

    @Override
    public void onChange(boolean selfChange) {
        mainThreadHandler.removeCallbacks(delayedRescanTask);
        mainThreadHandler.postDelayed(delayedRescanTask, RESCAN_DELAY_MS);
    }

    private final Runnable delayedRescanTask = new Runnable() {
        @Override
        public void run() {
            EventBus.getDefault().post(new MediaStoreUpdateEvent());
        }
    };
}

package com.studio4plus.homerplayer;

import android.database.ContentObserver;
import android.os.Handler;

import com.studio4plus.homerplayer.events.MediaStoreUpdateEvent;

import de.greenrobot.event.EventBus;

/**
 * Observe for changes to media files and post a MediaStoreUpdateEvent to the event bus to trigger
 * a scan for new audiobooks.
 *
 * The onChange method may be called a number of times as media files are being changed on the
 * device. To avoid rescanning often, a rescan is triggered only after RESCAN_DELAY_MS milliseconds
 * have passed since the last onChange call.
 */
public class MediaStoreUpdateObserver extends ContentObserver {

    private static final int RESCAN_DELAY_MS = 5000;

    private final Handler mainThreadHandler;

    public MediaStoreUpdateObserver(Handler mainThreadHandler) {
        super(mainThreadHandler);
        this.mainThreadHandler = mainThreadHandler;
    }

    @Override
    public void onChange(boolean selfChange) {
        mainThreadHandler.removeCallbacks(delayedRescanTask);
        mainThreadHandler.postDelayed(delayedRescanTask, RESCAN_DELAY_MS);
    }

    private final Runnable delayedRescanTask = new Runnable() {
        @Override
        public void run() {
            EventBus.getDefault().post(new MediaStoreUpdateEvent());
        }
    };
}

Reduce the audiobooks rescan delay to 5s.


package org.unitedinternet.cosmo.ext;

import java.util.HashSet;
import java.util.Set;

import org.unitedinternet.cosmo.model.ICalendarItem;
import org.unitedinternet.cosmo.model.NoteItem;
import org.unitedinternet.cosmo.model.hibernate.EntityConverter;

import net.fortuna.ical4j.model.Calendar;

/**
 * Helper class that allows translating Calendar objects to NoteItem-s.
 *
 * @author daniel grigore
 *
 */
public class ContentConverter {

    private final EntityConverter entityConverter;

    public ContentConverter(EntityConverter entityConverter) {
        super();
        this.entityConverter = entityConverter;
    }

    public Set<NoteItem> asItems(Calendar calendar) {
        Set<NoteItem> items = new HashSet<>();
        if (calendar != null) {
            Set<ICalendarItem> calendarItems = this.entityConverter.convertCalendar(calendar);

            for (ICalendarItem item : calendarItems) {
                /**
                 * Only VEVENT are supported currently. VTODO or VJOURNAL are not yet supported.
                 */
                if (item instanceof NoteItem) {
                    items.add((NoteItem) item);
                    item.setName(item.getIcalUid() + ".ics");
                }
            }
        }
        return items;
    }
}

package org.unitedinternet.cosmo.ext;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.unitedinternet.cosmo.model.ICalendarItem;
import org.unitedinternet.cosmo.model.NoteItem;
import org.unitedinternet.cosmo.model.hibernate.EntityConverter;
import org.unitedinternet.cosmo.model.hibernate.HibNoteItem;

import net.fortuna.ical4j.model.Calendar;

/**
 * Helper class that allows translating Calendar objects to NoteItem-s.
 *
 * @author daniel grigore
 *
 */
public class ContentConverter {

    private final EntityConverter entityConverter;

    public ContentConverter(EntityConverter entityConverter) {
        super();
        this.entityConverter = entityConverter;
    }

    public Set<NoteItem> asItems(Calendar calendar) {
        Set<NoteItem> items = new HashSet<>();
        if (calendar != null) {
            Set<ICalendarItem> calendarItems = this.entityConverter.convertCalendar(calendar);

            for (ICalendarItem item : calendarItems) {
                /**
                 * Only VEVENT are supported currently. VTODO or VJOURNAL are not yet supported.
                 */
                if (item instanceof HibNoteItem) {
                    HibNoteItem noteItem = (HibNoteItem) item;
                    Date now = new Date();
                    noteItem.setCreationDate(now);
                    noteItem.setModifiedDate(now);
                    items.add(noteItem);
                    noteItem.setName(noteItem.getIcalUid() + ".ics");
                }
            }
        }
        return items;
    }
}

Set creationDate and modifiedDate when reading content from external sources to be able to calculate different eTag.


package cloud.cluster.sim.requestsimulator.dao;

import cloud.cluster.sim.requestsimulator.dto.SimulationStatistics;
import org.springframework.data.mongodb.repository.MongoRepository;

/**
 * Define operations on SimulationStatistics
 */
public interface SimulationStatisticsOperations extends MongoRepository<SimulationStatistics, String> {
}

package cloud.cluster.sim.requestsimulator.dao;

import cloud.cluster.sim.requestsimulator.dto.SimulationStatistics;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Component;

/**
 * Define operations on SimulationStatistics
 */
@Component
public interface SimulationStatisticsOperations extends MongoRepository<SimulationStatistics, String> {
}

Add component annotation in order to be able to auto wire component.


package cgeo.geocaching.utils;

import cgeo.geocaching.BuildConfig;

public class BranchDetectionHelper {

    // should contain the version name of the last feature release
    public static final String FEATURE_VERSION_NAME = "2022.09.19-RC";

    // should contain version names of active bugfix releases since last feature release, oldest first
    // empty the part within curly brackets when creating a new release branch from master
    public static final String[] BUGFIX_VERSION_NAME = new String[]{ };

    private BranchDetectionHelper() {
        // utility class
    }

    /**
     * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy)
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isProductionBuild() {
        return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly"));
    }

    /**
     * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build!
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isDeveloperBuild() {
        return BuildConfig.BUILD_TYPE.equals("debug");
    }

}

package cgeo.geocaching.utils;

import cgeo.geocaching.BuildConfig;

public class BranchDetectionHelper {

    // should contain the version name of the last feature release
    public static final String FEATURE_VERSION_NAME = "2022.10.16";

    // should contain version names of active bugfix releases since last feature release, oldest first
    // empty the part within curly brackets when creating a new release branch from master
    public static final String[] BUGFIX_VERSION_NAME = new String[]{ };

    private BranchDetectionHelper() {
        // utility class
    }

    /**
     * @return true, if BUILD_TYPE is not a nightly or debug build (e. g.: release, rc, legacy)
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isProductionBuild() {
        return !(BuildConfig.BUILD_TYPE.equals("debug") || BuildConfig.BUILD_TYPE.equals("nightly"));
    }

    /**
     * @return true, if BUILD_TYPE is a debug build. Nightly builds are **not** considered as developer build!
     */
    // BUILD_TYPE is detected as constant but can change depending on the build configuration
    @SuppressWarnings("ConstantConditions")
    public static boolean isDeveloperBuild() {
        return BuildConfig.BUILD_TYPE.equals("debug");
    }

}

Prepare version number for upcoming release


package ee.tuleva.onboarding.aml;

import ee.tuleva.onboarding.user.User;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import java.time.Instant;

@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class AmlCheck {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private User user;

    @Enumerated(value = EnumType.STRING)
    private AmlCheckType type;

    private boolean success;

    @CreatedDate
    private Instant createdTime;

    @PrePersist
    protected void onCreate() {
        createdTime = Instant.now();
    }
}

package ee.tuleva.onboarding.aml;

import ee.tuleva.onboarding.user.User;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;

import javax.persistence.*;
import java.time.Instant;

@Entity
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@ToString(exclude = {"user"})
public class AmlCheck {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne
    private User user;

    @Enumerated(value = EnumType.STRING)
    private AmlCheckType type;

    private boolean success;

    @CreatedDate
    private Instant createdTime;

    @PrePersist
    protected void onCreate() {
        createdTime = Instant.now();
    }
}

Exclude user from to string


package com.uwetrottmann.getglue.services;

import com.uwetrottmann.getglue.BaseTestCase;
import com.uwetrottmann.getglue.entities.GetGlueInteraction;
import com.uwetrottmann.getglue.entities.GetGlueInteractionResource;

import java.util.List;

import static org.fest.assertions.api.Assertions.assertThat;

public class InteractionServiceTest extends BaseTestCase {

    public static final String SAMPLE_INTERACTION = "getgluejava/2013-10-24T18:30:38Z";

    public void test_get() {
        InteractionService service = getManager().interactionService();
        GetGlueInteractionResource resource = service.get(SAMPLE_INTERACTION);
        assertThat(resource).isNotNull();
        assertThat(resource.interaction).isNotNull();
        assertThat(resource.interaction._object).isNotNull();
        assertThat(resource.interaction._object.id).isEqualTo("tv_shows/how_i_met_your_mother");
        assertThat(resource.interaction._object.title).isEqualTo("How I Met Your Mother");
    }

    public void test_votes() {
        InteractionService service = getManager().interactionService();
        List<GetGlueInteraction> resource = service.votes(SAMPLE_INTERACTION);
        assertThat(resource).isNotNull();
    }

    public void test_replies() {
        InteractionService service = getManager().interactionService();
        List<GetGlueInteraction> resource = service.replies(SAMPLE_INTERACTION);
        assertThat(resource).isNotNull();
    }

}

package com.uwetrottmann.getglue.services;

import com.uwetrottmann.getglue.BaseTestCase;
import com.uwetrottmann.getglue.entities.GetGlueInteraction;
import com.uwetrottmann.getglue.entities.GetGlueInteractionResource;

import java.util.List;

import static org.fest.assertions.api.Assertions.assertThat;

public class InteractionServiceTest extends BaseTestCase {

    public static final String SAMPLE_INTERACTION = "getgluejava/2013-10-24T18:30:38Z";

    public void test_get() {
        InteractionService service = getManager().interactionService();
        GetGlueInteractionResource resource = service.get(SAMPLE_INTERACTION);
        assertThat(resource).isNotNull();
        assertThat(resource.interaction).isNotNull();
        assertThat(resource.interaction._object).isNotNull();
        assertThat(resource.interaction._object.id).isEqualTo("tv_shows/how_i_met_your_mother");
        assertThat(resource.interaction._object.title).isEqualTo("How I Met Your Mother");
        assertThat(resource.interaction.comment).isEqualTo("Testing getglue-java.");
    }

    public void test_votes() {
        InteractionService service = getManager().interactionService();
        List<GetGlueInteraction> resource = service.votes(SAMPLE_INTERACTION);
        assertThat(resource).isNotNull();
    }

    public void test_replies() {
        InteractionService service = getManager().interactionService();
        List<GetGlueInteraction> resource = service.replies(SAMPLE_INTERACTION);
        assertThat(resource).isNotNull();
    }

}

Test for new comment property.


package tars.commons.events.model;

import tars.commons.events.BaseEvent;
import tars.model.ReadOnlyTars;

/** Indicates the Tars in the model has changed*/
public class TarsChangedEvent extends BaseEvent {

    public final ReadOnlyTars data;

    public TarsChangedEvent(ReadOnlyTars data){
        this.data = data;
    }

    @Override
    public String toString() {
        return "number of tasks " + data.getTaskList().size() + ", number of tags " + 0;
    }
}

package tars.commons.events.model;

import tars.commons.events.BaseEvent;
import tars.model.ReadOnlyTars;

/** Indicates the Tars in the model has changed*/
public class TarsChangedEvent extends BaseEvent {

    public final ReadOnlyTars data;

    public TarsChangedEvent(ReadOnlyTars data){
        this.data = data;
    }

    @Override
    public String toString() {
        return "number of tasks " + data.getTaskList().size() + ", number of tags " + data.getTagList().size();
    }
}

Update back the correct version


package org.hummingbirdlang.types.composite;

import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;

/**
 * Disjoint union type (aka. sum type): it is composed of members A and B.
 * Eventually the union is discriminated into either A or B.
 */
public class SumType extends CompositeType {
  public final Type[] subTypes;

  public SumType(Type[] subTypes) {
    this.subTypes = subTypes;
  }

  @Override
  public Property getProperty(String name) throws PropertyNotFoundException {
    throw new PropertyNotFoundException("Not yet implemented");
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder();
    boolean bar = false;
    for (Type subType : this.subTypes) {
      if (bar) {
        result.append(" | ");
      } else {
        bar = true;
      }
      result.append(subType.toString());
    }
    return result.toString();
  }
}

package org.hummingbirdlang.types.composite;

import org.hummingbirdlang.types.CompositeType;
import org.hummingbirdlang.types.Property;
import org.hummingbirdlang.types.PropertyNotFoundException;
import org.hummingbirdlang.types.Type;

/**
 * Disjoint union type (aka. sum type): it is composed of members A and B.
 * Eventually the union is discriminated into either A or B.
 */
public class SumType extends CompositeType {
  public final Type[] subTypes;

  public SumType(Type[] subTypes) {
    this.subTypes = subTypes;
  }

  @Override
  public Property getProperty(String name) throws PropertyNotFoundException {
    throw new PropertyNotFoundException("Not yet implemented");
  }

  /**
   * Other type must be equal to or smaller than this union for equality
   * to hold.
   */
  @Override
  public boolean equals(Type otherType) {
    // Equality check first.
    if (this == otherType) {
      return true;
    }
    // Then check if we contain the other type.
    for (Type subType : this.subTypes) {
      if (subType.equals(otherType)) {
        return true;
      }
    }
    return false;
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder();
    boolean bar = false;
    for (Type subType : this.subTypes) {
      if (bar) {
        result.append(" | ");
      } else {
        bar = true;
      }
      result.append(subType.toString());
    }
    return result.toString();
  }
}

Add basic type equality checking to sum type


package pl.tomaszdziurko.jvm_bloggers;

/**
 * UTM (Urchin Traffic Monitor) URL query parameter identifiers.
 *
 * @see UTM Parameters
 * @author cslysy <jakub.sprega@gmail.com>
 */
public class UtmParameters {

    public static final String UTM_SOURCE_KEY = "utm_source";

    public static final String UTM_MEDIUM_KEY = "utm_medium";

    public static final String UTM_CAMPAIGN_KEY = "utm_campaign";
}

Fix javadoc with escaped < and > characters


package info.u_team.u_team_test.init;

import info.u_team.u_team_core.api.construct.*;
import info.u_team.u_team_core.util.registry.BusRegister;

@Construct
public class TestCommonBusRegister implements IModConstruct {

	@Override
	public void construct() {
		BusRegister.registerMod(TestBiomes::registerMod);
		BusRegister.registerMod(TestBlocks::registerMod);
		BusRegister.registerMod(TestContainers::registerMod);
		BusRegister.registerMod(TestEffects::registerMod);
		BusRegister.registerMod(TestEnchantments::registerMod);
		BusRegister.registerMod(TestEntityTypes::registerMod);
		BusRegister.registerMod(TestGlobalLootModifiers::registerMod);
		BusRegister.registerMod(TestItems::registerMod);
		BusRegister.registerMod(TestModDimensions::registerMod);
		BusRegister.registerMod(TestPotions::registerMod);
		BusRegister.registerMod(TestSounds::registerMod);
		BusRegister.registerMod(TestTileEntityTypes::registerMod);
	}

}

package info.u_team.u_team_test.init;

import info.u_team.u_team_core.api.construct.*;
import info.u_team.u_team_core.util.registry.BusRegister;
import info.u_team.u_team_test.TestMod;

@Construct(modid = TestMod.MODID)
public class TestCommonBusRegister implements IModConstruct {

	@Override
	public void construct() {
		BusRegister.registerMod(TestBiomes::registerMod);
		BusRegister.registerMod(TestBlocks::registerMod);
		BusRegister.registerMod(TestContainers::registerMod);
		BusRegister.registerMod(TestEffects::registerMod);
		BusRegister.registerMod(TestEnchantments::registerMod);
		BusRegister.registerMod(TestEntityTypes::registerMod);
		BusRegister.registerMod(TestGlobalLootModifiers::registerMod);
		BusRegister.registerMod(TestItems::registerMod);
		BusRegister.registerMod(TestModDimensions::registerMod);
		BusRegister.registerMod(TestPotions::registerMod);
		BusRegister.registerMod(TestSounds::registerMod);
		BusRegister.registerMod(TestTileEntityTypes::registerMod);
	}

}

Add the new modid field in the common construct bus register


package uk.ac.ebi.ddi.extservices.net;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FtpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FtpUtils.class);

    public static List<String> getListFiles(FTPClient client, String path, String... ignoreDir) {
        List<String> result = new ArrayList<>();
        for (String dir : ignoreDir) {
            if (path.equals(dir)) {
                return result;
            }
        }
        try {
            if (!client.changeWorkingDirectory(path)) {
                return Collections.emptyList();
            }
            FTPFile[] ftpFiles = client.listFiles();
            for (FTPFile file : ftpFiles) {
                if (!file.getName().equals(".") && !file.getName().equals("..")) {
                    if (file.isDirectory()) {
                        result.addAll(getListFiles(client, file.getName(), ignoreDir));
                    } else {
                        String link = String.format("%s/%s", client.printWorkingDirectory(), file.getName());
                        result.add(link);
                    }
                }
            }
            client.changeToParentDirectory();
        } catch (Exception e) {
            LOGGER.error("Exception occurred when listing ftp files of {}, ", path, e);
        }
        return result;
    }
}

package uk.ac.ebi.ddi.extservices.net;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class FtpUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(FtpUtils.class);

    public static List<String> getListFiles(FTPClient client, String path, String... ignoreDir) throws IOException {
        List<String> result = new ArrayList<>();
        for (String dir : ignoreDir) {
            if (path.equals(dir)) {
                return result;
            }
        }
        if (!client.changeWorkingDirectory(path)) {
            return Collections.emptyList();
        }
        FTPFile[] ftpFiles = client.listFiles();
        for (FTPFile file : ftpFiles) {
            if (!file.getName().equals(".") && !file.getName().equals("..")) {
                if (file.isDirectory()) {
                    result.addAll(getListFiles(client, file.getName(), ignoreDir));
                } else {
                    String link = String.format("%s/%s", client.printWorkingDirectory(), file.getName());
                    result.add(link);
                }
            }
        }
        client.changeToParentDirectory();
        return result;
    }
}

Throw exception right away if it happen to avoid repeatedly throwing exceptions.


/*
	Block comment example.
*/

int i,j; // Global variables
int f(int a) { // f function
    return a;
}

void main() { // Main function
    int i,b; // Local variables
    double r;
    char c;
    int[10] v; // Array

    i = 1;
    r = 12.3 - 34.12E-3 * 2. + 3e3;
    c = '\126';

    b = v[2];
    if (1 && 2 || !0) {
        i = b;
    }

    while (i<10) {
        i=i+1;
        j=i;
    }
}

/*
	Block comment example.
*/

int i,j; // Global variables
int f(int a) { // f function
    return a;
}

void main() { // Main function
    int i,b; // Local variables
    double r;
    char c;
    int[10] v; // Array

    i = 1++;
    r = 12.3 - 34.12E-3 * 2. + 3e3;
    c = '\126';

    b = v[2];
    if (1 && 2 || !0) {
        i = b;
    }

    while (i<=10) {
        i=i+1;
        j=i;
    }
}

Update file to test more rules


package tropicalescape;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;

import tropicalescape.physics.Hitbox;

public class Flag extends GameObject {

	static final int DESC_HEIGHT_SHIFT = 15;
	static final String IMG_FILE = "res/flag.png";

	String m_desc;
	static Image m_img;

	static {
		try {
			m_img = new Image(IMG_FILE);
		} catch (SlickException e) {
			e.printStackTrace();
		}
	}

	Flag(String desc, float x, float y) {
		super(new Hitbox());
		m_desc = desc;
		getPosition().x = x;
		getPosition().y = y;
	}

	@Override
	public void render(Graphics g) {
		m_img.draw();
		if (getPosition().y - DESC_HEIGHT_SHIFT < 0) {
			g.drawString(m_desc, 0, m_img.getHeight());
		} else {
			g.drawString(m_desc, 0, -DESC_HEIGHT_SHIFT);
		}
	}

	@Override
	public void update(int delta) {
	}
}

package tropicalescape;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Vector2f;

import tropicalescape.physics.Hitbox;

public class Flag extends GameObject {

	static final int DESC_HEIGHT_SHIFT = 15;
	static final String IMG_FILE = "res/flag.png";

	String m_desc;
	static Image m_img;

	static {
		try {
			m_img = new Image(IMG_FILE);
		} catch (SlickException e) {
			e.printStackTrace();
		}
	}

	Flag(String desc, float x, float y) {
		super(new Hitbox());
		m_desc = desc;
		getPosition().x = x;
		getPosition().y = y;
	}

	@Override
	public void render(Graphics g) {
		Vector2f pos = getPosition();
		m_img.draw(pos.x, pos.y);
		if (getPosition().y - DESC_HEIGHT_SHIFT < 0) {
			g.drawString(m_desc, pos.x, m_img.getHeight());
		} else {
			g.drawString(m_desc, pos.x, pos.y - DESC_HEIGHT_SHIFT);
		}
	}

	@Override
	public void update(int delta) {
	}
}

Fix : Render du flag


package org.crunchytorch.coddy.snippet.service;

import org.crunchytorch.coddy.application.exception.EntityNotFoundException;
import org.crunchytorch.coddy.application.service.AbstractService;
import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity;
import org.crunchytorch.coddy.snippet.elasticsearch.repository.SnippetRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.SecurityContext;
import java.util.Date;

@Service
public class SnippetService extends AbstractService<SnippetEntity> {

    @Autowired
    public SnippetService(SnippetRepository repository) {
        super(repository);
    }

    public SnippetEntity getSnippet(String id) {
        SnippetEntity entity = this.repository.findOne(id);

        if (entity == null) {
            throw new EntityNotFoundException("snippet with the id : " + id + " not found");
        }

        return entity;
    }

    public SnippetEntity create(SnippetEntity entity, SecurityContext securityContext) {
        // Set date to now
        Date now = new Date();
        entity.setCreated(now);
        entity.setLastModified(now);
        // Set author from token information
        entity.setAuthor(securityContext.getUserPrincipal().getName());
        // Initiate rate
        entity.setRate(0);
        return super.create(entity);
    }
}

package org.crunchytorch.coddy.snippet.service;

import org.crunchytorch.coddy.application.exception.EntityNotFoundException;
import org.crunchytorch.coddy.application.service.AbstractService;
import org.crunchytorch.coddy.snippet.elasticsearch.entity.SnippetEntity;
import org.crunchytorch.coddy.snippet.elasticsearch.repository.SnippetRepository;
import org.crunchytorch.coddy.user.data.security.JWTPrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.ws.rs.core.SecurityContext;
import java.util.Date;

@Service
public class SnippetService extends AbstractService<SnippetEntity> {

    @Autowired
    public SnippetService(SnippetRepository repository) {
        super(repository);
    }

    public SnippetEntity getSnippet(String id) {
        SnippetEntity entity = this.repository.findOne(id);

        if (entity == null) {
            throw new EntityNotFoundException("snippet with the id : " + id + " not found");
        }

        return entity;
    }

    public SnippetEntity create(SnippetEntity entity, SecurityContext securityContext) {
        // Set date to now
        Date now = new Date();
        entity.setCreated(now);
        entity.setLastModified(now);
        // Set author from token information
        entity.setAuthor(((JWTPrincipal) securityContext.getUserPrincipal()).getLogin());
        // Initiate rate
        entity.setRate(0);
        return super.create(entity);
    }
}

Use login instead of user's name.


package com.nigorojr.typebest;

import java.sql.SQLException;
import java.util.LinkedHashMap;

public class Tester {

    public static void main(String[] args) {
        // This is to test the behavior of the Database class
        try {
            Records rec = new Records();
            System.out.println("exist?\n" + rec.isTableExist());
            LinkedHashMap<String, String> pair = new LinkedHashMap<String, String>();
            pair.put("foo", "int");
            pair.put("hoge", "varchar(50)");
            if (!rec.isTableExist()) {
                rec.createTable(pair);
            }
            System.out.println("finished creating...");
            LinkedHashMap<String, String> ins = new LinkedHashMap<String, String>();
            ins.put("foo", "50");
            ins.put("hoge", "'barbar'");
            rec.insert(ins);
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

package com.nigorojr.typebest;

import java.sql.SQLException;
import java.util.LinkedHashMap;

public class Tester {

    public static void main(String[] args) {
        // This is to test the behavior of the Database class
        try {
            Records rec = new Records();
            System.out.println("exist?\n" + rec.isTableExist());
            LinkedHashMap<String, String> pair = new LinkedHashMap<String, String>();
            pair.put("foo", "int");
            pair.put("hoge", "varchar(50)");
            if (!rec.isTableExist()) {
                rec.createTable(pair);
            }
            System.out.println("finished creating...");
            LinkedHashMap<String, String> ins = new LinkedHashMap<String, String>();
            ins.put("foo", "50");
            ins.put("hoge", "'barbar'");
            rec.insert(ins);

            // Test for Preferences class
            Preferences p = new Preferences("test_user");
            p.readPreferencesForID(1);
            System.out.println(p.getKeyboardLayout());
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

Add test for Preferences class


package fr.insee.pogues.config;

import org.apache.logging.log4j.web.Log4jServletContextListener;
import org.apache.logging.log4j.web.Log4jWebSupport;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class Log4j2ServletContextListener implements ServletContextListener {

    private String log4j2ConfigFile;

    private Log4jServletContextListener listener;

    public Log4j2ServletContextListener() {
        this.listener = new Log4jServletContextListener();
        this.log4j2ConfigFile = String.format("%s/log4j2.xml", System.getProperty("fr.insee.pogues.env"));
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().setInitParameter(
                Log4jWebSupport.LOG4J_CONFIG_LOCATION,
                log4j2ConfigFile);
        listener.contextInitialized(servletContextEvent);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) { }
}

package fr.insee.pogues.config;

import org.apache.logging.log4j.web.Log4jServletContextListener;
import org.apache.logging.log4j.web.Log4jWebSupport;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class Log4j2ServletContextListener implements ServletContextListener {

    private String log4j2ConfigFile;

    private Log4jServletContextListener listener;

    public Log4j2ServletContextListener() {
        this.listener = new Log4jServletContextListener();
        String env = System.getProperty("fr.insee.pogues.env");
        if(null == env) {
            env = "dv";
        }
        this.log4j2ConfigFile = String.format("%s/log4j2.xml", env);
    }

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        servletContextEvent.getServletContext().setInitParameter(
                Log4jWebSupport.LOG4J_CONFIG_LOCATION,
                log4j2ConfigFile);
        listener.contextInitialized(servletContextEvent);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) { }
}

Add default environment to logger: dv


package codechicken.lib.world;

import net.minecraft.world.chunk.ChunkPrimerWrapper;
import net.minecraft.world.chunk.IChunk;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;

public class TileChunkLoadHook {

    private static boolean init;

    public static void init() {
        if (init) {
            return;
        }
        init = true;

        MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook());
    }

    @SubscribeEvent
    public void onChunkLoad(ChunkEvent.Load event) {
        IChunk chunk = event.getChunk();
        if(chunk instanceof ChunkPrimerWrapper) {
            chunk = ((ChunkPrimerWrapper) chunk).func_217336_u();
        }
        chunk.getTileEntitiesPos().stream()//
                .map(chunk::getTileEntity)//
                .filter(e -> e instanceof IChunkLoadTile)//
                .map(e -> (IChunkLoadTile) e)//
                .forEach(IChunkLoadTile::onChunkLoad);
    }
}

package codechicken.lib.world;

import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.ChunkPrimer;
import net.minecraft.world.chunk.ChunkPrimerWrapper;
import net.minecraft.world.chunk.IChunk;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.ChunkEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;

import java.util.Map;

public class TileChunkLoadHook {

    private static boolean init;

    public static void init() {
        if (init) {
            return;
        }
        init = true;

        MinecraftForge.EVENT_BUS.register(new TileChunkLoadHook());
    }

    @SubscribeEvent
    public void onChunkLoad(ChunkEvent.Load event) {
        IChunk chunk = event.getChunk();
        Map<BlockPos, TileEntity> tiles = null;
        if (chunk instanceof ChunkPrimerWrapper) {
            chunk = ((ChunkPrimerWrapper) chunk).func_217336_u();
        }
        if (chunk instanceof Chunk) {
            tiles = ((Chunk) chunk).getTileEntityMap();
        }
        if (chunk instanceof ChunkPrimer) {
            tiles = ((ChunkPrimer) chunk).getTileEntities();
        }
        if (tiles != null) {
            for (TileEntity tile : tiles.values()) {
                if (tile instanceof IChunkLoadTile) {
                    ((IChunkLoadTile) tile).onChunkLoad();
                }
            }
        }
    }
}

Fix chunk load hook causing chunk loading deadlocks.


package ganymedes01.etfuturum.blocks;

import ganymedes01.etfuturum.EtFuturum;
import ganymedes01.etfuturum.IConfigurable;
import ganymedes01.etfuturum.core.utils.Utils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.util.ForgeDirection;

public class CoarseDirt extends Block implements IConfigurable {

	public CoarseDirt() {
		super(Material.ground);
		setHardness(0.5F);
		setStepSound(soundTypeGravel);
		setBlockTextureName("coarse_dirt");
		setBlockName(Utils.getUnlocalisedName("coarse_dirt"));
		setCreativeTab(EtFuturum.enableCoarseDirt ? EtFuturum.creativeTab : null);
	}

	@Override
	public boolean canSustainPlant(IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plant) {
		return Blocks.dirt.canSustainPlant(world, x, y, z, direction, plant);
	}

	@Override
	public boolean isEnabled() {
		return EtFuturum.enableCoarseDirt;
	}
}

package ganymedes01.etfuturum.blocks;

import ganymedes01.etfuturum.EtFuturum;
import ganymedes01.etfuturum.IConfigurable;
import ganymedes01.etfuturum.core.utils.Utils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.common.util.ForgeDirection;

public class CoarseDirt extends Block implements IConfigurable {

	public CoarseDirt() {
		super(Material.ground);
		setHardness(0.5F);
		setHarvestLevel("shovel", 0);
		setStepSound(soundTypeGravel);
		setBlockTextureName("coarse_dirt");
		setBlockName(Utils.getUnlocalisedName("coarse_dirt"));
		setCreativeTab(EtFuturum.enableCoarseDirt ? EtFuturum.creativeTab : null);
	}

	@Override
	public boolean canSustainPlant(IBlockAccess world, int x, int y, int z, ForgeDirection direction, IPlantable plant) {
		return Blocks.dirt.canSustainPlant(world, x, y, z, direction, plant);
	}

	@Override
	public boolean isEnabled() {
		return EtFuturum.enableCoarseDirt;
	}
}

Set a harvest level for coarse dirt.


// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// TODO: This implements the old, deprecated document HTTP= API. Remove on Vespa 7
/**
 * Exported not as an API, but specifically for SSBE.
 */
@ExportPackage
package com.yahoo.feedhandler;

import com.yahoo.osgi.annotation.ExportPackage;

// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
/**
 * Exported not as an API, but specifically for SSBE.
 */
@ExportPackage
package com.yahoo.feedhandler;

import com.yahoo.osgi.annotation.ExportPackage;

Remove wrong TODO - this is needed for vespafeeder


package com.ociweb.gateway;

import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.Hardware;
import com.ociweb.iot.maker.IoTSetup;

public class IoTApp implements IoTSetup
{
	private static String brokerURI;
	private static String clientId;
    private static String kafkaURI;

    public static void main( String[] args ) {

    	//parse the optional command line arguments
    	brokerURI = DeviceRuntime.getOptArg("--brokerURI", "-br", args, "tcp://localhost:1883");;
    	clientId = DeviceRuntime.getOptArg("--clientId", "-id", args, "unknownGateway");
        kafkaURI = DeviceRuntime.getOptArg("--kafkaURI", "-ku", args, "ec2-54-149-45-216.us-west-2.compute.amazonaws.com:9092");

        DeviceRuntime.run(new IoTApp());
    }

    @Override
    public void declareConnections(Hardware c) {
    }

    @Override
    public void declareBehavior(DeviceRuntime runtime) {

    	runtime.addStartupListener(new SubscribeDataMQTT(runtime, "#", "localPub", brokerURI, clientId ));

    	runtime.addPubSubListener(new PublishKafka(runtime, kafkaURI)).addSubscription("localPub");

    }

}

package com.ociweb.gateway;

import com.ociweb.iot.maker.DeviceRuntime;
import com.ociweb.iot.maker.Hardware;
import com.ociweb.iot.maker.IoTSetup;

public class IoTApp implements IoTSetup
{
	private static String brokerURI;
	private static String clientId;
    private static String kafkaURI;

    public static void main( String[] args ) {

    	//parse the optional command line arguments
    	brokerURI = DeviceRuntime.getOptArg("--brokerURI", "-br", args, "tcp://localhost:1883");;
    	clientId = DeviceRuntime.getOptArg("--clientId", "-id", args, "unknownGateway");
        kafkaURI = DeviceRuntime.getOptArg("--kafkaURI", "-ku", args, "localhost:9092");

        DeviceRuntime.run(new IoTApp());
    }

    @Override
    public void declareConnections(Hardware c) {
    }

    @Override
    public void declareBehavior(DeviceRuntime runtime) {

    	runtime.addStartupListener(new SubscribeDataMQTT(runtime, "#", "localPub", brokerURI, clientId ));

    	runtime.addPubSubListener(new PublishKafka(runtime, kafkaURI)).addSubscription("localPub");

    }

}

Change default KafkaURI to localhost


package chat.rocket.android.widget;

import android.content.Context;
import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator;
import com.facebook.common.logging.FLog;
import com.facebook.drawee.backends.pipeline.DraweeConfig;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.listener.RequestListener;
import com.facebook.imagepipeline.listener.RequestLoggingListener;
import java.util.HashSet;
import java.util.Set;
import okhttp3.OkHttpClient;

public class RocketChatWidgets {

  public static void initialize(Context context, OkHttpClient okHttpClient) {
    FLog.setMinimumLoggingLevel(FLog.VERBOSE);
    Set<RequestListener> listeners = new HashSet<>();
    listeners.add(new RequestLoggingListener());

    ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory
        .newBuilder(context, okHttpClient)
        .setRequestListeners(listeners)
        .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig())
        .setDownsampleEnabled(true)
        .experiment().setBitmapPrepareToDraw(true)
        .experiment().setPartialImageCachingEnabled(true)
        .build();

    DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder();
    CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder);

    Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build());
    FLog.setMinimumLoggingLevel(FLog.ERROR);
  }
}

package chat.rocket.android.widget;

import android.content.Context;
import chat.rocket.android.widget.fresco.CustomImageFormatConfigurator;
import com.facebook.common.logging.FLog;
import com.facebook.drawee.backends.pipeline.DraweeConfig;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.listener.RequestListener;
import com.facebook.imagepipeline.listener.RequestLoggingListener;
import java.util.HashSet;
import java.util.Set;
import okhttp3.OkHttpClient;

public class RocketChatWidgets {

  public static void initialize(Context context, OkHttpClient okHttpClient) {
    FLog.setMinimumLoggingLevel(FLog.VERBOSE);
    Set<RequestListener> listeners = new HashSet<>();
    listeners.add(new RequestLoggingListener());

    ImagePipelineConfig imagePipelineConfig = OkHttpImagePipelineConfigFactory
        .newBuilder(context, okHttpClient)
        .setRequestListeners(listeners)
        .setImageDecoderConfig(CustomImageFormatConfigurator.createImageDecoderConfig())
        .setDownsampleEnabled(true)
        .experiment().setBitmapPrepareToDraw(true)
        .experiment().setPartialImageCachingEnabled(true)
        .build();

    DraweeConfig.Builder draweeConfigBuilder = DraweeConfig.newBuilder();
    CustomImageFormatConfigurator.addCustomDrawableFactories(draweeConfigBuilder);

    Fresco.initialize(context, imagePipelineConfig, draweeConfigBuilder.build());
  }
}

Set back Fresco logger to verbose


package openperipheral.integration.vanilla;

import java.util.Map;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.Vec3;
import openperipheral.api.helpers.EntityMetaProviderSimple;

import com.google.common.collect.Maps;

public class EntityPlayerMetaProvider extends EntityMetaProviderSimple<EntityPlayer> {

	@Override
	public String getKey() {
		return "player";
	}

	@Override
	public Object getMeta(EntityPlayer target, Vec3 relativePos) {
		Map<String, Object> map = Maps.newHashMap();

		map.put("inventory", InventoryMetaProvider.wrapToProxyTable(target.inventory));
		map.put("isAirBorne", target.isAirBorne);
		map.put("isBlocking", target.isBlocking());
		map.put("profile", target.getGameProfile());
		map.put("foodLevel", target.getFoodStats().getFoodLevel());
		map.put("isCreativeMode", target.capabilities.isCreativeMode);

		return map;
	}

}

package openperipheral.integration.vanilla;

import java.util.Map;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.Vec3;
import openperipheral.api.helpers.EntityMetaProviderSimple;

import com.google.common.collect.Maps;

public class EntityPlayerMetaProvider extends EntityMetaProviderSimple<EntityPlayer> {

	@Override
	public String getKey() {
		return "player";
	}

	@Override
	public Object getMeta(EntityPlayer target, Vec3 relativePos) {
		Map<String, Object> map = Maps.newHashMap();

		map.put("inventory", InventoryMetaProvider.wrapToProxyTable(target.inventory));
		map.put("isAirBorne", target.isAirBorne);
		map.put("isBlocking", target.isBlocking());
		map.put("profile", target.getGameProfile());
		map.put("foodLevel", target.getFoodStats().getFoodLevel());
		map.put("isCreativeMode", target.capabilities.isCreativeMode);

		Map<String, Object> experience = Maps.newHashMap();
		experience.put("level", target.experienceLevel);
		experience.put("levelProgress", target.experience);
		experience.put("nextLevelXp", target.xpBarCap());
		map.put("experience", experience);

		return map;
	}

}

Add information about player experience to meta provider


package com.example.android.quakereport;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import java.util.List;

/**
 * Created by Lenovo on 7/6/2017.
 */

public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>>
{
    final static String LOG_TAG = EarthquakeLoader.class.getSimpleName();
    private String mUrl;

    //TODO: Extract the earthquake data from the USGS url

    public EarthquakeLoader(Context context, String url)
    {
        super(context);
        this.mUrl = url;
    }

    @Override
    protected void onStartLoading()
    {
        forceLoad();
    }

    @Override
    public List<Earthquake> loadInBackground()
    {
        List<Earthquake> result = null;

        // Don't perform the request if there are no URLs, or the first URL
        if(getUrl().length() < 1)
            return null;
        try
        {
            // Perform the HTTP request for earthquake data and process the response.
            result = QueryUtils.fetchEarthquakeData(getUrl());

        }catch (SecurityException e)
        {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
        return result;
    }

    //@return the url of the earthquake data to the displayed
    public String getUrl()
    {
        return mUrl;
    }
}

package com.example.android.quakereport;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import java.util.List;

/**
 * Created by Lenovo on 7/6/2017.
 */

/*
   Loads a list of earthquakes by using an AsyncTaskLoader to perform the
   network request to the destination(USGS) url.
 */
public class EarthquakeLoader extends AsyncTaskLoader<List<Earthquake>>
{
    /* Tag for log messages */
    private final static String LOG_TAG = EarthquakeLoader.class.getSimpleName();

    /* Query URL */
    private String mUrl;

    //TODO: Extract the earthquake data from the USGS url

    public EarthquakeLoader(Context context, String url)
    {
        super(context);
        this.mUrl = url;
    }

    @Override
    protected void onStartLoading()
    {
        forceLoad();
    }

    /*
     * Run the earthquake data request in the background
     */
    @Override
    public List<Earthquake> loadInBackground()
    {
        List<Earthquake> earthquakes = null;

        // Don't perform the request if there are no URLs, or the first URL
        if(mUrl == null)
            return null;
        try
        {
            /* Perform the HTTP request for earthquake data and process the response. */
            earthquakes = QueryUtils.fetchEarthquakeData(mUrl);

        }catch (SecurityException e)
        {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
        return earthquakes;
    }
}

Replace AsyncTask with AsyncTaskLoader and do some clean up.


package mil.nga.mapcache.io.network;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Makes http requests asynchronously.
 */
public class HttpClient {

    /**
     * The instance of this class.
     */
    private static final HttpClient instance = new HttpClient();

    /**
     * The thread pool.
     */
    private ExecutorService executor = Executors.newFixedThreadPool(4);

    /**
     * Gets the instance of this class.
     *
     * @return This class instance.
     */
    public static HttpClient getInstance() {
        return instance;
    }

    /**
     * Sends a http get to the specified url.
     *
     * @param url     The url to send a get request to.
     * @param handler The response handler, called when request is complete.
     */
    public void sendGet(String url, IResponseHandler handler) {
        HttpGetRequest request = new HttpGetRequest(url, handler);
        executor.execute(request);
    }

    /**
     * Private constructor, keep it a singleton.
     */
    private HttpClient() {
    }
}

package mil.nga.mapcache.io.network;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import mil.nga.mapcache.utils.ThreadUtils;

/**
 * Makes http requests asynchronously.
 */
public class HttpClient {

    /**
     * The instance of this class.
     */
    private static final HttpClient instance = new HttpClient();

    /**
     * Gets the instance of this class.
     *
     * @return This class instance.
     */
    public static HttpClient getInstance() {
        return instance;
    }

    /**
     * Sends a http get to the specified url.
     *
     * @param url     The url to send a get request to.
     * @param handler The response handler, called when request is complete.
     */
    public void sendGet(String url, IResponseHandler handler) {
        HttpGetRequest request = new HttpGetRequest(url, handler);
        ThreadUtils.getInstance().runBackground(request);
    }

    /**
     * Private constructor, keep it a singleton.
     */
    private HttpClient() {
    }
}

Use ThreadUtils instead of its own executor


/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */

package org.geomajas.layer;

import org.geomajas.global.Api;

import java.io.Serializable;

/**
 * <p>
 * Listing of all types of vector layers.
 * </p>
 *
 * @author Pieter De Graef
 * @since 1.6.0
 */
@Api(allMethods = true)
public enum LayerType implements Serializable {

	RASTER(1),
	POINT(2),
	LINESTRING(3),
	POLYGON(4),
	MULTIPOINT(5),
	MULTILINESTRING(6),
	MULTIPOLYGON(7);

	private int code;

	/**
	 * Create layer type.
	 *
	 * @param code code to apply
	 */
	private LayerType(int code) {
		this.code = code;
	}

	/**
	 * Convert to string.
	 *
	 * @return string representation of layer type
	 */
	public String toString() {
		return Integer.toString(code);
	}
}

/*
 * This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
 *
 * Copyright 2008-2011 Geosparc nv, http://www.geosparc.com/, Belgium.
 *
 * The program is available in open source according to the GNU Affero
 * General Public License. All contributions in this program are covered
 * by the Geomajas Contributors License Agreement. For full licensing
 * details, see LICENSE.txt in the project root.
 */

package org.geomajas.layer;

import org.geomajas.global.Api;

import java.io.Serializable;

/**
 * <p>
 * Listing of all types of vector layers.
 * </p>
 *
 * @author Pieter De Graef
 * @since 1.6.0
 */
@Api(allMethods = true)
public enum LayerType implements Serializable {

	RASTER(1),
	POINT(2),
	LINESTRING(3),
	POLYGON(4),
	MULTIPOINT(5),
	MULTILINESTRING(6),
	MULTIPOLYGON(7),
	GEOMETRY_COLLECTION(8);

	private int code;

	/**
	 * Create layer type.
	 *
	 * @param code code to apply
	 */
	private LayerType(int code) {
		this.code = code;
	}

	/**
	 * Convert to string.
	 *
	 * @return string representation of layer type
	 */
	public String toString() {
		return Integer.toString(code);
	}
}

Add support for mixed geometry type (GEOMETRY_COLLECTION)


/*
 * Created on 04-Feb-2004
 *
 * (c) 2003-2004 ThoughtWorks
 *
 * See license.txt for licence details
 */
package com.thoughtworks.proxy.toys.delegate;

import com.thoughtworks.proxy.ProxyFactory;
import com.thoughtworks.proxy.factory.StandardProxyFactory;

/**
 * @author Dan North
 */
public class Delegating {
    /** delegate must implement the method's interface */
    public static final boolean STATIC_TYPING = DelegatingInvoker.EXACT_METHOD;
    /** delegate must have method with matching signature - not necessarily the same */
    public static final boolean DYNAMIC_TYPING = DelegatingInvoker.SAME_SIGNATURE_METHOD;

    public static Object object(Class type, Object delegate) {
        return object(type, delegate, new StandardProxyFactory());
    }

    public static Object object(Class type, Object delegate, ProxyFactory factory) {
        return factory.createProxy(new Class[] {type}, new DelegatingInvoker(delegate));
    }

    /** It's a factory, stupid */
    private Delegating(){}
}

/*
 * Created on 04-Feb-2004
 *
 * (c) 2003-2004 ThoughtWorks
 *
 * See license.txt for licence details
 */
package com.thoughtworks.proxy.toys.delegate;

import com.thoughtworks.proxy.ProxyFactory;
import com.thoughtworks.proxy.factory.StandardProxyFactory;

/**
 * @author Dan North
 */
public class Delegating {
    /** delegate must implement the method's interface */
    public static final boolean STATIC_TYPING = DelegatingInvoker.EXACT_METHOD;
    /** delegate must have method with matching signature - not necessarily the same */
    public static final boolean DYNAMIC_TYPING = DelegatingInvoker.SAME_SIGNATURE_METHOD;

    public static Object object(Class type, Object delegate) {
        return object(type, delegate, new StandardProxyFactory());
    }

    public static Object object(Class type, Object delegate, ProxyFactory factory) {
        return factory.createProxy(
                new Class[] {type},
                new DelegatingInvoker(factory, new SimpleReference(delegate), DYNAMIC_TYPING));
    }

    /** It's a factory, stupid */
    private Delegating(){}
}

Fix possible mix of ProxyFactory instances.


// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.data;

import com.google.gerrit.entities.SubmitRecord;

/**
 * Represents a {@link SubmitRecord.Label} that does not depend on Gerrit internal classes, to be
 * serialized.
 */
public class SubmitLabelAttribute {
  public String label;
  public String status;
  public AccountAttribute by;
}

// Copyright (C) 2012 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.data;

/**
 * Represents a {@link com.google.gerrit.entities.SubmitRecord.Label} that does not depend on Gerrit
 * internal classes, to be serialized.
 */
public class SubmitLabelAttribute {
  public String label;
  public String status;
  public AccountAttribute by;
}

Fix "Javadoc: Invalid member type qualification" warnings


package edu.kit.stc.lexer;

import edu.kit.stc.vocabulary.terminal.Token;

import java.util.ArrayList;
import java.util.Queue;

import static org.junit.Assert.*;

/**
 * Created by florian on 08.05.16.
 */
public class LexerTest {
    @org.junit.Test
    public void testLex() throws Exception {
        final String SAMPLE_INPUT = "abc(56.23e45L+42.)/";

        Lexer lxr = new Lexer(SAMPLE_INPUT);

        Queue<Token> tokens = lxr.lex();

        for (Token t : tokens) {
            System.out.println(t.toString());
        }
    }
}

package edu.kit.stc.lexer;

import edu.kit.stc.lexer.exception.LException;
import edu.kit.stc.vocabulary.terminal.Token;

import java.util.ArrayList;
import java.util.Queue;

import static org.junit.Assert.*;

/**
 * Created by florian on 08.05.16.
 */
public class LexerTest {
    @org.junit.Test
    public void simpleArithOperands() throws Exception {
        final String SAMPLE_INPUT = "-+==*/";

        Lexer lxr = new Lexer(SAMPLE_INPUT);

        Queue<Token> tokens = lxr.lex();

        for (Token t : tokens) {
            System.out.println(t.toString());
        }
    }

    @org.junit.Test(expected = LException.class)
    public void faultyFloat() throws Exception {
        final String SAMPLE_INPUT = "42";

        Lexer lxr = new Lexer(SAMPLE_INPUT);

        lxr.lex();
    }

    @org.junit.Test
    public void floatWithNachkommaanteil() throws Exception {
        final String SAMPLE_INPUT = "42.42l";

        Lexer lxr = new Lexer(SAMPLE_INPUT);

        Queue<Token> tokens = lxr.lex();

        for (Token t : tokens) {
            System.out.println(t.toString());
        }
    }

    @org.junit.Test
    public void complexFloatWithExponent() throws Exception {
        final String SAMPLE_INPUT = "42.41e-14L";

        Lexer lxr = new Lexer(SAMPLE_INPUT);

        Queue<Token> tokens = lxr.lex();

        for (Token t : tokens) {
            System.out.println(t.toString());
        }
    }
}

Add some little tests for lexer


package com.boundary.sdk.event;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ScriptUtils {

	private static Logger LOG = LoggerFactory.getLogger(ScriptUtils.class);

	public ScriptUtils() {
	}

	/**
	 * Finds a script to be tested from
	 * @param scriptName
	 * @return {@link File}
	 */
	static public FileReader getFile(String scriptPath) {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();

		URL url = loader.getResource(scriptPath);
		assert(url == null);
		File f = new File(url.getFile());
		FileReader reader = null;
		try {
			reader = new FileReader(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		}
		return reader;
	}
}

package com.boundary.sdk.event;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Utilities used for java script execution
 *
 * @author davidg
 *
 */
public class ScriptUtils {

	private static Logger LOG = LoggerFactory.getLogger(ScriptUtils.class);

	public ScriptUtils() {
	}

	/**
	 * Finds a script to be tested from
	 * @param scriptPath
	 * @return {@link File}
	 */
	static public FileReader getFile(String scriptPath) {
		ClassLoader loader = Thread.currentThread().getContextClassLoader();

		URL url = loader.getResource(scriptPath);
		assert(url == null);
		File f = new File(url.getFile());
		FileReader reader = null;
		try {
			reader = new FileReader(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			LOG.error(e.getMessage());
		}
		return reader;
	}
}

Fix warning when generating javadoc ; Add class description


package in.twizmwaz.cardinal.util;

import org.bukkit.Bukkit;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;

public class DomUtils {

    public static Document parse(File file) throws JDOMException, IOException {
        SAXBuilder saxBuilder = new SAXBuilder();
        Document original = saxBuilder.build(file);
        Path repo = file.getParentFile().getParentFile().toPath();
        for (Element include : original.getRootElement().getChildren("include")) {
            try {
                Path included;
                try {
                    included = repo.resolve(include.getAttributeValue("src")).normalize();
                    for (Element element : parse(included.toFile()).getRootElement().getChildren()) {
                        original.getRootElement().addContent(element.detach());
                    }
                } catch (FileNotFoundException e) {
                    included = file.getParentFile().toPath().resolve(include.getAttributeValue("src")).normalize();
                    for (Element element : parse(included.toFile()).getRootElement().getChildren()) {
                        original.getRootElement().addContent(element.detach());
                        Bukkit.getLogger().info(element.getName());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return original;
    }
}

package in.twizmwaz.cardinal.util;

import org.bukkit.Bukkit;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;

public class DomUtils {

    public static Document parse(File file) throws JDOMException, IOException {
        SAXBuilder saxBuilder = new SAXBuilder();
        Document original = saxBuilder.build(file);
        Bukkit.getLogger().info("1");
        for (Element include : original.getRootElement().getChildren("include")) {
            Bukkit.getLogger().info("2");
            File path = file.getParentFile();
            Bukkit.getLogger().info("3");
            String source = include.getAttributeValue("src");
            Bukkit.getLogger().info("4");
            while (source.contains("../")) {
                source = source.replace("../", "");
                path = path.getParentFile();
            }
            Bukkit.getLogger().info("5");
            File including = new File(path, source);
            Bukkit.getLogger().info("6");
            try {
                for (Element element : parse(including).getRootElement().getChildren()) {
                    Bukkit.getLogger().info(element.getName() + "");
                    original.getRootElement().addContent(element.detach());
                }
            } catch (JDOMException | IOException e) {
                Bukkit.getLogger().log(Level.WARNING, "File '" + including.getName() + "' was not included correctly!");
            }
        }
        return original;
    }
}

Work on includes, left debug messages inside (for later)


package nz.org.hikari.cat.ncdc_download;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.apache.hadoop.io.Text;
import org.junit.Test;

public class NcdcDownloadOutputFormatTest {

	@Test
	public void checkPath() {
		NcdcDownloadOutputFormat outputFormat = new NcdcDownloadOutputFormat();
		String path = outputFormat.generateFileNameForKeyValue(new Text("1901"),
			new Text("value"), "filename.bz2");
		assertEquals(path, "1901/filename.bz2");
	}

	@Test
	public void checkKey()
	{
		NcdcDownloadOutputFormat outputFormat = new NcdcDownloadOutputFormat();
		Text key = outputFormat.generateActualKey(new Text("1901"), new Text("value"));
		assertNull(key);
	}

}

package nz.org.hikari.cat.ncdc_download;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.apache.hadoop.io.Text;
import org.junit.Test;

public class NcdcDownloadOutputFormatTest {

	@Test
	public void checkPath() {
		NcdcDownloadOutputFormat outputFormat = new NcdcDownloadOutputFormat();
		String path = outputFormat.generateFileNameForKeyValue(new Text("1901"),
			new Text("value"), "filename.bz2");
		assertEquals("1901/filename.bz2", path);
	}

	@Test
	public void checkKey()
	{
		NcdcDownloadOutputFormat outputFormat = new NcdcDownloadOutputFormat();
		Text key = outputFormat.generateActualKey(new Text("1901"), new Text("value"));
		assertNull(key);
	}

}

Fix argument order in test case


// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.component;

/**
 * A {@link BindingPattern} which is implicitly constructed by the model, e.g for built-in handlers and filter chains.
 *
 * @author bjorncs
 */
public class SystemBindingPattern extends BindingPattern {

    private SystemBindingPattern(String scheme, String host, String port, String path) { super(scheme, host, port, path); }
    private SystemBindingPattern(String binding) { super(binding); }

    public static SystemBindingPattern fromHttpPath(String path) { return new SystemBindingPattern("http", "*", null, path);}
    public static SystemBindingPattern fromPattern(String binding) { return new SystemBindingPattern(binding);}

    @Override
    public String toString() {
        return "SystemBindingPattern{" +
                "scheme='" + scheme() + '\'' +
                ", host='" + host() + '\'' +
                ", port='" + port().orElse(null) + '\'' +
                ", path='" + path() + '\'' +
                '}';
    }
}

// Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.container.component;

/**
 * A {@link BindingPattern} which is implicitly constructed by the model, e.g for built-in handlers and filter chains.
 *
 * @author bjorncs
 */
public class SystemBindingPattern extends BindingPattern {

    private SystemBindingPattern(String scheme, String host, String port, String path) { super(scheme, host, port, path); }
    private SystemBindingPattern(String binding) { super(binding); }

    public static SystemBindingPattern fromHttpPath(String path) { return new SystemBindingPattern("http", "*", null, path);}
    public static SystemBindingPattern fromPattern(String binding) { return new SystemBindingPattern(binding);}
    public static SystemBindingPattern fromPortAndPath(String port, String path) { return new SystemBindingPattern("http", "*", port, path); }

    @Override
    public String toString() {
        return "SystemBindingPattern{" +
                "scheme='" + scheme() + '\'' +
                ", host='" + host() + '\'' +
                ", port='" + port().orElse(null) + '\'' +
                ", path='" + path() + '\'' +
                '}';
    }
}

Add static builder taking port and path


package client.command;

public enum Commands {

    Username(new String[]{"/username", "/name", "/u"}, Username.class),
    Team(new String[]{"/team", "/t"}, Team.class),
    Contract(new String[]{"/contract"}, Contract.class),
    Create(new String[]{"/create", "/c"}, Create.class),
    Join(new String[]{"/join", "/j"}, Join.class),
    ListPlayers(new String[]{"/list-players"}, ListPlayers.class),
    ListChannel(new String[]{"/list-channel"}, ListChannel.class),
    Leave(new String[]{"/leave", "/l"}, Leave.class),
    ShowCards(new String[]{"/show-cards"}, ShowCards.class),
    ShowTable(new String[]{"/show-table"}, ShowTable.class),
    PlayCard(new String[]{"/play"}, PlayCard.class),
    ShowContract(new String[]{"/show-contract"}, ShowContract.class);

    private String[] aliases;
    private Class command;

    Commands(String[] aliases, Class command) {
        this.aliases = aliases;
        this.command = command;
    }

    public static Class from(String text) throws Exception {
        for (Commands command : Commands.values()) {
            for (String alias : command.getAliases()) {
                if (text.startsWith(alias + ' ')) {
                    return command.getCommand();
                }
            }
        }
        throw new Exception();
    }

    public String[] getAliases() {
        return this.aliases;
    }

    public Class getCommand() {
        return this.command;
    }

}

package client.command;

public enum Commands {

    Username(new String[]{"/username", "/name", "/u", "/n"}, Username.class),
    Team(new String[]{"/team", "/t"}, Team.class),
    Contract(new String[]{"/put-contract", "/contract"}, Contract.class),
    Create(new String[]{"/create", "/c"}, Create.class),
    Join(new String[]{"/join", "/j"}, Join.class),
    ListPlayers(new String[]{"/list-players", "/players"}, ListPlayers.class),
    ListChannel(new String[]{"/list-channels", "/channels"}, ListChannel.class),
    Leave(new String[]{"/leave", "/l"}, Leave.class),
    ShowCards(new String[]{"/show-cards", "/cards"}, ShowCards.class),
    ShowTable(new String[]{"/show-table", "/table"}, ShowTable.class),
    PlayCard(new String[]{"/play", "/p"}, PlayCard.class),
    ShowContract(new String[]{"/show-contract"}, ShowContract.class);

    private String[] aliases;
    private Class command;

    Commands(String[] aliases, Class command) {
        this.aliases = aliases;
        this.command = command;
    }

    public static Class from(String text) throws Exception {
        for (Commands command : Commands.values()) {
            for (String alias : command.getAliases()) {
                if (text.split("\\s+")[0].equals(alias)) {
                    return command.getCommand();
                }
            }
        }
        throw new Exception();
    }

    public String[] getAliases() {
        return this.aliases;
    }

    public Class getCommand() {
        return this.command;
    }

}

Fix a bug when a command like "/list-players" is miss-spelled and "/leave" is executed cause of its alias "/l". And add some aliases.


package com.akexorcist.mvpsimple.module.feed;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;

import com.akexorcist.mvpsimple.R;

public class FeedActivity extends AppCompatActivity implements FeedContractor.View {

    private FeedContractor.Presenter feedPresenter;

    private RecyclerView rvPostList;
    private FeedAdapter feedAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.akexorcist.mvpsimple.R.layout.activity_feed);

        bindView();
        setupView();
        createPresenter();
    }

    private void bindView() {
        rvPostList = (RecyclerView) findViewById(R.id.rv_post_list);
    }

    private void setupView() {
        feedAdapter = new FeedAdapter();
        rvPostList.setAdapter(feedAdapter);
    }

    private void createPresenter() {
        FeedPresenter.createPresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        feedPresenter.start();

    }

    @Override
    public void updatePostList() {
        feedAdapter.setPostItemList(feedPresenter.getPostList().getItemList());
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void setPresenter(FeedContractor.Presenter presenter) {
        this.feedPresenter = presenter;
    }
}

package com.akexorcist.mvpsimple.module.feed;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.akexorcist.mvpsimple.R;

public class FeedActivity extends AppCompatActivity implements FeedContractor.View {

    private FeedContractor.Presenter feedPresenter;

    private RecyclerView rvPostList;
    private FeedAdapter feedAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.akexorcist.mvpsimple.R.layout.activity_feed);

        bindView();
        setupView();
        createPresenter();
    }

    private void bindView() {
        rvPostList = (RecyclerView) findViewById(R.id.rv_post_list);
    }

    private void setupView() {
        feedAdapter = new FeedAdapter();
        rvPostList.setAdapter(feedAdapter);
        rvPostList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    private void createPresenter() {
        FeedPresenter.createPresenter(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        feedPresenter.start();

    }

    @Override
    public void updatePostList() {
        feedAdapter.setPostItemList(feedPresenter.getPostList().getItemList());
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void setPresenter(FeedContractor.Presenter presenter) {
        this.feedPresenter = presenter;
    }
}

Add linear layout manager to recycler view