package io.sigpipe.sing.dataset;

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

import io.sigpipe.sing.dataset.feature.Feature;

public class Quantizer {

    private NavigableSet<Feature> ticks = new TreeSet<>();

    public Quantizer(Object start, Object end, Object step) {
        this(
                Feature.fromPrimitiveType(start),
                Feature.fromPrimitiveType(end),
                Feature.fromPrimitiveType(step));
    }

    public Quantizer(Feature start, Feature end, Feature step) {
        if (start.sameType(end) == false || start.sameType(step) == false) {
            throw new IllegalArgumentException(
                    "All feature types must be the same");
        }
        this.start = start;
        this.end = end;

        Feature tick = new Feature(start);
        while (tick.less(end)) {
            insertTick(tick);
            tick = tick.add(step);
        }
    }

    public void insertTick(Feature tick) {
        ticks.add(tick);
    }

    public void removeTick(Feature tick) {
        ticks.remove(tick);
    }

    public Feature quantize(Feature feature) {
        Feature result = ticks.floor(feature);
        if (result == null) {
            return ticks.first();
        }
        return result;
    }

    @Override
    public String toString() {
        String output = "";
        for (Feature f : ticks) {
            output += f.getString() + System.lineSeparator();
        }
        return output;
    }

}

package io.sigpipe.sing.dataset;

import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

import io.sigpipe.sing.dataset.feature.Feature;

public class Quantizer {

    private NavigableSet<Feature> ticks = new TreeSet<>();

    public Quantizer(Object start, Object end, Object step) {
        this(
                Feature.fromPrimitiveType(start),
                Feature.fromPrimitiveType(end),
                Feature.fromPrimitiveType(step));
    }

    public Quantizer(Feature start, Feature end, Feature step) {
        if (start.sameType(end) == false || start.sameType(step) == false) {
            throw new IllegalArgumentException(
                    "All feature types must be the same");
        }
        this.start = start;
        this.end = end;

        Feature tick = new Feature(start);
        while (tick.less(end)) {
            insertTick(tick);
            tick = tick.add(step);
        }
    }

    public void insertTick(Feature tick) {
        ticks.add(tick);
    }

    public void removeTick(Feature tick) {
        ticks.remove(tick);
    }

    public Feature quantize(Feature feature) {
        Feature result = ticks.floor(feature);
        if (result == null) {
            return ticks.first();
        }
        return result;
    }

    public Feature nextTick(Feature feature) {
        Feature result = ticks.higher(feature);
        //TODO this will return null when feature > highest tick, but should
        //actually return 'end'
        return result;
    }

    @Override
    public String toString() {
        String output = "";
        for (Feature f : ticks) {
            output += f.getString() + System.lineSeparator();
        }
        return output;
    }

}

Add method to retrieve the next tick mark


package com.verybadalloc.designlib.presenters;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.verybadalloc.designlib.model.Book;
import com.verybadalloc.designlib.network.DataCallback;
import com.verybadalloc.designlib.network.DataFetcher;
import com.verybadalloc.designlib.views.BooksListView;

/**
 * Created by aambri on 15-06-09.
 */
public class BooksListPresenter extends MvpBasePresenter<BooksListView> {

    private static final String TAG = "BooksListPresenter";

    public void loadEateries(final boolean pullToRefresh) {

        if(isViewAttached()) {
            getView().showLoading(pullToRefresh);
        }

        DataFetcher.getBooks(new DataCallback<Book[]>() {

            @Override
            public void onSuccess(Book[] books) {
                if (isViewAttached()) {
                    getView().setData(books);
                    getView().showContent();
                }
            }

            @Override
            public void onFailure(String reason) {
                String message = "Failed to load books because " + reason;
                if (isViewAttached()) {
                    getView().showError(new Throwable(message), pullToRefresh);
                }
            }
        });
    }
}

package com.verybadalloc.designlib.presenters;

import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.verybadalloc.designlib.model.Book;
import com.verybadalloc.designlib.network.DataCallback;
import com.verybadalloc.designlib.network.DataFetcher;
import com.verybadalloc.designlib.views.BooksListView;

/**
 * Created by aambri on 15-06-09.
 */
public class BooksListPresenter extends MvpBasePresenter<BooksListView> {

    private static final String TAG = "BooksListPresenter";

    public void loadBooks(final boolean pullToRefresh) {

        if(isViewAttached()) {
            getView().showLoading(pullToRefresh);
        }

        DataFetcher.getBooks(new DataCallback<Book[]>() {

            @Override
            public void onSuccess(Book[] books) {
                if (isViewAttached()) {
                    getView().setData(books);
                    getView().showContent();
                }
            }

            @Override
            public void onFailure(String reason) {
                String message = "Failed to load books because " + reason;
                if (isViewAttached()) {
                    getView().showError(new Throwable(message), pullToRefresh);
                }
            }
        });
    }

    public void loadBooksOfType(String bookType, final boolean pullToRefresh) {

        if(isViewAttached()) {
            getView().showLoading(pullToRefresh);
        }

        DataFetcher.getBooksOfType(bookType, new DataCallback<Book[]>() {

            @Override
            public void onSuccess(Book[] books) {
                if (isViewAttached()) {
                    getView().setData(books);
                    getView().showContent();
                }
            }

            @Override
            public void onFailure(String reason) {
                String message = "Failed to load books because " + reason;
                if (isViewAttached()) {
                    getView().showError(new Throwable(message), pullToRefresh);
                }
            }
        });
    }
}

Add presenter methods to retrieve books by type


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.logging.log4j.util;

/**
 * Indicates that a particular annotated construct was written with certain performance constraints in mind that
 * should be considered when modifying or testing.
 *
 * @since 2.6
 */
public @interface PerformanceSensitive {
    /** Description of why this is written the way it is. */
    String value() default "";
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.logging.log4j.util;

/**
 * Indicates that a particular annotated construct was written with certain performance constraints in mind that
 * should be considered when modifying or testing.
 *
 * @since 2.6
 */
public @interface PerformanceSensitive {
    /** Description of why this is written the way it is. */
    String[] value() default "";
}

Allow multiple reasons for performance.

Allow multiple reasons for performance.


package uk.gov;

import org.postgresql.util.PGobject;

import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class DestinationPostgresDB extends PostgresDB {
    private final String indexedEntriesTableName;
    private final String waterMarkTableName;

    public DestinationPostgresDB(String connectionString) throws SQLException {
        super(connectionString);
        this.indexedEntriesTableName = "ordered_entry_index";
        this.waterMarkTableName = "streamed_entries";
    }

    public void write(ResultSet resultSet) throws SQLException {
        while (resultSet.next()) {
            try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) {
                statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY")));
                statement.executeUpdate();
            }
        }
    }

    public int currentWaterMark() throws SQLException {
        try (Statement statement = connection.createStatement()) {
            try(ResultSet resultSet = statement.executeQuery("SELECT ID FROM " + waterMarkTableName)){
                return resultSet.next() ? resultSet.getInt("ID") : 0;
            }
        }
    }

    private PGobject jsonbObject(byte[] value) {
        try {
            PGobject pGobject = new PGobject();
            pGobject.setType("jsonb");
            pGobject.setValue(new String(value, Charset.forName("UTF-8")));
            return pGobject;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

package uk.gov;

import org.postgresql.util.PGobject;

import java.nio.charset.Charset;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class DestinationPostgresDB extends PostgresDB {
    private final String indexedEntriesTableName;
    private final String waterMarkTableName;

    public DestinationPostgresDB(String connectionString) throws SQLException {
        super(connectionString);
        this.indexedEntriesTableName = "ordered_entry_index";
        this.waterMarkTableName = "streamed_entries";
    }

    public void write(ResultSet resultSet) throws SQLException {
        while (resultSet.next()) {
            connection.setAutoCommit(false);
            try (PreparedStatement statement = connection.prepareStatement("INSERT INTO " + indexedEntriesTableName + "(ENTRY) VALUES(?)")) {
                statement.setObject(1, jsonbObject(resultSet.getBytes("ENTRY")));
                statement.executeUpdate();
            }
            try (PreparedStatement statement = connection.prepareStatement("UPDATE " + waterMarkTableName + " SET ID = ID + 1")) {
                statement.executeUpdate();
            }
            connection.setAutoCommit(true);
        }
    }

    public int currentWaterMark() throws SQLException {
        try (Statement statement = connection.createStatement()) {
            try(ResultSet resultSet = statement.executeQuery("SELECT ID FROM " + waterMarkTableName)){
                return resultSet.next() ? resultSet.getInt("ID") : 0;
            }
        }
    }

    private PGobject jsonbObject(byte[] value) {
        try {
            PGobject pGobject = new PGobject();
            pGobject.setType("jsonb");
            pGobject.setValue(new String(value, Charset.forName("UTF-8")));
            return pGobject;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

Increase watermark by one everytime when an entry is written


package fitnesse.fixtures;

import java.util.Map;
import java.util.TreeMap;

public class HashFixture {

  private Map hash;

  public void sendAsHash(Map hash) {
    this.hash = hash;
  }

  public Map hash() {
    // Make result predictable (ordered)
    return new TreeMap(hash);
  }

  public Object hashIs(String key) {
    return hash.get(key);
  }
}

package fitnesse.fixtures;

import java.util.Map;
import java.util.TreeMap;

public class HashFixture {

  private Map<String, Object> hash;

  public void sendAsHash(Map<String, Object> hash) {
    this.hash = hash;
  }

  public Map<String, Object> hash() {
    // Make result predictable (ordered)
    return new TreeMap<String, Object>(hash);
  }

  public Object hashIs(String key) {
    return hash.get(key);
  }
}

Add parameters to raw type

Add parameters to raw type


package org.kurento.modulecreator.definition;

public abstract class Type extends NamedElement {

  protected transient ModuleDefinition module;

  public Type(String name, String doc) {
    super(name, doc);
  }

  public ModuleDefinition getModule() {
    return module;
  }

  public void setModule(ModuleDefinition module) {
    this.module = module;
  }

}

package org.kurento.modulecreator.definition;

public abstract class Type extends NamedElement {

  protected transient ModuleDefinition module;

  public Type(String name, String doc) {
    super(name, doc);
  }

  public ModuleDefinition getModule() {
    return module;
  }

  public void setModule(ModuleDefinition module) {
    this.module = module;
  }

  /**
   * Get qualified name mixing In the format module.name
   *
   * @return The qualified name
   */
  public String getQualifiedName() {
    if (this.module == null || this.module.getName() == null) {
      return name;
    }
    if (this.module.getName().equals("core") || this.module.getName().equals("filters")
        || this.module.getName().equals("elements")) {
      return "kurento." + name;
    } else {
      return this.module.getName() + "." + name;
    }
  }

}

Add new getter for qualifiedName

Add new getter for qualifiedName

Change-Id: I2a68a1c5f4bbc2f0cad4f92e47b0d1a062cd45ed


// Copyright 2011 The MOE Authors All Rights Reserved.

package com.google.devtools.moe.client.project;

import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.devtools.moe.client.Ui;

import java.io.File;
import java.io.IOException;

import javax.inject.Inject;

/**
 *
 * @author dbentley@google.com (Daniel Bentley)
 */
public class FileReadingProjectContextFactory implements ProjectContextFactory {

  @Inject Ui ui;

  public ProjectContext makeProjectContext(String configFilename) throws InvalidProject{
    String configText;
    Ui.Task task = ui.pushTask(
        "read_config",
        String.format("Reading config file from %s", configFilename));
    try {
      try {
        configText = Files.toString(new File(configFilename), Charsets.UTF_8);
      } catch (IOException e) {
        throw new InvalidProject(
            "Config File \"" + configFilename + "\" not accessible.");
      }

      return ProjectContext.makeProjectContextFromConfigText(configText);
    } finally {
      ui.popTask(task, "");
    }
  }

}

// Copyright 2011 The MOE Authors All Rights Reserved.

package com.google.devtools.moe.client.project;

import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.io.Files;
import com.google.devtools.moe.client.Ui;

import java.io.File;
import java.io.IOException;

import javax.inject.Inject;

/**
 *
 * @author dbentley@google.com (Daniel Bentley)
 */
public class FileReadingProjectContextFactory implements ProjectContextFactory {

  @Inject Ui ui;

  public ProjectContext makeProjectContext(String configFilename) throws InvalidProject{
    String configText;
    Ui.Task task = ui.pushTask(
        "read_config",
        String.format("Reading config file from %s", configFilename));
    try {
      try {
        configText = Files.toString(new File(configFilename), UTF_8);
      } catch (IOException e) {
        throw new InvalidProject(
            "Config File \"" + configFilename + "\" not accessible.");
      }

      return ProjectContext.makeProjectContextFromConfigText(configText);
    } finally {
      ui.popTask(task, "");
    }
  }

}

Use the Charset constants in the JDK's StandardCharsets class instead of c.g.c.base.Charsets. The c.g.common.base.Charsets is scheduled for deletion.

More information: []

Tested:
    TAP train for global presubmit queue
    []    Some tests failed; test failures are believed to be unrelated to this CL
	Change on 2015/01/30 by kak <kak@google.com>
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=85186588


package com.peterjosling.scroball.transforms;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.peterjosling.scroball.Track;

import java.util.Collection;

public class MetadataTransformers {

  private static final MetadataTransform VIDEO_TITLE_CLEANER = new VideoTitleCleaner();
  private static final MetadataTransform TITLE_EXTRACTOR = new TitleExtractor();

  private static final ImmutableMultimap<String, MetadataTransform> APP_TRANSFORMS =
      ImmutableMultimap.<String, MetadataTransform>builder()
          .putAll(
              "com.google.android.youtube", ImmutableList.of(TITLE_EXTRACTOR, VIDEO_TITLE_CLEANER))
          .build();

  public Track transformForPackageName(String packageName, Track track) {
    Collection<MetadataTransform> transforms = APP_TRANSFORMS.get(packageName);

    for (MetadataTransform transform : transforms) {
      track = transform.transform(track);
    }
    return track;
  }
}

package com.peterjosling.scroball.transforms;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.peterjosling.scroball.Track;

import java.util.Collection;
import java.util.List;

public class MetadataTransformers {

  private static final MetadataTransform VIDEO_TITLE_CLEANER = new VideoTitleCleaner();
  private static final MetadataTransform TITLE_EXTRACTOR = new TitleExtractor();

  private static final List<MetadataTransform> VIDEO_TRANSFORMS =
      ImmutableList.of(TITLE_EXTRACTOR, VIDEO_TITLE_CLEANER);
  private static final ImmutableMultimap<String, MetadataTransform> APP_TRANSFORMS =
      ImmutableMultimap.<String, MetadataTransform>builder()
          .putAll("com.google.android.youtube", VIDEO_TRANSFORMS)
          .putAll("com.google.android.youtube.tv", VIDEO_TRANSFORMS)
          .build();

  public Track transformForPackageName(String packageName, Track track) {
    Collection<MetadataTransform> transforms = APP_TRANSFORMS.get(packageName);

    for (MetadataTransform transform : transforms) {
      track = transform.transform(track);
    }
    return track;
  }
}

Add support for Android TV YouTube app

Add support for Android TV YouTube app


package unstar;

import org.junit.Test;
import static org.junit.Assert.*;

public class CrackerTest {

    @Test
    public void digitTest() {
        assertEquals(36, Cracker.DIGITS.length);
    }

    @Test
    public void encodeTest() {
        assertEquals("1", Cracker.encode(1, 1));
        assertEquals("A", Cracker.encode(1, 10));
        assertEquals("00RS", Cracker.encode(4, 1000));
        assertEquals(1000, Cracker.decode("00RS"));
    }
}

package unstar;

import org.junit.Test;
import static org.junit.Assert.*;

public class CrackerTest {

    @Test
    public void digitTest() {
        assertEquals(36, Cracker.DIGITS.length);
    }

    @Test
    public void encodeTest() {
        assertEquals("1", Cracker.encode(1, 1));
        assertEquals("A", Cracker.encode(1, 10));
        assertEquals("00RS", Cracker.encode(4, 1000));
        assertEquals(1000, Cracker.decode("00RS"));
    }

    @Test
    public void serialTest() {
        assertEquals(0x1009db6241eL, Cracker.decode("E2BO659A"));
        assertEquals(0x10120a6bad5L, Cracker.decode("E3C03B2T"));
        assertEquals(0x101e22fa47cL, Cracker.decode("E4TP99BW"));
        assertEquals(0x105d81aa6a9L, Cracker.decode("ECN101WP"));
        assertEquals(0x1071daf128cL, Cracker.decode("EF5D4KNG"));
        assertEquals(0x10f0e3321c7L, Cracker.decode("EUTBD0AV"));
        assertEquals(0x2042ff5da94L, Cracker.decode("SAH96KK4"));
        assertEquals(0x2042ff79a65L, Cracker.decode("SAH9910L"));
        assertEquals(0x2042ff197cbL, Cracker.decode("SAH90L3F"));
    }
}

Add another, uh, unit test.

Add another, uh, unit test.


package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarTest
{
	@Test
	public void testMultiplication()
	{
		Dollar dollar = new Dollar(5);
		dollar.times(3);
		assertEquals(10, dollar.amount);
	}

}

package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarTest
{
	@Test
	public void testMultiplication()
	{
			Dollar five= new Dollar(5);
			assertEquals(new Dollar(10), five.times(2));
			assertEquals(new Dollar(15), five.times(3));
	}
	@Test
	public void testFrancMultiplication()
	{
		Franc five= new Franc(5);
		assertEquals(new Franc(10), five.times(2));
		assertEquals(new Franc(15), five.times(3));
	}
	@Test
	public void testEquality()
	{
		assertTrue(new Dollar(5).equals(new Dollar(5)));
		assertFalse(new Dollar(5).equals(new Dollar(6)));
	}
}

Include all test cases in one test class


package com.intellij.vcs.log.graph.render;

import com.intellij.vcs.log.graph.elements.Branch;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author erokhins
 */
public class ColorGenerator {
  private static final Map<Integer, Color> colorMap = new HashMap<Integer, Color>();

  private static final Map<Branch, Color> ourCachedColors = new HashMap<Branch, Color>();

  @NotNull
  public static Color getColor(@NotNull Branch branch) {
    int indexColor = branch.getBranchNumber();
    Color color = colorMap.get(indexColor);
    if (color == null) {
      color = getColor(indexColor);
      colorMap.put(indexColor, color);
    }
    return color;
  }

  private static int rangeFix(int n) {
    return Math.abs(n) % 200;
  }

  private static Color getColor(int indexColor) {
    int r = indexColor * 200 + 30;
    int g = indexColor * 130 + 50;
    int b = indexColor * 90 + 100;
    try {
      return new Color(rangeFix(r), rangeFix(g), rangeFix(b));
    }
    catch (IllegalArgumentException a) {
      throw new IllegalArgumentException("indexColor: " + indexColor + " " + r % 256 + " " + (g % 256) + " " + (b % 256));
    }
  }
}

package com.intellij.vcs.log.graph.render;

import com.intellij.vcs.log.graph.elements.Branch;
import org.jetbrains.annotations.NotNull;

import java.awt.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author erokhins
 */
public class ColorGenerator {
  private static final Map<Integer, Color> colorMap = new HashMap<Integer, Color>();

  private static final Map<Branch, Color> ourCachedColors = new HashMap<Branch, Color>();

  @NotNull
  public static Color getColor(@NotNull Branch branch) {
    int indexColor = branch.getBranchNumber();
    Color color = colorMap.get(indexColor);
    if (color == null) {
      color = getColor(indexColor);
      colorMap.put(indexColor, color);
    }
    return color;
  }

  private static int rangeFix(int n) {
    return Math.abs(n) % 100 + 70;
  }

  private static Color getColor(int indexColor) {
    int r = indexColor * 200 + 30;
    int g = indexColor * 130 + 50;
    int b = indexColor * 90 + 100;
    try {
      return new Color(rangeFix(r), rangeFix(g), rangeFix(b));
    }
    catch (IllegalArgumentException a) {
      throw new IllegalArgumentException("indexColor: " + indexColor + " " + r % 256 + " " + (g % 256) + " " + (b % 256));
    }
  }
}

Make branch colors a bit more calm

[log] Make branch colors a bit more calm


package com.custardsource.parfait.timing;

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

public class ThreadMetricSuite {
    private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics
            .defaults());

    public final void addMetric(ThreadMetric metric) {
        metrics.add(metric);
    }

    public final List<ThreadMetric> metrics() {
        return Collections.unmodifiableList(metrics);
    }

}

package com.custardsource.parfait.timing;

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

public class ThreadMetricSuite {
    private final List<ThreadMetric> metrics = new ArrayList<ThreadMetric>(StandardThreadMetrics
            .defaults());

    public final void addMetric(ThreadMetric metric) {
        metrics.add(metric);
    }

    public final void addAllMetrics(Collection<ThreadMetric> metrics) {
        metrics.addAll(metrics);
    }

    public final List<ThreadMetric> metrics() {
        return Collections.unmodifiableList(metrics);
    }

}

Add useful addAll() metric to the suite

Add useful addAll() metric to the suite


package org.vaadin.alump.searchdropdown.demo;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;

@Theme("demo")
@Title("SearchDropDown Add-on Demo")
@Push
@SuppressWarnings("serial")
public class DemoUI extends UI {

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.alump.searchdropdown.demo.WidgetSet")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        Navigator navigator = new Navigator(this, this);
        navigator.addView(MenuView.VIEW_NAME, MenuView.class);
        navigator.addView(TestView.VIEW_NAME, TestView.class);
        navigator.addView(ExampleView.VIEW_NAME, ExampleView.class);
        navigator.addView(JustTesting.VIEW_NAME, JustTesting.class);
        navigator.addView(SimpleView.VIEW_NAME, SimpleView.class);
        navigator.setErrorView(MenuView.class);
        setNavigator(navigator);
    }

}

package org.vaadin.alump.searchdropdown.demo;

import javax.servlet.annotation.WebServlet;

import com.vaadin.annotations.Push;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.*;

@Theme("demo")
@Title("SearchDropDown Add-on Demo")
@Push
@SuppressWarnings("serial")
public class DemoUI extends UI {

    @WebServlet(value = "/*", asyncSupported = true)
    @VaadinServletConfiguration(productionMode = false, ui = DemoUI.class, widgetset = "org.vaadin.alump.searchdropdown.demo.WidgetSet")
    public static class Servlet extends VaadinServlet {
    }

    @Override
    protected void init(VaadinRequest request) {
        Navigator navigator = new Navigator(this, this);
        navigator.addView(MenuView.VIEW_NAME, MenuView.class);
        navigator.addView(TestView.VIEW_NAME, TestView.class);
        navigator.addView(ExampleView.VIEW_NAME, ExampleView.class);
        navigator.addView(SimpleView.VIEW_NAME, SimpleView.class);
        navigator.setErrorView(MenuView.class);
        setNavigator(navigator);
    }

}

Remove reference to removed view

Remove reference to removed view


package net.folab.fo.jast;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import net.folab.fo.bytecode.ByteArrayClassLoader;
import net.folab.fo.jast.AstVisitor;
import net.folab.fo.jast.AstWriter;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class AstWriterTest {

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testSetName() throws InstantiationException, IllegalAccessException {

        AstVisitor av;
        Class<?> generatedClass;
        byte[] bytecode;
        String name;

        Object obj;

        // - - -

        name = "MainClass";
        av = new AstWriter();

        new ClassDeclaration(name).accept(av);
        bytecode = av.toByteArray();

        generatedClass = defineClass(name, bytecode);
        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

        // - - -

        name = "foo.MainClass";
        av = new AstWriter();

        new ClassDeclaration(name).accept(av);
        bytecode = av.toByteArray();

        generatedClass = defineClass(name, bytecode);

        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

    }

    public static Class<?> defineClass(String name, byte[] bytecode) {
        return new ByteArrayClassLoader().defineClass(name, bytecode);
    }

}

package net.folab.fo.jast;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import net.folab.fo.bytecode.ByteArrayClassLoader;
import net.folab.fo.jast.AstWriter;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class AstWriterTest {

    private AstWriter writer;

    @Before
    public void setUp() throws Exception {
        writer = new AstWriter();
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testSetName() throws InstantiationException, IllegalAccessException {

        Class<?> generatedClass;
        byte[] bytecode;
        String name;

        Object obj;

        // - - -

        name = "MainClass";

        new ClassDeclaration(name).accept(writer);
        bytecode = writer.toByteArray();

        generatedClass = defineClass(name, bytecode);
        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

        // - - -

        name = "foo.MainClass";
        writer = new AstWriter();

        new ClassDeclaration(name).accept(writer);
        bytecode = writer.toByteArray();

        generatedClass = defineClass(name, bytecode);

        assertThat(generatedClass.getName(), is(name));

        obj = generatedClass.newInstance();
        assertThat(obj, is(not(nullValue())));

    }

    public static Class<?> defineClass(String name, byte[] bytecode) {
        return new ByteArrayClassLoader().defineClass(name, bytecode);
    }

}

Update test codes to fit test target.

Update test codes to fit test target.


package org.knowm.xchange.interceptor;

import com.google.common.base.Suppliers;
import java.util.Collection;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import si.mazi.rescu.Interceptor;

public class InterceptorProvider {

  private static final Supplier<Collection<Interceptor>> INTERCEPTORS_SUPPLIER =
      Suppliers.memoize(
          () -> {
            final ServiceLoader<Interceptor> serviceLoader = ServiceLoader.load(Interceptor.class);
            return StreamSupport.stream(serviceLoader.spliterator(), false)
                .collect(Collectors.toSet());
          });

  public static Collection<Interceptor> provide() {
    return INTERCEPTORS_SUPPLIER.get();
  }
}

Add possibility to use custom Interceptors


package com.google.rolecall.authentication;

import com.google.rolecall.Constants;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

/** Parses the header of a request for EMAIL and AUTHORIZZATION used in authentication */
public class PreAuthTokenHeaderFilter extends AbstractPreAuthenticatedProcessingFilter {

  @Override
  protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    return request.getHeader(Constants.Headers.EMAIL);
  }

  @Override
  protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
    String token = request.getHeader(Constants.Headers.OAUTH_KEY);
    return token == null ? "" : token;
  }
}

package com.google.rolecall.authentication;

import com.google.rolecall.Constants;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter;

/** Parses the header of a request for EMAIL and AUTHORIZZATION used in authentication */
public class PreAuthTokenHeaderFilter extends AbstractPreAuthenticatedProcessingFilter {

  @Override
  protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    return request.getHeader(Constants.Headers.EMAIL);
  }

  @Override
  protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
    String fullValue = request.getHeader(Constants.Headers.OAUTH_KEY);
    String prefix = "Bearer ";

    if(fullValue != null && fullValue.startsWith(prefix)) {
      return fullValue.substring(prefix.length());
    }

    return "";
  }
}

Add bearer tag to auth

Add bearer tag to auth


 package basearch.integration;

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

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

public class ApplicationInitializerListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(ApplicationInitializerListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.debug("Shutting down application...");
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.debug("Starting up application...");
	}

}

 package basearch.integration;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;

public class ApplicationInitializerListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(ApplicationInitializerListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		logger.debug("Shutting down application...");
		// logback's async appender shutdown
		((LoggerContext)LoggerFactory.getILoggerFactory()).stop();
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		logger.debug("Starting up application...");
	}

}

Add shutdown code for logback's async appender


package com.alexstyl.specialdates.events.peopleevents;

import com.alexstyl.specialdates.R;
import com.alexstyl.resources.StringResources;
import com.alexstyl.specialdates.events.database.EventColumns;

public class CustomEventType implements EventType {

    private final String name;

    public CustomEventType(String name) {
        this.name = name;
    }

    @Override
    public String getEventName(StringResources stringResources) {
        return name;
    }

    @Override
    public int getColorRes() {
        return R.color.purple_custom_event;
    }

    @Override
    public int getId() {
        return EventColumns.TYPE_CUSTOM;
    }

    @Override
    public int getIconResId() {
        return R.drawable.ic_cake;
    }
}

package com.alexstyl.specialdates.events.peopleevents;

import com.alexstyl.specialdates.R;
import com.alexstyl.resources.StringResources;
import com.alexstyl.specialdates.events.database.EventColumns;

public class CustomEventType implements EventType {

    private final String name;

    public CustomEventType(String name) {
        this.name = name;
    }

    @Override
    public String getEventName(StringResources stringResources) {
        return name;
    }

    @Override
    public int getColorRes() {
        return R.color.purple_custom_event;
    }

    @Override
    public int getId() {
        return EventColumns.TYPE_CUSTOM;
    }

    @Override
    public int getIconResId() {
        return R.drawable.ic_custom;
    }
}

Return custom icon for custom events

Return custom icon for custom events


package com.coding4people.mosquitoreport.api.factories;

import java.util.Optional;

import javax.inject.Inject;

import org.glassfish.hk2.api.Factory;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;

public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
    DynamoDBMapper mapper;

    @Inject
    public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
        mapper = new DynamoDBMapper(client,
                new DynamoDBMapperConfig.Builder()
                        .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
                                .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost")))
                .build());
    }

    @Override
    public void dispose(DynamoDBMapper mapper) {
    }

    @Override
    public DynamoDBMapper provide() {
        return mapper;
    }
}

package com.coding4people.mosquitoreport.api.factories;

import java.util.Optional;

import javax.inject.Inject;

import org.glassfish.hk2.api.Factory;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;

public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
    DynamoDBMapper mapper;

    @Inject
    public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
        mapper = new DynamoDBMapper(client,
                new DynamoDBMapperConfig.Builder()
                        .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
                                .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost.")))
                .build());
    }

    @Override
    public void dispose(DynamoDBMapper mapper) {
    }

    @Override
    public DynamoDBMapper provide() {
        return mapper;
    }
}

Set default table prefix as ` localhost.`


/**
 * Copyright © 2014 tuxed <write@imaginarycode.com>
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */
package com.imaginarycode.minecraft.hubmagic.bungee;

import com.imaginarycode.minecraft.hubmagic.HubMagic;
import com.imaginarycode.minecraft.hubmagic.selectors.ServerSelector;
import lombok.AllArgsConstructor;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;

@AllArgsConstructor
public class HubMagicReconnectHandler extends AbstractReconnectHandler {
    private final ServerSelector selector;

    @Override
    protected ServerInfo getStoredServer(ProxiedPlayer player) {
        return selector.selectServer(player);
    }

    @Override
    public final void setServer(ProxiedPlayer player) {

    }

    @Override
    public final void save() {
        HubMagic.getPlugin().getPingManager().shutdown();
    }

    @Override
    public final void close() {

    }
}

/**
 * Copyright © 2014 tuxed <write@imaginarycode.com>
 * This work is free. You can redistribute it and/or modify it under the
 * terms of the Do What The Fuck You Want To Public License, Version 2,
 * as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
 */
package com.imaginarycode.minecraft.hubmagic.bungee;

import com.imaginarycode.minecraft.hubmagic.HubMagic;
import com.imaginarycode.minecraft.hubmagic.selectors.ServerSelector;
import lombok.AllArgsConstructor;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;

@AllArgsConstructor
public class HubMagicReconnectHandler extends AbstractReconnectHandler {
    private final ServerSelector selector;

    @Override
    protected ServerInfo getStoredServer(ProxiedPlayer player) {
        return selector.selectServer(player);
    }

    @Override
    public final void setServer(ProxiedPlayer player) {

    }

    @Override
    public final void save() {

    }

    @Override
    public final void close() {
        HubMagic.getPlugin().getPingManager().shutdown();
    }
}

Fix a rather embarrassing bug where HubMagic's pinging functionality would shut down after five minutes.


package org.gbif.checklistbank.cli.analysis;

import org.gbif.cli.Command;
import org.gbif.cli.service.ServiceCommand;

import com.google.common.util.concurrent.Service;
import org.kohsuke.MetaInfServices;

@MetaInfServices(Command.class)
public class AnalysisCommand extends ServiceCommand {

  private final AnalysisConfiguration configuration = new AnalysisConfiguration();

  public AnalysisCommand() {
    super("matcher");
  }

  @Override
  protected Service getService() {
    return new AnalysisService(configuration);
  }

  @Override
  protected Object getConfigurationObject() {
    return configuration;
  }

}

package org.gbif.checklistbank.cli.analysis;

import org.gbif.cli.Command;
import org.gbif.cli.service.ServiceCommand;

import com.google.common.util.concurrent.Service;
import org.kohsuke.MetaInfServices;

@MetaInfServices(Command.class)
public class AnalysisCommand extends ServiceCommand {

  private final AnalysisConfiguration configuration = new AnalysisConfiguration();

  public AnalysisCommand() {
    super("analysis");
  }

  @Override
  protected Service getService() {
    return new AnalysisService(configuration);
  }

  @Override
  protected Object getConfigurationObject() {
    return configuration;
  }

}

Fix clb analysis command name

Fix clb analysis command name


package org.apache.camel.http.common;

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
public enum HttpMethods {

    GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH

}

/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.camel.http.common;

public enum HttpMethods {

    GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE, PATCH

}

Put license header in correct spot

Put license header in correct spot


package enmasse.storage.controller.admin;

import com.fasterxml.jackson.databind.JsonNode;
import enmasse.storage.controller.model.FlavorConfig;
import enmasse.storage.controller.model.parser.FlavorConfigParser;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Ulf Lilleengen
 */
public class FlavorManager implements ConfigManager, FlavorRepository {
    private volatile Map<String, FlavorConfig> flavorMap = Collections.emptyMap();
    private final FlavorConfigParser parser = new FlavorConfigParser();

    @Override
    public FlavorConfig getFlavor(String flavorName) {
        FlavorConfig flavor = flavorMap.get(flavorName);
        if (flavor == null) {
            String flavors = flavorMap.keySet().stream().collect(Collectors.joining(","));
            throw new IllegalArgumentException(String.format("No flavor with name '%s' exists, have [%s]", flavorName, flavors));
        }
        return flavor;
    }

    @Override
    public FlavorConfig getDefaultFlavor() {
        return new FlavorConfig.Builder().build();
    }

    @Override
    public void configUpdated(JsonNode jsonConfig) throws IOException {
        configUpdated(parser.parse(jsonConfig));
    }

    public void configUpdated(Map<String, FlavorConfig> flavorMap) {
        this.flavorMap = flavorMap;
    }
}

package enmasse.storage.controller.admin;

import com.fasterxml.jackson.databind.JsonNode;
import enmasse.storage.controller.model.FlavorConfig;
import enmasse.storage.controller.model.parser.FlavorConfigParser;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @author Ulf Lilleengen
 */
public class FlavorManager implements ConfigManager, FlavorRepository {
    private static final Logger log = Logger.getLogger(FlavorManager.class.getName());
    private volatile Map<String, FlavorConfig> flavorMap = Collections.emptyMap();
    private final FlavorConfigParser parser = new FlavorConfigParser();

    @Override
    public FlavorConfig getFlavor(String flavorName) {
        FlavorConfig flavor = flavorMap.get(flavorName);
        if (flavor == null) {
            String flavors = flavorMap.keySet().stream().collect(Collectors.joining(","));
            throw new IllegalArgumentException(String.format("No flavor with name '%s' exists, have [%s]", flavorName, flavors));
        }
        return flavor;
    }

    @Override
    public FlavorConfig getDefaultFlavor() {
        return new FlavorConfig.Builder().build();
    }

    @Override
    public void configUpdated(JsonNode jsonConfig) throws IOException {
        configUpdated(parser.parse(jsonConfig));
    }

    public void configUpdated(Map<String, FlavorConfig> flavorMap) {
        this.flavorMap = flavorMap;
        if (log.isLoggable(Level.INFO)) {
            String flavors = flavorMap.keySet().stream().collect(Collectors.joining(","));
            log.log(Level.INFO, String.format("Got new set of flavors: [%s]", flavors));
        }

    }
}

Add logging when flavors are updated

Add logging when flavors are updated


package org.apache.sling.commons.json;

import junit.framework.TestCase;

/**
 * @author vidar@idium.no
 * @since Apr 17, 2009 6:04:00 PM
 */
public class JSONObjectTest extends TestCase {
    private static final String KEY = "key";

    /**
     * See SLING-929
     */
    public void testAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.append(KEY, "value1");
        obj.append(KEY, "value2");
        Object result = obj.get(KEY);
        assertTrue("Did not create an array", result instanceof JSONArray);
    }

    /**
     * See SLING-929
     */
    public void testFailAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put(KEY, "value1");
        try {
            obj.append(KEY, "value2");
            TestCase.fail("Accepted append() to a non-array property");
        } catch (JSONException ignore) {
            // this is expected
        }
    }

}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.apache.sling.commons.json;

import junit.framework.TestCase;

/**
 * @since Apr 17, 2009 6:04:00 PM
 */
public class JSONObjectTest extends TestCase {
    private static final String KEY = "key";

    /**
     * See SLING-929
     */
    public void testAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.append(KEY, "value1");
        obj.append(KEY, "value2");
        Object result = obj.get(KEY);
        assertTrue("Did not create an array", result instanceof JSONArray);
    }

    /**
     * See SLING-929
     */
    public void testFailAppend() throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put(KEY, "value1");
        try {
            obj.append(KEY, "value2");
            TestCase.fail("Accepted append() to a non-array property");
        } catch (JSONException ignore) {
            // this is expected
        }
    }

}

Add missing header and remove author tag.

git-svn-id: c3eb811ccca381e673aa62a65336ec26649ed58c@769115 13f79535-47bb-0310-9956-ffa450edef68


package com.sap.mentors.lemonaid.external;

import org.springframework.stereotype.Component;

@Component
public class ScnImage {

	public String getProfilePhoto(final String scnUrl) {
		return scnUrl + "/avatar/144.png";
	}

}

package com.sap.mentors.lemonaid.external;

import org.springframework.stereotype.Component;

@Component
public class ScnImage {

	public String getProfilePhoto(final String scnUrl) {
		if (scnUrl.contains("people.sap.com")) {
			return scnUrl.replace("people.sap.com", "people.sap.com/avatar");
		} else {
			return scnUrl + "/avatar/144.png";
		}
	}

}

Support grabbing avatars from new SCN

Support grabbing avatars from new SCN


package com.cedricziel.idea.fluid.lang.psi.impl;

import com.cedricziel.idea.fluid.lang.psi.FluidElement;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;

public class FluidElementImpl extends ASTWrapperPsiElement implements FluidElement {

  public FluidElementImpl(@NotNull ASTNode node) {
    super(node);
  }

  @Override
  public String toString() {
    final String className = getClass().getSimpleName();
    return StringUtil.trimEnd(className, "Impl");
  }
}

package com.cedricziel.idea.fluid.lang.psi.impl;

import com.cedricziel.idea.fluid.lang.psi.FluidElement;
import com.intellij.extapi.psi.ASTWrapperPsiElement;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiReference;
import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry;
import org.jetbrains.annotations.NotNull;

public class FluidElementImpl extends ASTWrapperPsiElement implements FluidElement {

  public FluidElementImpl(@NotNull ASTNode node) {
    super(node);
  }

  @Override
  public String toString() {
    final String className = getClass().getSimpleName();
    return StringUtil.trimEnd(className, "Impl");
  }

    @NotNull
    @Override
    public PsiReference[] getReferences() {
        return ReferenceProvidersRegistry.getReferencesFromProviders(this);
    }

    @Override
    public PsiReference getReference() {
        PsiReference[] references = getReferences();

        return references.length == 0 ? null : references[0];
    }
}

[Fluid] Allow placing PsiReferences on FluidElements


/*
 * Copyright (C) 2013 Simon Marquis (http://www.simon-marquis.fr)
 *
 * 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 fr.simon.marquis.preferencesmanager.model;

import fr.simon.marquis.preferencesmanager.R;

public enum AppTheme {
    LIGHT(R.style.AppThemeLight, R.string.dark_theme), DARK(R.style.AppThemeDark, R.string.light_theme);

    public static final AppTheme DEFAULT_THEME = DARK;
    public final int theme;
    /**
     * This is the title displayed in menu, so it's normal that's inverted
     */
    public final int title;

    AppTheme(int theme, int title) {
        this.theme = theme;
        this.title = title;
    }
}

/*
 * Copyright (C) 2013 Simon Marquis (http://www.simon-marquis.fr)
 *
 * 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 fr.simon.marquis.preferencesmanager.model;

import fr.simon.marquis.preferencesmanager.R;

public enum AppTheme {
    LIGHT(R.style.AppThemeLight, R.string.dark_theme), DARK(R.style.AppThemeDark, R.string.light_theme);

    public static final AppTheme DEFAULT_THEME = LIGHT;
    public final int theme;
    /**
     * This is the title displayed in menu, so it's normal that's inverted
     */
    public final int title;

    AppTheme(int theme, int title) {
        this.theme = theme;
        this.title = title;
    }
}

Change default theme to Holo Light

Change default theme to Holo Light


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * 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.facebook.litho.widget;

import androidx.annotation.Nullable;

/**
 * A controller that can be passed as {@link com.facebook.litho.annotations.Prop} to a {@link
 * VerticalScrollSpec} to trigger events from outside the component hierarchy.
 */
public class VerticalScrollEventsController {

  @Nullable private LithoScrollView mScrollView;

  void setScrollView(@Nullable LithoScrollView scrollView) {
    mScrollView = scrollView;
  }

  public void scrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.scrollTo(mScrollView.getScrollX(), y);
    }
  }

  public void smoothScrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.smoothScrollTo(mScrollView.getScrollX(), y);
    }
  }
}

/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * 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.facebook.litho.widget;

import android.view.View;
import androidx.annotation.Nullable;

/**
 * A controller that can be passed as {@link com.facebook.litho.annotations.Prop} to a {@link
 * VerticalScrollSpec} to trigger events from outside the component hierarchy.
 */
public class VerticalScrollEventsController {

  @Nullable private LithoScrollView mScrollView;

  void setScrollView(@Nullable LithoScrollView scrollView) {
    mScrollView = scrollView;
  }

  public void scrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.scrollTo(mScrollView.getScrollX(), y);
    }
  }

  public void smoothScrollTo(int y) {
    if (mScrollView != null) {
      mScrollView.smoothScrollTo(mScrollView.getScrollX(), y);
    }
  }

  public void scrollToTop() {
    if (mScrollView != null) {
      mScrollView.fullScroll(View.FOCUS_UP);
    }
  }

  public void scrollToBottom() {
    if (mScrollView != null) {
      mScrollView.fullScroll(View.FOCUS_DOWN);
    }
  }
}

Add support for scrolling to top and bottom in VerticalScrollSpec

Summary: as title

Reviewed By: mihaelao

Differential Revision: D33711690

fbshipit-source-id: 44d52eaaea775acf80db530af2990acd236415b8


/**
 * Copyright 2016 Bryan Kelly
 *
 * 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.btkelly.gnag.utils;

import org.jetbrains.annotations.Nullable;

public final class StringUtils {

    /**
     * Removes leading/trailing whitespace and newlines.
     */
    public static String sanitize(@Nullable final String string) {
        if (string == null) {
            return null;
        }

        return string
                .trim()
                .replaceAll("^\\r|^\\n|\\r$\\n$", "");
    }

    private StringUtils() {
        // This constructor intentionally left blank.
    }

}

/**
 * Copyright 2016 Bryan Kelly
 *
 * 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.btkelly.gnag.utils;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public final class StringUtils {

    /**
     * Removes leading/trailing whitespace and newlines.
     */
    @NotNull
    public static String sanitize(@Nullable final String string) {
        if (string == null) {
            return "";
        }

        return string
                .trim()
                .replaceAll("^\\r|^\\n|\\r$\\n$", "");
    }

    private StringUtils() {
        // This constructor intentionally left blank.
    }

}

Make sanitization method more safe

Make sanitization method more safe


package org.talend.dataprep.configuration;

import java.util.List;

import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JSR310Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;

@Configuration
@SuppressWarnings("InsufficientBranchCoverage")
public class Serialization {

    @Autowired
    List<Module> modules;

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.featuresToDisable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
        builder.indentOutput(false);
        // FIXME we should use jackson modules and remove home made LocalDateTimeModule
        //modules.add( new JavaTimeModule() );
        //modules.add( new Jdk8Module() );
        builder.modules(modules);
        return builder;
    }
}

package org.talend.dataprep.configuration;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.Module;

@Configuration
@SuppressWarnings("InsufficientBranchCoverage")
public class Serialization {

    @Autowired
    List<Module> modules;

    @Bean
    public Jackson2ObjectMapperBuilder jacksonBuilder() {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.featuresToDisable(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES);
        builder.indentOutput(false);
        builder.modules(modules);
        return builder;
    }
}

[Misc] Clean up unused imports (was supposed to be done in branch).


package devopsdistilled.operp.server;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.server.context.AppContext;

public class ServerApp {

	public static void main(String[] args) {

		if (args.length > 0 && args[0].equalsIgnoreCase("create"))
			System.setProperty("hibernate.hbm2ddl.auto", "create");
		else
			System.setProperty("hibernate.hbm2ddl.auto", "update");

		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppContext.class);

		System.out.println(context);
	}
}

package devopsdistilled.operp.server;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import devopsdistilled.operp.server.context.AppContext;

public class ServerApp {

	public static void main(String[] args) {

		if (args.length > 0 && args[0].equalsIgnoreCase("init"))
			System.setProperty("hibernate.hbm2ddl.auto", "create");
		else
			System.setProperty("hibernate.hbm2ddl.auto", "update");

		ApplicationContext context = new AnnotationConfigApplicationContext(
				AppContext.class);

		System.out.println(context);
	}
}

Change argument to "init" for creating schema


/*
 * Copyright 2005-2014 Red Hat, Inc.
 *
 * Red Hat licenses this file to you 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 io.fabric8.arquillian.kubernetes;

public class Constants {

    public static final String ARQ_KEY = "arquillian";

    public static final String MASTER_URL = "masterUrl";
    public static final String CONFIG_URL = "configUrl";

    public static final String TIMEOUT = "timeout";
    public static final String POLL_INTERVAL = "pollInterval";

    public static final String CONFIG_FILE_NAME = "configFileName";
    public static final String DEFAULT_CONFIG_FILE_NAME = "kubernetes.json";
    public static final String POD_STATUS_RUNNING = "Running";
}

/*
 * Copyright 2005-2014 Red Hat, Inc.
 *
 * Red Hat licenses this file to you 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 io.fabric8.arquillian.kubernetes;

public class Constants {

    public static final String ARQ_KEY = "arquillian";

    public static final String MASTER_URL = "masterUrl";
    public static final String CONFIG_URL = "configUrl";

    public static final String TIMEOUT = "timeout";
    public static final String POLL_INTERVAL = "pollInterval";

    public static final String CONFIG_FILE_NAME = "configFileName";
    public static final String DEFAULT_CONFIG_FILE_NAME = "kubernetes.json";
}

Remove constant that is not used anymore.


package de.danoeh.antennapod.core.util.comparator;

import java.util.Collections;
import java.util.Comparator;

import de.danoeh.antennapod.core.feed.FeedItem;

/** Compares the pubDate of two FeedItems for sorting*/
public class FeedItemPubdateComparator implements Comparator<FeedItem> {

	public static final Comparator<FeedItem> descending = new FeedItemPubdateComparator();
	public static final Comparator<FeedItem> ascending = Collections.reverseOrder(new FeedItemPubdateComparator());

	/** Returns a new instance of this comparator in reverse order.
	public static FeedItemPubdateComparator newInstance() {
		FeedItemPubdateComparator
	}*/
	@Override
	public int compare(FeedItem lhs, FeedItem rhs) {
		return rhs.getPubDate().compareTo(lhs.getPubDate());
	}

}

package de.danoeh.antennapod.core.util.comparator;

import java.util.Comparator;

import de.danoeh.antennapod.core.feed.FeedItem;

/** Compares the pubDate of two FeedItems for sorting*/
public class FeedItemPubdateComparator implements Comparator<FeedItem> {

	/** Returns a new instance of this comparator in reverse order.
	public static FeedItemPubdateComparator newInstance() {
		FeedItemPubdateComparator
	}*/
	@Override
	public int compare(FeedItem lhs, FeedItem rhs) {
		return rhs.getPubDate().compareTo(lhs.getPubDate());
	}

}

Remove unused comparators after SortOrder refactoring


package upparse.corpus;

/**
 * Data structure representing a bracket, not including a category label
 * @author eponvert@utexas.edu (Elias Ponvert)
 */
public class UnlabeledBracket implements Comparable<UnlabeledBracket> {

  private final int first, last;

  public UnlabeledBracket(final int _first, final int _last) {
    first = _first;
    last = _last;
  }

  @Override
  public boolean equals(Object obj) {
    final UnlabeledBracket b = (UnlabeledBracket) obj;
    return first == b.first && last == b.last;
  }

  @Override
  public int hashCode() {
    return 37 * first + last;
  }

  public int getFirst() {
    return first;
  }

  public int getLast() {
    return last;
  }

  public int len() {
    return last - first;
  }

  @Override
  public int compareTo(UnlabeledBracket o) {
    if (o == null) throw new NullPointerException();
    else if (last < o.first) return -1;
    else if (o.last < first) return 1;
    else if (o.first <= first && last <= o.last) return -1;
    else return 0;
  }

  public boolean contains(UnlabeledBracket b) {
    return first <= b.first && b.last <= last;
  }

  @Override
  public String toString() {
    return String.format("[%d,%d]", first, last);
  }
}

package upparse.corpus;

/**
 * Data structure representing a bracket, not including a category label
 * @author eponvert@utexas.edu (Elias Ponvert)
 */
public class UnlabeledBracket implements Comparable<UnlabeledBracket> {

  private final int first, last;

  public UnlabeledBracket(final int _first, final int _last) {
    first = _first;
    last = _last;
  }

  @Override
  public boolean equals(Object obj) {
    final UnlabeledBracket b = (UnlabeledBracket) obj;
    return first == b.first && last == b.last;
  }

  @Override
  public int hashCode() {
    return 37 * first + last;
  }

  public int getFirst() {
    return first;
  }

  public int getLast() {
    return last;
  }

  public int len() {
    return last - first;
  }

  @Override
  public int compareTo(UnlabeledBracket o) {
    if (o == null) throw new NullPointerException();
    else if (last < o.first) return -1;
    else if (o.last < first) return 1;
    else if (o.first == first && last == o.last) return 0;
    else if (o.first <= first && last <= o.last) return -1;
    else if (first <= o.first && o.last <= last) return 1;
    else return 0;
  }

  public boolean contains(UnlabeledBracket b) {
    return first <= b.first && b.last <= last;
  }

  @Override
  public String toString() {
    return String.format("[%d,%d]", first, last);
  }
}

Fix to bracket ordering in tree representation


/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package com.edinarobotics.zed;

import edu.wpi.first.wpilibj.IterativeRobot;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the IterativeRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class Zed extends IterativeRobot {
    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {

    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {

    }

    /**
     * This function is called periodically during operator control
     */
    public void teleopPeriodic() {

    }

    /**
     * This function is called periodically during test mode
     */
    public void testPeriodic() {

    }

}

/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package com.edinarobotics.zed;

import edu.wpi.first.wpilibj.IterativeRobot;

/**
 * The VM is configured to automatically run this class, and to call the
 * functions corresponding to each mode, as described in the IterativeRobot
 * documentation. If you change the name of this class or the package after
 * creating this project, you must also update the manifest file in the resource
 * directory.
 */
public class Zed extends IterativeRobot {
    /**
     * This function is run when the robot is first started up and should be
     * used for any initialization code.
     */
    public void robotInit() {
        Components.getInstance(); //Create all robot subsystems.
    }

    /**
     * This function is called periodically during autonomous
     */
    public void autonomousPeriodic() {

    }

    /**
     * This function is called periodically during operator control
     */
    public void teleopPeriodic() {

    }

    /**
     * This function is called periodically during test mode
     */
    public void testPeriodic() {

    }

}

Add call to Components.getInstance to robotInit.

This call will create all subsystems at robot init time.


package org.royaldev.royalcommands.listeners;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import org.royaldev.royalcommands.PConfManager;
import org.royaldev.royalcommands.RoyalCommands;

public class TagAPIListener implements Listener {

    RoyalCommands plugin;

    public TagAPIListener(RoyalCommands instance) {
        plugin = instance;
    }

    @EventHandler
    public void onTag(PlayerReceiveNameTagEvent e) {
        if (e.getNamedPlayer() == null) return;
        PConfManager pcm = new PConfManager(e.getNamedPlayer());
        String dispname = pcm.getString("dispname");
        if (dispname == null) return;
        if (dispname.equalsIgnoreCase(e.getNamedPlayer().getName())) {
            e.setTag(dispname);
            return;
        }
        if (!plugin.nickPrefix.equals(""))
            dispname = dispname.substring(plugin.nickPrefix.length());
        e.setTag(dispname);
    }

}

package org.royaldev.royalcommands.listeners;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.kitteh.tag.PlayerReceiveNameTagEvent;
import org.royaldev.royalcommands.PConfManager;
import org.royaldev.royalcommands.RoyalCommands;

public class TagAPIListener implements Listener {

    RoyalCommands plugin;

    public TagAPIListener(RoyalCommands instance) {
        plugin = instance;
    }

    @EventHandler
    public void onTag(PlayerReceiveNameTagEvent e) {
        if (e.getNamedPlayer() == null) return;
        PConfManager pcm = new PConfManager(e.getNamedPlayer());
        String dispname = pcm.getString("dispname");
        if (dispname == null) return;
        if (dispname.equalsIgnoreCase(e.getNamedPlayer().getName())) {
            e.setTag(dispname);
            return;
        }
        if (!plugin.nickPrefix.equals("") && dispname.startsWith(plugin.nickPrefix))
            dispname = dispname.substring(plugin.nickPrefix.length());
        e.setTag(dispname);
    }

}

Updated: Make sure nick has prefix if you're going to cut it off (TagAPI)


package radicalzephyr.boot_junit.test;

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import net.zephyrizing.http_server.Calculator;

public class CalculatorTest {
    @Test
    public void evaluatesExpression() {
        Calculator calculator = new Calculator();
        int sum = calculator.evaluate("1+2+3");
        assertEquals(6, 5);
    }
}

package radicalzephyr.boot_junit.test;

import radicalzephyr.boot_junit.test.Calculator;

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

public class CalculatorTest {
    @Test
    public void evaluatesExpression() {
        Calculator calculator = new Calculator();
        int sum = calculator.evaluate("1+2+3");
        assertEquals(6, 5);
    }
}

Fix the test class to compile

Fix the test class to compile


package ru.nsu.ccfit.bogush;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.nsu.ccfit.bogush.view.FactoryView;

public class Main {
	private static final String CONFIG_FILE = "config.properties";
	private static final String LOG_CONFIG_FILE = "log4j2.xml";
	private static final String LOGGER_NAME = "Main";
	private static final Logger logger;

	static {
		System.setProperty("log4j.configurationFile", LOG_CONFIG_FILE);
		logger = LogManager.getLogger(LOGGER_NAME);
	}

	public static void main(String[] args) {
		logger.trace("Launching application");
		try {
			logger.trace("Running prepare");
			Config config = new ConfigSerializer().load(CONFIG_FILE);
			new FactoryView(new CarFactoryModel(config));
		} catch (Exception e) {
			logger.fatal(e);
			e.printStackTrace();
		}
		logger.trace("Exiting");
	}
}

package ru.nsu.ccfit.bogush;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.nsu.ccfit.bogush.view.FactoryView;

public class Main {
	private static final String CONFIG_FILE     = "config.properties";
	private static final String LOG_CONFIG_FILE = "log4j2.xml";
	private static final String LOGGER_NAME     = "Main";
	private static final Logger logger;

	static {
		System.setProperty("log4j.configurationFile", LOG_CONFIG_FILE);
		logger = LogManager.getLogger(LOGGER_NAME);
	}

	public static void main(String[] args) {
		logger.trace("Launching application");
		try {
			logger.trace("Running prepare");
			Config config = new ConfigSerializer().load(CONFIG_FILE);
			new FactoryView(new CarFactoryModel(config));
		} catch (Exception e) {
			logger.fatal(e);
			e.printStackTrace();
			System.exit(1);
		} finally {
			logger.trace("Exiting");
		}
	}
}

Add exit with status 1 on caught exception Refactor


/**
 * DocumentValidator
 * Copyright (c) 2013-, Takahiko Ito, All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 */
package org.unigram.docvalidator.util;
/**
 * FakeResultDistributor does nothing. this class is just for testing.
 */
public class FakeResultDistributor implements ResultDistributor {
  /**
   * Constructor.
   */
  public FakeResultDistributor() {
    super();
  }

  @Override
  public int flushResult(ValidationError err) {
    return 0;
  }

  @Override
  public void setFormatter(Formatter formatter) {}

  @Override
  public void flushHeader() {}

  @Override
  public void flushFooter() {}
}

/**
 * DocumentValidator
 * Copyright (c) 2013-, Takahiko Ito, All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3.0 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library.
 */
package org.unigram.docvalidator.util;
/**
 * FakeResultDistributor does nothing. this class is just for testing.
 */
public class FakeResultDistributor implements ResultDistributor {
  /**
   * Constructor.
   */
  public FakeResultDistributor() {
    super();
  }

  @Override
  public int flushResult(ValidationError err) {
    return 0;
  }

  @Override
  public void setFormatter(Formatter formatter) { }

  @Override
  public void flushHeader() { }

  @Override
  public void flushFooter() { }
}

Add a white space after left brackets

Add a white space after left brackets


package com.markupartist.sthlmtraveling.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;

abstract public class WakefulIntentService extends IntentService {
    private static String TAG = "WakefulIntentService";
    public static final String LOCK_NAME_STATIC =
        "com.markupartist.sthlmtraveling.service.WakefulIntentService.Static";
    private static PowerManager.WakeLock lockStatic = null;

    public WakefulIntentService(String name) {
        super(name);
    }

    synchronized private static PowerManager.WakeLock getLock(Context context) {
        Log.d(TAG, "About to get lock");
        if (lockStatic == null) {
            PowerManager mgr =
                (PowerManager)context.getSystemService(Context.POWER_SERVICE);
            lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                    LOCK_NAME_STATIC);
            lockStatic.setReferenceCounted(true);
        }
        return lockStatic;
    }

    abstract void doWakefulWork(Intent intent);

    public static void acquireStaticLock(Context context) {
        Log.d(TAG, "About acquire static lock");
        getLock(context).acquire();
    }

    @Override
    final protected void onHandleIntent(Intent intent) {
        doWakefulWork(intent);
        getLock(this).release();
    }
}

package com.markupartist.sthlmtraveling.service;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;

abstract public class WakefulIntentService extends IntentService {
    private static String TAG = "WakefulIntentService";
    public static final String LOCK_NAME =
            "com.markupartist.sthlmtraveling.service.WakefulIntentService.Static";
    private static PowerManager.WakeLock lockStatic = null;

    public WakefulIntentService(String name) {
        super(name);
    }

    synchronized private static PowerManager.WakeLock getLock(Context context) {
        if (lockStatic == null) {
            PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);

            lockStatic = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, LOCK_NAME);
            lockStatic.setReferenceCounted(true);
        }

        return (lockStatic);
    }

    abstract void doWakefulWork(Intent intent);

    public static void acquireStaticLock(Context context) {
        Log.d(TAG, "About acquire static lock");
        getLock(context).acquire();
    }

    @Override
    final protected void onHandleIntent(Intent intent) {
        try {
            doWakefulWork(intent);
        } finally {
            PowerManager.WakeLock lock = getLock(getApplicationContext());
            if (lock.isHeld()) {
                try {
                    lock.release();
                } catch (Exception e) {
                    Log.e(TAG, "Exception when releasing wakelock");
                }
            }
        }
    }
}

Add some error handling around releasing wake locks


package io.github.trevornelson;

/**
 * Contains the client IDs and scopes for allowed clients consuming the helloworld API.
 */
public class Constants {
  public static final String WEB_CLIENT_ID = "99492469869-a8phf2icj5576p0a1or8v25djbqlb32k.apps.googleusercontent.com";
  public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID";
  public static final String IOS_CLIENT_ID = "replace this with your iOS client ID";
  public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID;

  public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
}

package io.github.trevornelson;

public class Constants {
  public static final String WEB_CLIENT_ID = "99492469869-a8phf2icj5576p0a1or8v25djbqlb32k.apps.googleusercontent.com";
  public static final String ANDROID_CLIENT_ID = "replace this with your Android client ID";
  public static final String IOS_CLIENT_ID = "replace this with your iOS client ID";
  public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID;

  public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email";
  public static final String ANALYTICS_SCOPE = "https://www.googleapis.com/auth/analytics.readonly";
}

Add ANALYTICS_SCOPE constant to constants file


package polyglot.server;

import io.grpc.stub.StreamObserver;
import polyglot.HelloProto.HelloRequest;
import polyglot.HelloProto.HelloResponse;
import polyglot.HelloServiceGrpc.HelloService;

public class HelloServiceImpl implements HelloService {
  @Override
  public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseStream) {
    responseStream.onNext(HelloResponse.getDefaultInstance());
  }
}

package polyglot.server;

import io.grpc.stub.StreamObserver;
import polyglot.HelloProto.HelloRequest;
import polyglot.HelloProto.HelloResponse;
import polyglot.HelloServiceGrpc.HelloService;

public class HelloServiceImpl implements HelloService {
  @Override
  public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseStream) {
    responseStream.onNext(HelloResponse.getDefaultInstance());
    responseStream.onCompleted();
  }
}

Make sure we always call onCompleted when responding to rpcs.


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the “License”). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.util;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests {@link IdUtils}.
 */
public final class IdUtilsTest {
  /**
   * Tests if output of {@link IdUtils#getRandomNonNegativeLong()} is non-negative.
   * Also tests for randomness property.
   */
  @Test
  public void getRandomNonNegativeLongTest() throws Exception {
    long first = IdUtils.getRandomNonNegativeLong();
    long second = IdUtils.getRandomNonNegativeLong();
    Assert.assertTrue(first >= 0);
    Assert.assertTrue(second >= 0);
    Assert.assertTrue(first != second);
  }
}

/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the “License”). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio.util;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests {@link IdUtils}.
 */
public final class IdUtilsTest {
  /**
   * Tests if output of {@link IdUtils#getRandomNonNegativeLong()} is non-negative.
   * Also tests for randomness property.
   */
  @Test
  public void getRandomNonNegativeLongTest() throws Exception {
    long first = IdUtils.getRandomNonNegativeLong();
    long second = IdUtils.getRandomNonNegativeLong();
    Assert.assertTrue(first >= 0);
    Assert.assertTrue(second >= 0);
    Assert.assertTrue(first != second);
  }

  /**
   * Tests if output of {@link IdUtils#createFileId(long)} is valid.
   */
  @Test
  public void createFileIdTest() throws Exception {
    long containerId = 1;
    long fileId = IdUtils.createFileId(containerId);
    Assert.assertTrue(fileId != -1);
  }

  /**
   * Tests if output of {@link IdUtils#createRpcId()} is non-empty.
   * Also tests for randomness property.
   */
  @Test
  public void createRpcIdTest() throws Exception {
    String first = IdUtils.createRpcId();
    Assert.assertTrue(first != null && !first.isEmpty());
    String second = IdUtils.createRpcId();
    Assert.assertTrue(second != null && !second.isEmpty());
    Assert.assertTrue(!first.equals(second));
  }
}

Add unit tests for IdUtils

[ALLUXIO-1776] Add unit tests for IdUtils


/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Sekai Kyoretsuna
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package io.fudev.laye.vm;

/**
 * @author Sekai Kyoretsuna
 */
public
class LayeKit
   extends LayeObject
{
   public LayeKit()
   {
   }

   @Override
   public String toString()
   {
      return(null);
   }

   public void setField(LayeVM vm, String key, LayeFunction.Callback callback)
   {
      setField(vm, key, new LayeFunction(callback));
   }
}

/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2015 Sekai Kyoretsuna
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package io.fudev.laye.vm;

/**
 * @author Sekai Kyoretsuna
 */
public
class LayeKit
   extends LayeObject
{
   public LayeKit()
   {
   }

   @Override
   public String toString()
   {
      return("LayeKit:" + hashCode());
   }

   public void setField(LayeVM vm, String key, LayeFunction.Callback callback)
   {
      setField(vm, key, new LayeFunction(callback));
   }
}

Fix 'bug' with kit toString

Fix 'bug' with kit toString

Was always returning null. Not good for debugging.


package io.quarkus.vertx.web.runtime;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;

import io.vertx.ext.web.Router;

@Singleton
public class RouterProducer {

    private volatile Router router;

    void initialize(Router router) {
        this.router = router;
    }

    // Note that we need a client proxy because if a bean also @Observes Router a null value would be injected
    @ApplicationScoped
    @Produces
    Router produceRouter() {
        return router;
    }

    @ApplicationScoped
    @Produces
    io.vertx.reactivex.ext.web.Router produceRxRouter() {
        return io.vertx.reactivex.ext.web.Router.newInstance(router);
    }

}

package io.quarkus.vertx.web.runtime;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Singleton;

import io.vertx.ext.web.Router;

@Singleton
public class RouterProducer {

    private volatile Router router;

    void initialize(Router router) {
        this.router = router;
    }

    // Note that we need a client proxy because if a bean also @Observes Router a null value would be injected
    @ApplicationScoped
    @Produces
    Router produceRouter() {
        return router;
    }

}

Remove CDI producer for io.vertx.reactivex.ext.web.Router


package io.liveoak.container.service;

import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;

/**
 * @author Ken Finnigan
 */
public class CodecInstallationCompleteService implements Service<Void> {
    @Override
    public void start(StartContext context) throws StartException {
        //Do Nothing
    }

    @Override
    public void stop(StopContext context) {
    }

    @Override
    public Void getValue() throws IllegalStateException, IllegalArgumentException {
        return null;
    }
}

package io.liveoak.container.service;

import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;

/**
 * @author Ken Finnigan
 */
public class CodecInstallationCompleteService implements Service<Void> {
    @Override
    public void start(StartContext context) throws StartException {
        //Do Nothing
        log.trace("Codec installation complete.");
    }

    @Override
    public void stop(StopContext context) {
    }

    @Override
    public Void getValue() throws IllegalStateException, IllegalArgumentException {
        return null;
    }

    static final Logger log = Logger.getLogger(CodecInstallationCompleteService.class);
}

Add trace message stating codec installation is complete


package uk.ac.ebi.quickgo.geneproduct.common;

/**
 * An enumeration of the possible states of proteome membership a gene product can have.
 * @author Tony Wardell
 * Date: 06/03/2018
 * Time: 10:33
 * Created with IntelliJ IDEA.
 */
public enum ProteomeMembership {
    REFERENCE("Reference"),
    COMPLETE("Complete"),
    NONE("None"),
    NOT_APPLICABLE("Not-applicable");

    private String value;

    ProteomeMembership(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }

    /**
     * Define the predicates required and order of importance to work out which Proteome membership category is
     * applicable.
     * @param isProtein is the gene product a protein
     * @param isReferenceProteome is the gene product a reference proteome
     * @param isComplete is the gene product a member of a complete proteome.
     * @return the String representation of the ProteomeMembership matching the applied constraints
     */
    public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {

        if (!isProtein) {
            return NOT_APPLICABLE.toString();
        } else if (isReferenceProteome) {
            return REFERENCE.toString();
        } else if (isComplete) {
            return COMPLETE.toString();
        }
        return NONE.toString();
    }
}

package uk.ac.ebi.quickgo.geneproduct.common;

/**
 * An enumeration of the possible states of proteome membership a gene product can have.
 * @author Tony Wardell
 * Date: 06/03/2018
 * Time: 10:33
 * Created with IntelliJ IDEA.
 */
public enum ProteomeMembership {
    REFERENCE("Reference"),
    COMPLETE("Complete"),
    NONE("None"),
    NOT_APPLICABLE("Not applicable");

    private String value;

    ProteomeMembership(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }

    /**
     * Define the predicates required and order of importance to work out which Proteome membership category is
     * applicable.
     * @param isProtein is the gene product a protein
     * @param isReferenceProteome is the gene product a reference proteome
     * @param isComplete is the gene product a member of a complete proteome.
     * @return the String representation of the ProteomeMembership matching the applied constraints
     */
    public static String membership(boolean isProtein, boolean isReferenceProteome, boolean isComplete) {

        if (!isProtein) {
            return NOT_APPLICABLE.toString();
        } else if (isReferenceProteome) {
            return REFERENCE.toString();
        } else if (isComplete) {
            return COMPLETE.toString();
        }
        return NONE.toString();
    }
}

Change the toString value for NOT_APPLICABLE to not 'applicable'