package uk.ac.ebi.atlas.search.analyticsindex;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.context.annotation.Scope;
import uk.ac.ebi.atlas.search.analyticsindex.solr.AnalyticsClient;
import uk.ac.ebi.atlas.search.analyticsindex.solr.AnalyticsQueryBuilder;
import uk.ac.ebi.atlas.solr.SolrUtil;
import uk.ac.ebi.atlas.web.GeneQuery;

import javax.inject.Inject;
import javax.inject.Named;

@Named
@Scope("singleton")
public class AnalyticsSearchService {

    private AnalyticsClient analyticsClient;

    @Inject
    public AnalyticsSearchService(AnalyticsClient analyticsClient) {
        this.analyticsClient = analyticsClient;
    }

    public Optional<ImmutableSet<String>> searchBioentityIdentifiers(GeneQuery geneQuery, String species) {
        QueryResponse queryResponse = analyticsClient.query(new AnalyticsQueryBuilder().queryIdentifierSearch(geneQuery).ofSpecies(species).setRows(0).facetByBioentityIdentifier().build());
        return Optional.of(SolrUtil.extractFirstFacetValues(queryResponse));
    }
}

package uk.ac.ebi.atlas.search.analyticsindex;

import com.google.common.base.Optional;
import com.google.common.collect.ImmutableSet;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.context.annotation.Scope;
import uk.ac.ebi.atlas.search.analyticsindex.solr.AnalyticsClient;
import uk.ac.ebi.atlas.search.analyticsindex.solr.AnalyticsQueryBuilder;
import uk.ac.ebi.atlas.solr.SolrUtil;
import uk.ac.ebi.atlas.web.GeneQuery;

import javax.inject.Inject;
import javax.inject.Named;

@Named
@Scope("singleton")
public class AnalyticsSearchService {

    private AnalyticsClient analyticsClient;

    @Inject
    public AnalyticsSearchService(AnalyticsClient analyticsClient) {
        this.analyticsClient = analyticsClient;
    }

    public ImmutableSet<String> searchBioentityIdentifiers(GeneQuery geneQuery, String species) {
        QueryResponse queryResponse = analyticsClient.query(new AnalyticsQueryBuilder().queryIdentifierSearch(geneQuery).ofSpecies(species).setRows(0).facetByBioentityIdentifier().build());
        return SolrUtil.extractFirstFacetValues(queryResponse);
    }
}

Remove Optional (Optional of a Set, when the Set can be empty seems overengineering things)


package dk.cmol.arduinorgb_controller;

import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class SliderFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_slider,
				container, false);

		return rootView;
	}

	@Override
	public void onResume() {
		super.onResume();

		boolean[] lamps = ((ArduinoRGBActivity) getActivity()).lamp_toggle;

		Button btns[] = { (Button) getActivity().findViewById(R.id.lamp1),
				(Button) getActivity().findViewById(R.id.lamp2),
				(Button) getActivity().findViewById(R.id.lamp3),
				(Button) getActivity().findViewById(R.id.lamp4) };

		for (int i = 0; i < lamps.length; i++) {
			if (lamps[i]) {
				btns[i].getBackground().setColorFilter(Color.GREEN,
						PorterDuff.Mode.MULTIPLY);
			}
		}
	}

}

package dk.cmol.arduinorgb_controller;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class SliderFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_slider, container,
				false);

		return rootView;
	}

}

Remove button update code, FIX later

Remove button update code, FIX later


package fi.tekislauta;

import static spark.Spark.*;
import fi.tekislauta.db.*;
import com.google.gson.*;
import fi.tekislauta.models.Board;
import fi.tekislauta.models.Post;

public class Main {
    public static void main(String[] args) {
        port(1234);

        Gson gson = new Gson();

        Database db = new Database();
        get("/api", (req, res) -> {
            return db.executeQuery("SELECT * FROM Board");
        });

        get("/api/boards/:id", (req,res) -> {
            return db.executeQuery("SELECT * FROM Board WHERE abbreviation='" + req.params("id") + "'");
        });

        get("/api/posts/:id", (req,res) -> {
            return "Hello world!";
        });

        get("/api/test", (req, res) -> {
            Board b = new Board(1, "Koulu", "Kumpula", "uliopisto");
            b.addPost(new Post(1,1,12345,123,"Joonan kissa", "Joonan kissat ovat ruotsalaisia"));

            b.addPost(new Post(2,2,12345,123,"Joonan kissa", "Joonan kissat ovat ruotsalaisia"));

            return gson.toJson(b);

        });
    }
}

package fi.tekislauta;

import static spark.Spark.*;
import fi.tekislauta.db.*;
import com.google.gson.*;
import fi.tekislauta.models.Board;
import fi.tekislauta.models.Post;

public class Main {
    public static void main(String[] args) {
        port(1234);

        Gson gson = new Gson();

        Database db = new Database();
        get("/api", (req, res) -> {
            return db.executeQuery("SELECT * FROM Board");
        });

        get("/api/boards/:id", (req,res) -> {
            return db.executeQuery("SELECT * FROM Board WHERE abbreviation='" + req.params("id") + "'");
        });

        get("/api/posts/:id", (req,res) -> {
            return "Hello world!";
        });

        get("/api/test", (req, res) -> {
            res.header("Content-Type","application/json");
            Board b = new Board(1, "Koulu", "Kumpula", "uliopisto");
            b.addPost(new Post(1,1,12345,123,"Joonan kissa", "Joonan kissat ovat ruotsalaisia"));

            b.addPost(new Post(2,2,12345,123,"Joonan kissa", "Joonan kissat ovat ruotsalaisia"));

            return gson.toJson(b);

        });
    }
}

Add JSON header to test method

Add JSON header to test method


/*
 * Copyright 2015-present Facebook, Inc.
 *
 * 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.buck.util;

import com.sun.security.auth.module.UnixSystem;

/**
 * Fetches the user ID of the running process.
 */
public class UnixUserIdFetcher implements UserIdFetcher {
  @Override
  public long getUserId() {
    return new UnixSystem().getUid();
  }
}

/*
 * Copyright 2015-present Facebook, Inc.
 *
 * 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.buck.util;

import java.lang.reflect.Method;

/**
 * Fetches the user ID of the running process.
 */
public class UnixUserIdFetcher implements UserIdFetcher {
  @Override
  public long getUserId() {
    try {
      Class<?> cls = Class.forName("com.sun.security.auth.module.UnixSystem", true, null);
      Object unixSystem = cls.newInstance();
      Method getUid = cls.getDeclaredMethod("getUid");
      return (long) getUid.invoke(unixSystem);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
}

Use reflection to access UnixSystem

Use reflection to access UnixSystem

Summary: This class doesn't exist on Windows and breaks compilation as a result.

Test Plan: `ant clean default` on Windows.


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

/**
 * A marker annotation to tell the primitive expander not to substitute
 * The line in question
 */
public @interface DoNotSub
{
}

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

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

/**
 * A marker annotation to tell the primitive expander not to substitute
 * The line in question
 */
@Retention(RetentionPolicy.SOURCE)
public @interface DoNotSub
{
}

[Java] Change retention policy on DoNotStub annotation so it is source only and not included in the class as is the default.


/*
 * Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
 */

package ai.vespa.metricsproxy.metric.model.json;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_ABSENT;

/**
 * @author gjoranv
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_ABSENT)
@JsonPropertyOrder({ "node", "services" })
public class GenericJsonModel {
    private static Logger log = Logger.getLogger(GenericJsonModel.class.getName());

    @JsonProperty("node")
    public GenericNode node;

    @JsonProperty("services")
    public List<GenericService> services;

    public String serialize() {
        ObjectMapper mapper = JacksonUtil.createObjectMapper();
        try {
            return mapper.writeValueAsString(this);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Could not render metrics. Check the log for details.");
        }
    }

}

/*
 * Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
 */

package ai.vespa.metricsproxy.metric.model.json;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_ABSENT;

/**
 * @author gjoranv
 */
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(NON_ABSENT)
@JsonPropertyOrder({ "node", "services" })
public class GenericJsonModel {
    private static Logger log = Logger.getLogger(GenericJsonModel.class.getName());

    @JsonProperty("node")
    public GenericNode node;

    @JsonProperty("services")
    public List<GenericService> services;

    public String serialize() {
        ObjectMapper mapper = JacksonUtil.createObjectMapper();
        try {
            return mapper.writeValueAsString(this);
        } catch (IOException e) {
            log.log(Level.WARNING, "Got exception when rendering metrics:", e);
            throw new RuntimeException("Could not render metrics. Check the log for details.");
        }
    }

}

Use logger instead of printStackTrace

Use logger instead of printStackTrace


package osgi.enroute.trains.controller.api;

import org.osgi.util.promise.Promise;

/**
 * This controller controls a LOCATOR Segment
 */
public interface RFIDSegmentController extends SegmentController {

	/**
	 * Read an RFID. Resolves the promise when a new RFID is read.
	 * @return
	 */
	Promise<String> lastRFID();
}

package osgi.enroute.trains.controller.api;

import org.osgi.util.promise.Promise;

/**
 * This controller controls a LOCATOR Segment
 */
public interface RFIDSegmentController extends SegmentController {

	/**
	 * Return the last seen RFID
	 */
	String lastRFID();

	/**
	 * Read an RFID. Resolves the promise when a new RFID is read.
	 * @return
	 */
	Promise<String> nextRFID();
}

Change method lastRFID to return immediately and have nextRFID method to return promise


package org.robolectric.android.fakes;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import androidx.test.runner.MonitoringInstrumentation;
import org.robolectric.Robolectric;
import org.robolectric.android.controller.ActivityController;

public class RoboMonitoringInstrumentation extends MonitoringInstrumentation {

  @Override
  protected void specifyDexMakerCacheProperty() {
    // ignore, unnecessary for robolectric
  }

  @Override
  protected void installMultidex() {
    // ignore, unnecessary for robolectric
  }

  @Override
  public void setInTouchMode(boolean inTouch) {
    // ignore
  }

  @Override
  public void waitForIdleSync() {
    // ignore
  }

  @Override
  public Activity startActivitySync(final Intent intent) {
    ActivityInfo ai = intent.resolveActivityInfo(getTargetContext().getPackageManager(), 0);
    try {
      Class<? extends Activity> activityClass = Class.forName(ai.name).asSubclass(Activity.class);
      ActivityController<? extends Activity> controller = Robolectric.buildActivity(activityClass, intent);
      Activity activity = controller.get();
      callActivityOnCreate(activity, null);
      controller.postCreate(null);
      callActivityOnStart(activity);
      callActivityOnResume(activity);
      controller.visible().windowFocusChanged(true);
      return activity;
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Could not load activity " + ai.name, e);
    }
  }

  @Override
  public void runOnMainSync(Runnable runner) {
    runner.run();
  }
}

package org.robolectric.android.fakes;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import androidx.test.runner.MonitoringInstrumentation;
import org.robolectric.Robolectric;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.shadows.ShadowLooper;

public class RoboMonitoringInstrumentation extends MonitoringInstrumentation {

  @Override
  protected void specifyDexMakerCacheProperty() {
    // ignore, unnecessary for robolectric
  }

  @Override
  protected void installMultidex() {
    // ignore, unnecessary for robolectric
  }

  @Override
  public void setInTouchMode(boolean inTouch) {
    // ignore
  }

  @Override
  public void waitForIdleSync() {
    ShadowLooper.getShadowMainLooper().idle();
  }

  @Override
  public Activity startActivitySync(final Intent intent) {
    ActivityInfo ai = intent.resolveActivityInfo(getTargetContext().getPackageManager(), 0);
    try {
      Class<? extends Activity> activityClass = Class.forName(ai.name).asSubclass(Activity.class);
      ActivityController<? extends Activity> controller = Robolectric.buildActivity(activityClass, intent);
      Activity activity = controller.get();
      callActivityOnCreate(activity, null);
      controller.postCreate(null);
      callActivityOnStart(activity);
      callActivityOnResume(activity);
      controller.visible().windowFocusChanged(true);
      return activity;
    } catch (ClassNotFoundException e) {
      throw new RuntimeException("Could not load activity " + ai.name, e);
    }
  }

  @Override
  public void runOnMainSync(Runnable runner) {
    runner.run();
  }
}

Call through to ShadowLooper on Instrumentation.waitForIdleSync

PiperOrigin-RevId: 203801396


package com.thebluealliance.androidclient.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.astuetz.PagerSlidingTabStrip;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.adapters.TeamListFragmentPagerAdapter;

public class AllTeamsListFragment extends Fragment {

    private ViewPager mViewPager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_team_list_fragment_pager, container, false);
        mViewPager = (ViewPager) v.findViewById(R.id.team_pager);
        mViewPager.setAdapter(new TeamListFragmentPagerAdapter(getChildFragmentManager()));
        mViewPager.setPageMargin(Utilities.getPixelsFromDp(getActivity(), 16));

        PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) v.findViewById(R.id.team_pager_tabs);
        tabs.setViewPager(mViewPager);
        return v;
    }
}

package com.thebluealliance.androidclient.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.astuetz.PagerSlidingTabStrip;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.Utilities;
import com.thebluealliance.androidclient.adapters.TeamListFragmentPagerAdapter;

public class AllTeamsListFragment extends Fragment {

    private ViewPager mViewPager;
    private PagerSlidingTabStrip mTabs;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_team_list_fragment_pager, container, false);
        mViewPager = (ViewPager) v.findViewById(R.id.team_pager);
        mViewPager.setPageMargin(Utilities.getPixelsFromDp(getActivity(), 16));
        mTabs = (PagerSlidingTabStrip) v.findViewById(R.id.team_pager_tabs);

        /**
         * Fix for really strange bug. Menu bar items wouldn't appear only when navigated to from 'Events' in the nav drawer
         * Bug is some derivation of this: https://code.google.com/p/android/issues/detail?id=29472
         * So set the view pager's adapter in another thread to avoid a race condition, or something.
         */
        mViewPager.post(new Runnable() {
            public void run() {
                mViewPager.setAdapter(new TeamListFragmentPagerAdapter(getChildFragmentManager()));
                mTabs.setViewPager(mViewPager);
            }
        });

        return v;
    }
}

Fix strange menu bug with teams

Fix strange menu bug with teams


package leetcode;

import java.util.Arrays;

/**
 * https://leetcode.com/problems/sort-colors/
 */
public class Problem75 {
    public void sortColors(int[] nums) {
        // using counting sort
        int[] aux = new int[nums.length];
        for (int i = 0; i < aux.length; i++) {
            aux[i] = nums[i];
        }
        System.out.println("Input: " + Arrays.toString(nums));
        int size = 3;
        int[] count = new int[size];
        for (int i = 0; i < aux.length; i++) {
            count[aux[i]] += 1;
        }
        System.out.println("Count: " + Arrays.toString(count));
        for (int i = 1; i < count.length; i++) {
            count[i] = count[i-1] + count[i];
        }
        System.out.println("Sum: " + Arrays.toString(count));
        for (int i = aux.length-1; i >= 0; i--) {
            int val = aux[i];
            count[val]--;
            int idx = count[val];
            nums[idx] = val;
        }
        System.out.println("Sorted: " + Arrays.toString(nums));
    }

    public static void main(String[] args) {
        Problem75 prob = new Problem75();
//        prob.sortColors(new int[]{2});
//        prob.sortColors(new int[]{3, 2, 1, 2, 3, 1});
//        prob.sortColors(new int[]{2, 27, 22, 8, 28, 1, 30, 8, 29, 28, 15, 16, 25, 28, 23, 16, 24, 23, 17, 11, 4, 2, 2, 22, 23, 8, 29, 16, 29, 28});
//        prob.sortColors(new int[]{1, 4, 1, 2, 7, 5, 2});
    }
}

package leetcode;

/**
 * https://leetcode.com/problems/sort-colors/
 */
public class Problem75 {
    public void sortColors(int[] nums) {
        // using counting sort
        int[] aux = new int[nums.length];
        for (int i = 0; i < aux.length; i++) {
            aux[i] = nums[i];
        }
        int size = 3;
        int[] count = new int[size];
        for (int i = 0; i < aux.length; i++) {
            count[aux[i]] += 1;
        }
        for (int i = 1; i < count.length; i++) {
            count[i] = count[i-1] + count[i];
        }
        for (int i = aux.length-1; i >= 0; i--) {
            int val = aux[i];
            count[val]--;
            int idx = count[val];
            nums[idx] = val;
        }
    }
}

Clean up problem 75 solution

Clean up problem 75 solution


package by.triumgroup.recourse.configuration.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final DataSource dataSource;

    @Autowired
    public ResourceServerConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                .tokenStore(tokenStore());
        resources.stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/**").permitAll()
                    .anyRequest().authenticated();
    }
}

package by.triumgroup.recourse.configuration.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final DataSource dataSource;

    @Autowired
    public ResourceServerConfiguration(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public TokenStore tokenStore() {
        return new JdbcTokenStore(dataSource);
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources
                .tokenStore(tokenStore());
        resources.stateless(false);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    // TODO Need to be configured
                    .antMatchers("/**").permitAll()
                    .anyRequest().authenticated();
    }
}

Add TODO task to security configuration.


/*
 Copyright 2014 Etienne Studer

 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 nu.studer.gradle.jooq;

/**
 * jOOQ comes in different editions, which are published
 * under different group ids. The artifact names and versions
 * are the same for all editions.
 */
public enum JooqEdition {

    OSS("org.jooq"),
    PRO("org.jooq.pro"),
    PRO_JAVA_8("org.jooq.pro-java-8"),
    PRO_JAVA_6("org.jooq.pro-java-6"),
    TRIAL("org.jooq.trial"),
    TRIAL_JAVA_8("org.jooq.trial-java-8"),
    TRIAL_JAVA_6("org.jooq.trial-java-6");

    private final String groupId;

    JooqEdition(String groupId) {
        this.groupId = groupId;
    }

    public String getGroupId() {
        return groupId;
    }

}

/*
 Copyright 2014 Etienne Studer

 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 nu.studer.gradle.jooq;

/**
 * jOOQ comes in different editions, which are published
 * under different group ids. The artifact names and versions
 * are the same for all editions.
 */
public enum JooqEdition {

    OSS("org.jooq"),
    PRO("org.jooq.pro"),
    PRO_JAVA_11("org.jooq.pro-java-11"),
    PRO_JAVA_8("org.jooq.pro-java-8"),
    PRO_JAVA_6("org.jooq.pro-java-6"),
    TRIAL("org.jooq.trial"),
    TRIAL_JAVA_11("org.jooq.trial-java-11"),
    TRIAL_JAVA_8("org.jooq.trial-java-8"),
    TRIAL_JAVA_6("org.jooq.trial-java-6");

    private final String groupId;

    JooqEdition(String groupId) {
        this.groupId = groupId;
    }

    public String getGroupId() {
        return groupId;
    }

}

Add support for new jOOQ 3.15 distributions

I've just published jOOQ 3.15, see:
https://blog.jooq.org/2021/07/06/3-15-0-release-with-support-for-r2dbc-nested-row-array-and-multiset-types-5-new-sql-dialects-create-procedure-function-and-trigger-support-and-much-more/

jOOQ 3.15 includes the following changes that are relevant for your plugin:

- The commercial editions now have a new Java 11 distribution. The default distribution is a Java 17 distribution (currently supporting Java 16)
- Support for the Java 6 distribution has been dropped in jOOQ 3.15, though I guess you should keep that enum value for now, in case someone uses jOOQ 3.14 or less
- The open source edition requires Java 11 starting from jOOQ 3.15

Let me know if you need any additional info and I'll be very happy to help.


package com.surfsoftconsulting.clipper.racetracker.controller;

/*
 * Copyright 2017 Phil Haigh
 *
 * 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.
 */

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class HealthCheckController {

    @RequestMapping(method=GET, path="/")
    public void healthCheck() {}

}

package com.surfsoftconsulting.clipper.racetracker.controller;

/*
 * Copyright 2017 Phil Haigh
 *
 * 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.
 */

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.web.bind.annotation.RequestMethod.GET;

@RestController
public class HealthCheckController {

    @RequestMapping(method=GET, path="/healthcheck")
    public void healthCheck() {}

}

Fix URL of healthcheck endpoint

Fix URL of healthcheck endpoint


package org.teiid.authoring.client.perspectives;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;

import org.uberfire.client.annotations.Perspective;
import org.uberfire.client.annotations.WorkbenchPerspective;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PanelType;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PartDefinitionImpl;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;

// /**
// * A Perspective to show File Explorer
// */
@ApplicationScoped
@WorkbenchPerspective(identifier = "MainPerspective", isDefault = true)
public class MainPerspective {

    private PerspectiveDefinition perspective;

    @PostConstruct
    public void init() {
        buildPerspective();
    }

    @Perspective
    public PerspectiveDefinition getPerspective() {
        return this.perspective;
    }

    public PerspectiveDefinition buildPerspective() {
        perspective = new PerspectiveDefinitionImpl( PanelType.ROOT_STATIC );
        perspective.setTransient(true);
        perspective.setName("MainPerspective");
        perspective.getRoot().addPart(new PartDefinitionImpl(new DefaultPlaceRequest("DataSourcesScreen")));

//        PanelDefinitionImpl westPanel = new PanelDefinitionImpl(PanelType.MULTI_LIST);
//        perspective.getRoot().insertChild(Position.WEST, westPanel);
//        westPanel.setWidth(250);
//        westPanel.addPart(
//                new PartDefinitionImpl(
//                        new DefaultPlaceRequest("MoodScreen")));

        return perspective;
    }
}

package org.teiid.authoring.client.perspectives;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;

import org.uberfire.client.annotations.Perspective;
import org.uberfire.client.annotations.WorkbenchPerspective;
import org.uberfire.mvp.impl.DefaultPlaceRequest;
import org.uberfire.workbench.model.PanelType;
import org.uberfire.workbench.model.PerspectiveDefinition;
import org.uberfire.workbench.model.impl.PartDefinitionImpl;
import org.uberfire.workbench.model.impl.PerspectiveDefinitionImpl;

// /**
// * A Perspective to show File Explorer
// */
@ApplicationScoped
@WorkbenchPerspective(identifier = "MainPerspective", isDefault = true)
public class MainPerspective {

    @Perspective
    public PerspectiveDefinition buildPerspective() {
        PerspectiveDefinition perspective = new PerspectiveDefinitionImpl( PanelType.ROOT_STATIC );
        perspective.setTransient(true);
        perspective.setName("MainPerspective");
        perspective.getRoot().addPart(new PartDefinitionImpl(new DefaultPlaceRequest("DataSourcesScreen")));

//        PanelDefinitionImpl westPanel = new PanelDefinitionImpl(PanelType.MULTI_LIST);
//        perspective.getRoot().insertChild(Position.WEST, westPanel);
//        westPanel.setWidth(250);
//        westPanel.addPart(
//                new PartDefinitionImpl(
//                        new DefaultPlaceRequest("MoodScreen")));

        return perspective;
    }
}

Fix perspective initialization issue when clicking on top menu navbar


package org.ligi.snackengage;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;

import org.junit.Test;
import org.ligi.snackengage.conditions.connectivity.IsConnectedViaWiFiOrUnknown;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

public class TheConnectedViaWifiSnackConditions extends BaseTest {

    @Test
    public void shouldReturnTrueForWifi() throws Exception {
        assertThat(setupSnack(ConnectivityManager.TYPE_WIFI)).isTrue();
    }

    @Test
    public void shouldReturnFalseForMobile() throws Exception {
        assertThat(setupSnack(ConnectivityManager.TYPE_MOBILE)).isFalse();
    }

    private boolean setupSnack(final int networkType) {
        final IsConnectedViaWiFiOrUnknown tested = new IsConnectedViaWiFiOrUnknown();

        when(mockAndroidContext.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE)).thenReturn(PackageManager.PERMISSION_GRANTED);

        when(mockNetwork.getType()).thenReturn(networkType);
        when(mockNetwork.isConnectedOrConnecting()).thenReturn(true);

        return tested.isAppropriate(mockSnackContext, null);
    }

}

package org.ligi.snackengage;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;

import org.junit.Test;
import org.ligi.snackengage.conditions.connectivity.IsConnectedViaWiFiOrUnknown;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

public class TheConnectedViaWifiSnackConditions extends BaseTest {

    @Test
    public void shouldReturnTrueForWifi() {
        assertThat(setupSnack(ConnectivityManager.TYPE_WIFI)).isTrue();
    }

    @Test
    public void shouldReturnFalseForMobile() {
        assertThat(setupSnack(ConnectivityManager.TYPE_MOBILE)).isFalse();
    }

    private boolean setupSnack(final int networkType) {
        final IsConnectedViaWiFiOrUnknown tested = new IsConnectedViaWiFiOrUnknown();

        when(mockAndroidContext.checkCallingOrSelfPermission(Manifest.permission.ACCESS_NETWORK_STATE)).thenReturn(PackageManager.PERMISSION_GRANTED);

        when(mockNetwork.getType()).thenReturn(networkType);
        when(mockNetwork.isConnectedOrConnecting()).thenReturn(true);

        return tested.isAppropriate(mockSnackContext, null);
    }

}

Remove unneeded exception in test.

Remove unneeded exception in test.


#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package};

import org.exoplatform.services.rest.resource.ResourceContainer;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

/**
 * Created by eXo Platform MEA on 06/05/14.
 *
 * @author Marwen Trabelsi
 */

@Path("/my-resource")
public class MyRestResource implements ResourceContainer {

  @GET
  @Path("/get/{name}")
  public String get(@PathParam("word") String word) {
    return "Hello " + word;
  }

}

#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${package};

import org.exoplatform.services.rest.resource.ResourceContainer;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

/**
 * Created by WiseBrains on 06/05/14.
 *
 * The MyRestResource class represents a RESTful GateIn
 * resource container.
 *
 * @author Marwen Trabelsi
 */

@Path("/my-resource")
public class MyRestResource implements ResourceContainer {

  /**
   * A GET style method that returns a {@code String} object that
   * formed of
Hello
 along with a
word
 forwarded
   * to the the method endpoint URL as a {@code PathParam}.
   */
  @GET
  @Path("/get/{name}")
  public String get(@PathParam("word") String word) {
    return "Hello " + word;
  }

}

[IMP] Add JavaDoc to GateIn Rest resource component


package io.freefair.gradle.plugins.github;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin;

/**
 * @author Lars Grefer
 */
public class GithubPackageRegistryMavenPublishPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        project.getPlugins().apply(MavenPublishPlugin.class);
        project.getPlugins().apply(GithubPomPlugin.class);

        GithubExtension githubExtension = project.getRootProject().getExtensions().getByType(GithubExtension.class);

        project.afterEvaluate(p -> p.getExtensions().getByType(PublishingExtension.class)
                .getRepositories()
                .maven(githubRepo -> {
                    String owner = githubExtension.getOwner().get();
                    githubRepo.setName("GitHub " + owner + " Apache Maven Packages");
                    githubRepo.setUrl("https://maven.pkg.github.com/" + githubExtension.getSlug().get());

                    if (githubExtension.getUsername().isPresent() && githubExtension.getToken().isPresent()) {
                        githubRepo.credentials(passwordCredentials -> {
                            passwordCredentials.setUsername(githubExtension.getUsername().get());
                            passwordCredentials.setPassword(githubExtension.getToken().get());
                        });
                    }

                }));

    }
}

package io.freefair.gradle.plugins.github;

import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.publish.PublishingExtension;
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin;

/**
 * @author Lars Grefer
 */
public class GithubPackageRegistryMavenPublishPlugin implements Plugin<Project> {
    @Override
    public void apply(Project project) {

        project.getPlugins().apply(MavenPublishPlugin.class);
        project.getPlugins().apply(GithubPomPlugin.class);

        GithubExtension githubExtension = project.getRootProject().getExtensions().getByType(GithubExtension.class);

        project.afterEvaluate(p -> p.getExtensions().getByType(PublishingExtension.class)
                .getRepositories()
                .maven(githubRepo -> {
                    githubRepo.setName("GithubPackageRegistry");
                    githubRepo.setUrl("https://maven.pkg.github.com/" + githubExtension.getSlug().get());

                    if (githubExtension.getUsername().isPresent() && githubExtension.getToken().isPresent()) {
                        githubRepo.credentials(passwordCredentials -> {
                            passwordCredentials.setUsername(githubExtension.getUsername().get());
                            passwordCredentials.setPassword(githubExtension.getToken().get());
                        });
                    }

                }));

    }
}

Use a better name for the gihub publishing repository


/**
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * 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.redhat.ipaas.rest.v1.handler.exception;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Provider
public class IPaasServerExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<ClassNotFoundException> {

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

	@Override
	public Response toResponse(ClassNotFoundException e) {
		LOG.error(e.getMessage(),e);
		RestError error = new RestError("Internal Server Exception. " + e.getMessage(), "Please contact the administrator and file a bug report", 500);
		return Response.status(error.errorCode).entity(error).build();
	}

}

/**
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * 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.redhat.ipaas.rest.v1.handler.exception;

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@Provider
public class IPaasServerExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> {

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

	@Override
	public Response toResponse(Exception e) {
		LOG.error(e.getMessage(),e);
		RestError error = new RestError("Internal Server Exception. " + e.getMessage(), "Please contact the administrator and file a bug report", 500);
		return Response.status(error.errorCode).entity(error).build();
	}

}

fix(exception-mapper): Return 500 errors for all unmapped exceptions


package controllers;

import models.Game;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.platform_read;

import java.util.List;

public class PlatformController extends Controller {

    public static Result read(final String platformName) {
        if (platformName == null) {
            return notFound();
        }
        List<Game> games = getGamesByPlatform(platformName);
        return ok(platform_read.render(platformName, games));
    }

    public static List<Game> getGamesByPlatform(final String platformName) {
        return Game.finder.where().ieq("platforms.name", platformName).findList();
    }

}

package controllers;

import models.Game;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.platform_read;

import java.util.List;

public class PlatformController extends Controller {

    public static Result read(final String platformName) {
        if (platformName == null) {
            return notFound();
        }
        List<Game> games = getGamesByPlatform(platformName);
        return ok(platform_read.render(platformName, games));
    }

    public static List<Game> getGamesByPlatform(final String platformName) {
        return Game.finder.where().ieq("platforms.name", platformName).order("title").findList();
    }

}

Order one cc by game title

Order one cc by game title


package common.pages;

import io.sphere.sdk.models.Base;
import io.sphere.sdk.models.Image;

public class ImageData extends Base {

    private final Image image;

    private ImageData(final Image image) {
        this.image = image;
    }

    public static ImageData of(final Image image) {
        return new ImageData(image);
    }

    public String getThumbImage() {
        return nullIfEmpty(image.getUrl());
    }

    public String getBigImage() {
        return nullIfEmpty(image.getUrl());
    }

    public String getPlaceholderImage() {
        return "http://placehold.it/350x150";
    }

    private String nullIfEmpty(final String s) {
        if(s.isEmpty())
            return null;
        else
            return s;
    }
}

package common.pages;

import io.sphere.sdk.models.Base;
import io.sphere.sdk.models.Image;

import static org.apache.commons.lang3.StringUtils.trimToNull;

public class ImageData extends Base {

    private final Image image;

    private ImageData(final Image image) {
        this.image = image;
    }

    public static ImageData of(final Image image) {
        return new ImageData(image);
    }

    public String getThumbImage() {
        return trimToNull(image.getUrl());
    }

    public String getBigImage() {
        return trimToNull(image.getUrl());
    }

    public String getPlaceholderImage() {
        return "http://placehold.it/350x150";
    }
}

Remove nullIfEmpty method and use StringUtils instead


package com.codenvy.ide.ext.datasource.client.common;

import com.google.gwt.user.cellview.client.CellTable;

public interface CellTableResources extends CellTable.Resources {

    public interface CellTableStyle extends CellTable.Style {
    }

    @Source({"CellTable.css", "com/codenvy/ide/api/ui/style.css"})
    CellTableStyle cellTableStyle();
}

package com.codenvy.ide.ext.datasource.client.common;

import com.google.gwt.user.cellview.client.CellTable;

public interface CellTableResources extends CellTable.Resources {

    public interface CellTableStyle extends CellTable.Style {

        String infoHeader();

        String queryReminder();

        String csvButton();

        String infoHeaderTitle();
    }

    @Source({"CellTable.css", "com/codenvy/ide/api/ui/style.css"})
    CellTableStyle cellTableStyle();
}

Add accessors to result headers styles

Add accessors to result headers styles


package org.wildfly.jaxrs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Created by Muhammad on 11/11/2015.
 */

// This class is located at "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {
    // These method will process HTTP GET requests
    // The Java method will produce content identified by the MIME Media

    /**
     * Method to return text/plain request
     * @return
     */
    @GET
    @Produces("application/json")
    public String getJsonMessage() {
        // return some cliched textual content
        return "{\"info\": \"Welcome to the demo of Wildfly, Java EE7 and AngularJS. This message is retrieved" +
                "serve using REST API and consume by AngularJS.\"}";
    }

}

package org.wildfly.jaxrs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

/**
 * Created by Muhammad on 11/11/2015.
 */

// This class is located at "/helloworld"
@Path("/helloworld")
public class HelloWorldResource {
    // These method will process HTTP GET requests
    // The Java method will produce content identified by the MIME Media

    /**
     * Method to return text/plain request
     * @return
     */
    @GET
    @Produces("application/json")
    public String getJsonMessage() {
        // return some cliched textual content
        return "{\"info\": \"Welcome to the demo of Wildfly, Java EE7 and AngularJS. This message is " +
                "served using REST API and consumed by AngularJS.\"}";
    }

}

Fix grammar of the sentence for welcome page.


package net.chrizzly.csharp4netbeans.filetypes.cs.parser.reformatting;

import javax.swing.text.BadLocationException;
import org.netbeans.modules.editor.indent.spi.Context;
import org.netbeans.modules.editor.indent.spi.ExtraLock;
import org.netbeans.modules.editor.indent.spi.ReformatTask;
import org.openide.awt.StatusDisplayer;

/**
 *
 * @author chrl
 */
public class CsReformatTask implements ReformatTask {

    private Context context;

    public CsReformatTask(Context context) {
        this.context = context;
    }

    @Override
    public void reformat() throws BadLocationException {
        StatusDisplayer.getDefault().setStatusText("We will format this now...");
    }

    @Override
    public ExtraLock reformatLock() {
        return null;
    }

}

package net.chrizzly.csharp4netbeans.filetypes.cs.parser.reformatting;

import java.util.List;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import net.chrizzly.csharp4netbeans.utils.MiscUtil;
import org.netbeans.modules.editor.indent.spi.Context;
import org.netbeans.modules.editor.indent.spi.ExtraLock;
import org.netbeans.modules.editor.indent.spi.ReformatTask;
import org.openide.awt.StatusDisplayer;

/**
 *
 * @author chrl
 */
public class CsReformatTask implements ReformatTask {

    private final Context context;

    public CsReformatTask(Context context) {
        this.context = context;
    }

    @Override
    public void reformat() throws BadLocationException {
        StatusDisplayer.getDefault().setStatusText("We will format this now...");
        Document document = context.document();
        String fileContent = document.getText(document.getStartPosition().getOffset(),
                document.getEndPosition().getOffset());
        String fileFormattedFinal = formatFile(fileContent, 4);
        int length = document.getLength();
        document.remove(0, length);
        document.insertString(0, fileFormattedFinal, null);
    }

    @Override
    public ExtraLock reformatLock() {
        return null;
    }

    private static String formatFile(String fileContent, int spacesToIncrement) {
        short currentSpacesToUse = 0;

        StringBuilder sbResult = new StringBuilder();

        List<String> listLines = MiscUtil.getLinesFromFileContent(fileContent);
        for (String line : listLines) {
            int openTagsAmount = MiscUtil.getOpenSymbolsAmount(line);

            String amountSeparatorChars;
            if (openTagsAmount > 0) {
                amountSeparatorChars = MiscUtil.getAmountSeparatorChars(currentSpacesToUse);
                currentSpacesToUse += spacesToIncrement * openTagsAmount;
            } else {
                currentSpacesToUse += spacesToIncrement * openTagsAmount;
                amountSeparatorChars = MiscUtil.getAmountSeparatorChars(currentSpacesToUse);
            }

            sbResult.append(amountSeparatorChars).append(line.trim()).append(MiscUtil.LINE_SEPARATOR);
        }

        return sbResult.toString().substring(0, sbResult.length() - 1); //substring to remove the last LINE_SEPARATOR
    }
}

Copy over the reformat code from a fork of pedro.


/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.clustering.mesos.client.model.marathon.v2;

public class Command {

    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

}

Add header and remove final blank space

Add header and remove final blank space


package com.example.android.waitlist.data;

import android.provider.BaseColumns;

public class WaitlistContract {

    // TODO (1) Create an inner class named WaitlistEntry class that implements the BaseColumns interface

        // TODO (2) Inside create a static final members for the table name and each of the db columns
        // TABLE_NAME -> waitlist;
        // COLUMN_GUEST_NAME -> guestName
        // COLUMN_PARTY_SIZE -> partySize
        // COLUMN_TIMESTAMP -> timestamp

}

package com.example.android.waitlist.data;

import android.provider.BaseColumns;

public class WaitlistContract {

    private WaitlistContract(){};
    // TODO (1) Create an inner class named WaitlistEntry class that implements the BaseColumns interface

        // TODO (2) Inside create a static final members for the table name and each of the db columns
        // TABLE_NAME -> waitlist;
        // COLUMN_GUEST_NAME -> guestName
        // COLUMN_PARTY_SIZE -> partySize
        // COLUMN_TIMESTAMP -> timestamp
    public static final class WaitlistEntry implements BaseColumns {
            public static final String TABLE_NAME = "waitlist";
            public static final String COLUMN_GUEST_NAME = "guestName";
            public static final String COLUMN_PARTY_SIZE = "partySize";
            public static final String COLUMN_TIMESTAMP = "timestamp";
    }

}

Complete TODOs for T07.01 CreateAContract exercise


package org.ovirt.engine.core.common.queries;

import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;

public class GetFilteredAttachableDisksParameters extends GetAllAttachableDisksForVmQueryParameters {

    private int os;

    private Version vdsGroupCompatibilityVersion;

    public GetFilteredAttachableDisksParameters() {
        super();
    }

    public GetFilteredAttachableDisksParameters(Guid storagePoolId) {
        super(storagePoolId);
    }

    public int getOs() {
        return os;
    }

    public void setOs(int os) {
        this.os = os;
    }

    public Version getVdsGroupCompatibilityVersion() {
        return vdsGroupCompatibilityVersion;
    }

    public void setVdsGroupCompatibilityVersion(Version vdsGroupCompatibilityVersion) {
        this.vdsGroupCompatibilityVersion = vdsGroupCompatibilityVersion;
    }
}

package org.ovirt.engine.core.common.queries;

import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;

public class GetFilteredAttachableDisksParameters extends GetAllAttachableDisksForVmQueryParameters {

    private static final long serialVersionUID = 4092810692277463140L;

    private int os;

    private Version vdsGroupCompatibilityVersion;

    public GetFilteredAttachableDisksParameters() {
        super();
    }

    public GetFilteredAttachableDisksParameters(Guid storagePoolId) {
        super(storagePoolId);
    }

    public int getOs() {
        return os;
    }

    public void setOs(int os) {
        this.os = os;
    }

    public Version getVdsGroupCompatibilityVersion() {
        return vdsGroupCompatibilityVersion;
    }

    public void setVdsGroupCompatibilityVersion(Version vdsGroupCompatibilityVersion) {
        this.vdsGroupCompatibilityVersion = vdsGroupCompatibilityVersion;
    }
}

Add missing serial version id

core: Add missing serial version id

Change-Id: I1467bfda3a1f349087266bedb0fafac7170baeb2
Signed-off-by: Moti Asayag <da1debb83a8e12b6e8822edf2c275f55cc51b720@redhat.com>


package org.panda_lang.panda.framework.language.interpreter.parser.implementation.general.expression.updated.subparsers;

public class DefaultSubparserPriorities {

    public static final double SINGLE = 0;

    public static final double AFTER_SINGLE = 1;

    public static final double DYNAMIC = 2;

    public static final double AFTER_DYNAMIC = 3;

}

package org.panda_lang.panda.framework.language.interpreter.parser.implementation.general.expression.updated.subparsers;

public class DefaultSubparserPriorities {

    public static final double DYNAMIC = 1;

    public static final double SINGLE = 2;

}

Swap DYNAMIC parsers with SINGLE

Swap DYNAMIC parsers with SINGLE


package com.yuyakaido.android.cardstackview.internal;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;

import com.yuyakaido.android.cardstackview.CardStackLayoutManager;

public class CardStackDataObserver extends RecyclerView.AdapterDataObserver {

    private final RecyclerView recyclerView;

    public CardStackDataObserver(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    @Override
    public void onChanged() {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        manager.setTopPosition(0);
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
        // Do nothing
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        if (positionStart == 0) {
            manager.setTopPosition(0);
        }
        manager.removeAllViews();
    }

    @Override
    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
        // Do nothing
    }

    private CardStackLayoutManager getCardStackLayoutManager() {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof CardStackLayoutManager) {
            return (CardStackLayoutManager) manager;
        }
        throw new IllegalStateException("CardStackView must be set CardStackLayoutManager.");
    }

}

package com.yuyakaido.android.cardstackview.internal;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;

import com.yuyakaido.android.cardstackview.CardStackLayoutManager;

public class CardStackDataObserver extends RecyclerView.AdapterDataObserver {

    private final RecyclerView recyclerView;

    public CardStackDataObserver(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
    }

    @Override
    public void onChanged() {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        manager.setTopPosition(0);
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeChanged(int positionStart, int itemCount, @Nullable Object payload) {
        // Do nothing
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        // Do nothing
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        if (positionStart == 0) {
            manager.setTopPosition(0);
        }
        manager.removeAllViews();
    }

    @Override
    public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
        CardStackLayoutManager manager = getCardStackLayoutManager();
        manager.removeAllViews();
    }

    private CardStackLayoutManager getCardStackLayoutManager() {
        RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
        if (manager instanceof CardStackLayoutManager) {
            return (CardStackLayoutManager) manager;
        }
        throw new IllegalStateException("CardStackView must be set CardStackLayoutManager.");
    }

}

Refresh all views when invoking move action


package com.sandjelkovic.dispatch.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer
public class DispatchdConfigurationApplication {

	public static void main(String[] args) {
		SpringApplication.run(DispatchdConfigurationApplication.class, args);
	}
}

package com.sandjelkovic.dispatch.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//@EnableConfigServer
public class DispatchdConfigurationApplication {

	public static void main(String[] args) {
		SpringApplication.run(DispatchdConfigurationApplication.class, args);
	}
}

Fix failing test by temporarily removing Config server activation


package com.redhat.ceylon.eclipse.core.model;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;

import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;

public class ProjectSourceFile extends SourceFile implements IResourceAware {

    public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
        super(phasedUnit);
    }

    @Override
    public ProjectPhasedUnit getPhasedUnit() {
        return (ProjectPhasedUnit) super.getPhasedUnit();
    }

    @Override
    public IProject getProjectResource() {
        return getPhasedUnit().getProjectResource();
    }

    @Override
    public IFile getFileResource() {
        return (IFile)((ResourceVirtualFile) (getPhasedUnit().getUnitFile())).getResource();
    }

    @Override
    public IFolder getRootFolderResource() {
        return null;
    }
}

package com.redhat.ceylon.eclipse.core.model;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;

import com.redhat.ceylon.eclipse.core.typechecker.ProjectPhasedUnit;
import com.redhat.ceylon.eclipse.core.vfs.ResourceVirtualFile;

public class ProjectSourceFile extends SourceFile implements IResourceAware {

    public ProjectSourceFile(ProjectPhasedUnit phasedUnit) {
        super(phasedUnit);
    }

    @Override
    public ProjectPhasedUnit getPhasedUnit() {
        return (ProjectPhasedUnit) super.getPhasedUnit();
    }

    @Override
    public IProject getProjectResource() {
        return getPhasedUnit().getProjectResource();
    }

    @Override
    public IFile getFileResource() {
        return getPhasedUnit().getSourceFileResource();
    }

    @Override
    public IFolder getRootFolderResource() {
        return getPhasedUnit().getSourceFolderResource();
    }
}

Correct implementation of the IResourceAware methods


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

package org.gradle.launcher.daemon.server.exec;

import org.gradle.launcher.daemon.server.api.DaemonCommandAction;
import org.gradle.launcher.daemon.server.api.DaemonCommandExecution;
import org.gradle.internal.deprecation.DeprecationLogger;

public class ResetDeprecationLogger implements DaemonCommandAction {
    @Override
    public void execute(DaemonCommandExecution execution) {
        DeprecationLogger.reset();
        execution.proceed();
    }
}

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

package org.gradle.launcher.daemon.server.exec;

import org.gradle.internal.deprecation.DeprecationLogger;
import org.gradle.launcher.daemon.server.api.DaemonCommandAction;
import org.gradle.launcher.daemon.server.api.DaemonCommandExecution;
import org.gradle.util.IncubationLogger;

public class ResetDeprecationLogger implements DaemonCommandAction {
    @Override
    public void execute(DaemonCommandExecution execution) {
        DeprecationLogger.reset();
        IncubationLogger.reset();
        execution.proceed();
    }
}

Reset incubation logger with deprecation logger


package org.junit.core;

import org.opentestalliance.TestAbortedException;

/**
 * @author Sam Brannen
 * @since 5.0
 */
public final class Assumptions {

	private Assumptions() {
		/* no-op */
	}

	public static void assumeTrue(boolean condition) {
		if (!condition) {
			throw new TestAbortedException("Assumption failed: condition is not true");
		}
	}

	public static void assumeFalse(boolean condition) {
		if (condition) {
			throw new TestAbortedException("Assumption failed: condition is not false");
		}
	}

	public static void assumingThat(boolean condition, Executable executable) {
		if (condition) {
			try {
				executable.execute();
			}
			catch (Throwable e) {
				throw new RuntimeException("Wrapped exception thrown from Executable", e);
			}
		}
	}

}

package org.junit.core;

import org.opentestalliance.TestAbortedException;

/**
 * @author Sam Brannen
 * @since 5.0
 */
public final class Assumptions {

	private Assumptions() {
		/* no-op */
	}

	public static void assumeTrue(boolean condition) {
		if (!condition) {
			throw new TestAbortedException("Assumption failed: condition is not true");
		}
	}

	public static void assumeFalse(boolean condition) {
		if (condition) {
			throw new TestAbortedException("Assumption failed: condition is not false");
		}
	}

	public static void assumingThat(boolean condition, Executable executable) {
		if (condition) {
			try {
				executable.execute();
			}
			catch (Throwable e) {
				// TODO Don't wrap Throwables such as OutOfMemoryError, etc.
				throw new RuntimeException("Wrapped exception thrown from Executable", e);
			}
		}
	}

}

Add TODO re: not wrapping exceptions like OutOfMemoryError


package net.kencochrane.raven.getsentry.connection;

import mockit.Deencapsulation;
import mockit.Injectable;
import mockit.Tested;
import org.testng.annotations.Test;

import javax.net.ssl.SSLHandshakeException;
import java.net.URL;
import java.net.URLConnection;

import static org.testng.Assert.fail;

public class GetSentryHttpsConnectionTest {
    @Tested
    private GetSentryHttpsConnection connection;
    @Injectable("projectId")
    private String projectId;
    @Injectable("privateKey")
    private String publicKey;
    @Injectable("secretKey")
    private String secretKey;

    @Test
    public void ensureHttpsConnectionToGetSentryIsSecure() throws Exception {
        connection.getConnection().connect();
    }

    @Test(expectedExceptions = SSLHandshakeException.class)
    public void ensureHttpsConnectionToGoogleComIsNotSecure() throws Exception {
        final URL url = new URL("https://www.google.com");
        Deencapsulation.setField(connection, "sentryUrl", url);

        connection.getConnection().connect();
    }

    @Test(expectedExceptions = SSLHandshakeException.class)
    public void ensureHttpsConnectionToGetSentryRequiresCustomSslFactory() throws Exception {
        final URLConnection httpsConnection = GetSentryHttpsConnection.getSentryUrl(projectId).openConnection();

        httpsConnection.connect();

        fail("Ensure that the StartCom certificate hasn't been added manually to the KeyStore or skip this test.");
    }
}

package net.kencochrane.raven.getsentry.connection;

import mockit.Deencapsulation;
import mockit.Injectable;
import mockit.Tested;
import org.testng.annotations.Test;

import javax.net.ssl.SSLHandshakeException;
import java.net.URL;
import java.net.URLConnection;

import static org.testng.Assert.fail;

public class GetSentryHttpsConnectionTest {
    @Tested
    private GetSentryHttpsConnection connection;
    @Injectable("projectId")
    private String projectId;
    @Injectable("privateKey")
    private String publicKey;
    @Injectable("secretKey")
    private String secretKey;

    @Test
    public void ensureHttpsConnectionToGetSentryIsSecure() throws Exception {
        connection.getConnection().connect();
    }

    @Test(expectedExceptions = SSLHandshakeException.class)
    public void ensureHttpsConnectionToGoogleComIsNotSecure() throws Exception {
        final URL url = new URL("https://www.google.com");
        Deencapsulation.setField(connection, "sentryUrl", url);

        connection.getConnection().connect();
    }

    /*
     * Test disabled as it will fail when the CA is available in the default KeyStore.
     * It is useful to be able to run it to ensure that it's indeed necessary to keep the entire module.
     */
    @Test(expectedExceptions = SSLHandshakeException.class, enabled = false)
    public void ensureHttpsConnectionToGetSentryRequiresCustomSslFactory() throws Exception {
        final URLConnection httpsConnection = GetSentryHttpsConnection.getSentryUrl(projectId).openConnection();

        httpsConnection.connect();

        fail("Ensure that the StartCom certificate hasn't been added manually to the KeyStore or skip this test.");
    }
}

Disable the test on ensureHttpsConnectionToGetSentryRequiresCustomSslFactory


import org.junit.*;
import static org.junit.Assert.*;
import java.util.ArrayList;

public class ScrabbleTest {

  @Test
  public void scrabbleScore_returnsAScrabbleScoreForALetter_1() {
    Scrabble app = new Scrabble();
    Integer score = 1;
    assertEquals(score, app.scrabbleScore("a"));
  }

  // @Test
  // public void scrabbleScore_returnsAString_a() {
  //   Scrabble app = new Scrabble();
  //   String letter = "a";
  //   assertEquals(letter, app.scrabbleScore("a"));
  // }

  // @Test
  // public void scrabbleScore_returnsAnArrayList_aa() {
  //   Scrabble app = new Scrabble();
  //   ArrayList<String> expectedArray = new ArrayList<String>();
  //   expectedArray.add("a");
  //   expectedArray.add("a");
  //   assertEquals(expectedArray, app.scrabbleScore("aa"));
  // }

  @Test
  public void scrabbleScore_returnsTotalScore_2() {
    Scrabble app = new Scrabble();
    Integer total = 2;
    assertEquals(total, app.scrabbleScore("aa"));
  }

  @Test
    public void scrabbleScore_returnsDifferentTotalScore_5() {
      Scrabble app = new Scrabble();
      Integer total = 5;
      assertEquals(total, app.scrabbleScore("cat"));
    }

    @Test
      public void scrabbleScore_returnsTotalForTwoWords_9() {
        Scrabble app = new Scrabble();
        Integer total = 9;
        assertEquals(total, app.scrabbleScore("Cat dog"));
      }

  }

import org.junit.*;
import static org.junit.Assert.*;
import java.util.ArrayList;

public class ScrabbleTest {

  @Test
  public void scrabbleScore_returnsAScrabbleScoreForALetter_1() {
    Scrabble app = new Scrabble();
    Integer score = 1;
    assertEquals(score, app.scrabbleScore("a"));
  }

  @Test
  public void scrabbleScore_returnsTotalScore_2() {
    Scrabble app = new Scrabble();
    Integer total = 2;
    assertEquals(total, app.scrabbleScore("aa"));
  }

  @Test
    public void scrabbleScore_returnsDifferentTotalScore_5() {
      Scrabble app = new Scrabble();
      Integer total = 5;
      assertEquals(total, app.scrabbleScore("cat"));
    }

    @Test
      public void scrabbleScore_returnsTotalForTwoWords_10() {
        Scrabble app = new Scrabble();
        Integer total = 10;
        assertEquals(total, app.scrabbleScore("Cat dog"));
      }

  }

Add new test with multiple words to pass, clean up comments in test.


package xyz.brassgoggledcoders.steamagerevolution.modules.storage.renderers;

import javax.annotation.Nonnull;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import xyz.brassgoggledcoders.steamagerevolution.modules.storage.tileentities.TileEntityBasicFluidTank;
import xyz.brassgoggledcoders.steamagerevolution.utils.RenderUtil;

public class TileEntityBasicFluidTankRenderer extends TileEntitySpecialRenderer<TileEntityBasicFluidTank> {

	protected static Minecraft mc = Minecraft.getMinecraft();

	@Override
	public void renderTileEntityFast(@Nonnull TileEntityBasicFluidTank tile, double x, double y, double z,
			float partialTicks, int destroyStage, float partial, net.minecraft.client.renderer.BufferBuilder buffer) {
		FluidTank tank = tile.tank;
		FluidStack liquid = tank.getFluid();

		if(liquid != null) {

			float height = ((float) liquid.amount) / (float) tank.getCapacity();

			float d = RenderUtil.FLUID_OFFSET;
			RenderUtil.renderFluidCuboid(liquid, tile.getPos(), x, y, z, d, d, d, 1d - d, height - d, 1d - d);
		}
	}
}

package xyz.brassgoggledcoders.steamagerevolution.modules.storage.renderers;

import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.FluidTank;
import xyz.brassgoggledcoders.steamagerevolution.modules.storage.tileentities.TileEntityBasicFluidTank;
import xyz.brassgoggledcoders.steamagerevolution.utils.RenderUtil;

public class TileEntityBasicFluidTankRenderer extends TileEntitySpecialRenderer<TileEntityBasicFluidTank> {

	protected static Minecraft mc = Minecraft.getMinecraft();

	@Override
	public void render(TileEntityBasicFluidTank tile, double x, double y, double z, float partialTicks,
			int destroyStage, float alpha) {
		FluidTank tank = tile.tank;
		FluidStack liquid = tank.getFluid();

		if(liquid != null) {

			float height = ((float) liquid.amount) / (float) tank.getCapacity();

			float d = RenderUtil.FLUID_OFFSET;
			RenderUtil.renderFluidCuboid(liquid, tile.getPos(), x, y, z, d, d, d, 1d - d, height - d, 1d - d);
		}
	}
}

Fix fluid in tank rendering

Fix fluid in tank rendering


package backend;

public class ConstantValues {
	/*
	 * Certificate for the terminals should not have an expdate
	 * Certificate WITOUT expdate is a byte array that looks like:
	 * cert[0] = type (0 = smartcard, 1 = rentalterm, 2 = vehicleterm)
	 * cert[1..163] = rsapublickey (length 162bytes)
	 * cert[164...292] = Signature (128bytes)
	 */

	/* TODO: Change exp to short
	 * Certificate with expdate is a byte array that looks like:
	 * cert[0] = type (0 = smartcard, 1 = rentalterm, 2 = vehicleterm)
	 * cert[1..163] = rsapublickey (length 162bytes)
	 * cert[164..172] = expiration date of type long (8bytes)
	 * cert[173...301] = Signature (128bytes)
	 */
	public int RSAPUBLICKEYLENGTH = 162;
	public int EXP_LENGTH = 8;
	public int PK_EXP_LENGTH = 170; //162+8
	public int SIG_LENGTH = 128;

}

package backend;

public class ConstantValues {

	public int RSAPUBLICKEYLENGTH = 162;
	public int PUBMODULUS = 128; // after you strip off the first byte (which = 0)
	public int PUBEXPONENT = 3;
	public int PRIVMODULUS = 128; // after you strip off the first byte (which = 0)
	public int PRIVEXPONENT = 128; // after you strip off the first byte (which = 0)
	public int EXP_LENGTH = 8;
	public int PK_EXP_LENGTH = 170; //162+8
	public int SIG_LENGTH = 128;

}

Add modulus and exponent sizes

Add modulus and exponent sizes


package ryhma57.gui;

import java.util.EnumMap;
import ryhma57.backend.BibtexReferenceField;

/**
 * This is the main class currently.
 */
public class Application {
    public static void main(String[] args) {
        Application app = new Application();
        Window window;
        window = new Window(app);

        window.setVisible(true);
        System.out.println("test");
    }

    public void generateBibTex() {
        //XXX do something here
        System.out.println("Generate the bibtext file in the backend");
    }

    public void createNewBookReference(EnumMap<BibtexReferenceField, String> fields) {
        //XXX do something here
        System.out.println("Create the book reference in the backend");

        /* Push the changes into backend */
        //Reference ref = new Reference();
        //ref = this.referenceList.addReference(ref);
        //
        //for (BibtexReferenceField field : fields.keySet()) {
        //    ref.setField(field, fields.get(field));
        //}
    }
}

package ryhma57.gui;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.EnumMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import ryhma57.backend.BibtexReferenceField;
import ryhma57.backend.Book;
import ryhma57.backend.Reference;

/**
 * This is the main class currently.
 */
public class Application {
    public static void main(String[] args) {
        Application app = new Application();
        Window window;
        window = new Window(app);

        window.setVisible(true);
        System.out.println("test");
    }

    public void generateBibTex() {
        PrintWriter writer;
        System.out.println("Generate the bibtext file in the backend");

        try {
            writer = new PrintWriter("database.bib", "UTF-8");
            writer.print("Implement" /*this.referenceList.toBibTex()*/);
            writer.close();

        } catch (FileNotFoundException | UnsupportedEncodingException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void createNewBookReference(EnumMap<BibtexReferenceField, String> fields) {
        System.out.println("Create the book reference in the backend");

        String id = fields.get(BibtexReferenceField.ID);
        String author = fields.get(BibtexReferenceField.AUTHOR);
        String title = fields.get(BibtexReferenceField.TITLE);
        String year = fields.get(BibtexReferenceField.YEAR);
        String publisher = fields.get(BibtexReferenceField.PUBLISHER);

        Reference ref = new Book(id, author, title, year, publisher);
        //this.referenceList.addReference(ref);

        /* Alternative way to push the changes into backend */
        //Reference ref = new Reference();
        //this.referenceList.addReference(ref);
        //
        //for (BibtexReferenceField field : fields.keySet()) {
        //    ref.setField(field, fields.get(field));
        //}
    }
}

Implement most of the initial window contoller code.


package com.lukekorth.httpebble;

import android.app.Activity;
import android.os.Bundle;

public class Httpebble extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
}

package com.lukekorth.httpebble;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;

public class Httpebble extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	@Override
	protected void onResume() {
		// Check that Google Play services is available
		int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

		// If Google Play services is unavailable
		if (ConnectionResult.SUCCESS != resultCode) {
			// Get the error dialog from Google Play services
			Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this, 0);

			// If Google Play services can provide an error dialog
			if (errorDialog != null) {
				// Create a new DialogFragment for the error dialog
				ErrorDialogFragment errorFragment = new ErrorDialogFragment();

				// Set the dialog in the DialogFragment
				errorFragment.setDialog(errorDialog);

				// Show the error dialog in the DialogFragment
				errorFragment.show(getSupportFragmentManager(), "Location Updates");
			}
		}
	}

	// Define a DialogFragment that displays the error dialog
	public static class ErrorDialogFragment extends DialogFragment {

		// Global field to contain the error dialog
		private Dialog mDialog;

		// Default constructor. Sets the dialog field to null
		public ErrorDialogFragment() {
			super();
			mDialog = null;
		}

		// Set the dialog to display
		public void setDialog(Dialog dialog) {
			mDialog = dialog;
		}

		// Return a Dialog to the DialogFragment.
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			return mDialog;
		}
	}
}

Add check for Google Play services

Add check for Google Play services


import java.util.Map.Entry;

public class DegreeOfSeperation {

	public static void main(String[] args) {
		// TODO Implement
	}

}

class Vertex {

	public boolean isAdjacent() {
		// TODO Implement
		return false;
	}

	public Entry<Vertex, Integer>[] getNeighbors() {
		// TODO Implement
		return null;
	}
}

import java.util.Map.Entry;

public class DegreeOfSeperation {

	public static void main(String[] args) {
		// TODO Implement
	}

}

class Vertex {
	public static String INPUT_FILENAME = "facebook_combined.txt";
	private int id;
	private boolean initialized;
	private boolean visited;
	private double costFromStart;
	private Entry<Vertex, Integer>[] neighbors;

	public Vertex(int id) {
		this.id = id;
		this.initialized = false;
		this.visited = false;
		this.costFromStart = Double.POSITIVE_INFINITY;
	}

	public double getCostFromStart() {
		return costFromStart;
	}

	public boolean setCostFromStartIfSmaller(double newCost) {
		boolean setSuccess = false;
		if(newCost < costFromStart) {
			costFromStart = newCost;
		}
		return setSuccess;
	}

	public Entry<Vertex, Integer>[] getNeighbors() {
		// TODO Implement
		return null;
	}

}

Implement constructor, getCostFromStart(), setCostFromStartIfSmaller in Vertex


package dk.cmol.arduinorgb_controller;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class FaderFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_fader,
				container, false);

		return rootView;
	}
}

package dk.cmol.arduinorgb_controller;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.NumberPicker;

public class FaderFragment extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_fader, container,
				false);

		// Add min and max to number picker elements
		NumberPicker[] nps = {(NumberPicker) rootView.findViewById(R.id.numberPicker1),
				(NumberPicker) rootView.findViewById(R.id.numberPicker2),
				(NumberPicker) rootView.findViewById(R.id.numberPicker3)
		};

		for (int i = 0; i < nps.length; i++) {
			nps[i].setMaxValue(255);
			nps[i].setMinValue(0);
		}

		return rootView;
	}
}

Add value information to the numberPickers


// Copyright © 2011 - 2013 Forerunner Games
package com.forerunnergames.tools;

/**
 *
 * @author Aaron Mahan
 */
public class Point2D
{
  public Point2D (final int x, final int y)
  {
    x_ = x;
    y_ = y;
  }

  @Override
  public boolean equals (Object object)
  {
    if (this == object)
    {
      return true;
    }

    boolean equals = false;

    if (object != null && object.getClass() == getClass())
    {
      Point2D point2D = (Point2D) object;

      if (x_ == point2D.getX() && y_ == point2D.getY())
      {
        equals = true;
      }
    }

    return equals;
  }

  public int getX()
  {
    return x_;
  }

  public int getY()
  {
    return y_;
  }

  @Override
  public int hashCode()
  {
    int hash = 7;

    hash = 47 * hash + x_;
    hash = 47 * hash + y_;

    return hash;
  }

  @Override
  public String toString()
  {
    return String.format (getClass().getSimpleName() + ": (x: %1$6s, y: %2$6s)",
                          getX(), getY());
  }

  private final int x_;
  private final int y_;
}

// Copyright © 2011 - 2013 Forerunner Games
package com.forerunnergames.tools;

/**
 *
 * @author Aaron Mahan
 */
public class Point2D
{
  public Point2D (final int x, final int y)
  {
    x_ = x;
    y_ = y;
  }

  @Override
  public boolean equals (Object object)
  {
    if (this == object)
    {
      return true;
    }

    boolean equals = false;

    if (object != null && object.getClass() == getClass())
    {
      Point2D point = (Point2D) object;

      if (x_ == point.getX() && y_ == point.getY())
      {
        equals = true;
      }
    }

    return equals;
  }

  public int getX()
  {
    return x_;
  }

  public int getY()
  {
    return y_;
  }

  @Override
  public int hashCode()
  {
    int hash = 7;

    hash = 47 * hash + x_;
    hash = 47 * hash + y_;

    return hash;
  }

  @Override
  public String toString()
  {
    return String.format (getClass().getSimpleName() + ": (x: %1$6s, y: %2$6s)",
                          getX(), getY());
  }

  private final int x_;
  private final int y_;
}

Make local variable name more concise.

Make local variable name more concise.


/*
 * Copyright 2014 Taylor Caldwell
 *
 * 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 net.rithms.riot.constant;

public enum GameMode {
	ARAM("ARAM"),
	ASCENSION("Ascension"),
	CLASSIC("Classic"),
	FIRSTBLOOD("Snowdown Showdown"),
	KINGPORO("King Poro"),
	ODIN("Dominion/Crystal Scar"),
	ONEFORALL("One for All"),
	TUTORIAL("Tutorial");

	private String name;

	GameMode(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

/*
 * Copyright 2014 Taylor Caldwell
 *
 * 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 net.rithms.riot.constant;

public enum GameMode {
	ARAM("ARAM"),
	ASCENSION("Ascension"),
	CLASSIC("Classic"),
	FIRSTBLOOD("Snowdown Showdown"),
	KINGPORO("King Poro"),
	ODIN("Dominion/Crystal Scar"),
	ONEFORALL("One for All"),
	SIEGE("Nexus Siege"),
	TUTORIAL("Tutorial");

	private String name;

	GameMode(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

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

Add Nexus Siege game mode

Add Nexus Siege game mode


package com.algorithms.tree;

public class BST<Key extends Comparable<Key>, Value> {
}

package com.algorithms.tree;

public class BST<Key extends Comparable<Key>, Value> {

    private Node root;

    private class Node {
        private Key key;
        private Value val;
        private Node left, right;
        public Node(Key key, Value val) {
            this.key = key;
            this.val = val;
        }
    }

    public void put(Key key, Value val) {}

    public Value get(Key key) {}

    public void delete(Key key) {}

    public Iterable<Key> iterator() {}
}

Create Node class and other skeleton code


public class Node {

  Node next = null;
  int data;

  public Node(int d) {
    data = d;
  }

  // Appends data to the end of the linked list
  private void appendToTail(int data) {

    Node curr = this;
    Node end = new Node(data);

    while(curr.next != null) {
      curr = curr.next;
    }

    curr.next = end;
  }

  // Iterate through the linked list
  private void traverseList() {
  }

  // Delete the node from linked list n with data
  private void delete(Node n, int data) {
  }

  // Example
  public static void main(String[] args) {

    Node head = new Node(10);

  }

}

public class Node {

  Node next = null;
  int data;

  public Node(int d) {
    data = d;
  }

  // Appends data to the end of the linked list
  private void appendToTail(int data) {

    Node curr = this;
    Node end = new Node(data);

    while(curr.next != null) {
      curr = curr.next;
    }

    curr.next = end;
  }

  // Iterate through the linked list
  private void traverseList() {
  }

  // Delete the node from linked list n with data
  private void delete(Node n, int data) {
  }

  // Find the median element in the linked list
  private void findMedianElement() {
  }

  // Example
  public static void main(String[] args) {

    Node head = new Node(10);

  }

}

Add median element function declaration.


package com.max.soundboard;

import java.io.File;
import java.util.ArrayList;

class FileManager {
    private FileManager() {}

    public static ArrayList<String> getSubdirectories(String path) {
        ArrayList<String> subdirectories = new ArrayList<>();
        File[] files = new File(path).listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    subdirectories.add(file.getName());
                }
            }
        }
        return subdirectories;
    }

    public static ArrayList<String> getSoundFileNames(String path) {
        ArrayList<String> soundFiles = new ArrayList<>();

        for (File file : new File(path).listFiles()) {
            if (file.isFile() && isSoundFileName(file.getName())) {
                soundFiles.add(file.getName());
            }
        }
        return soundFiles;
    }

    private static boolean isSoundFileName(String filename) {
        return filename.endsWith(".mp3") || filename.endsWith(".wav");
    }
}

package com.max.soundboard;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

class FileManager {
    private FileManager() {
    }

    public static List<String> getSubdirectories(String path) {
        List<String> subdirectories = new ArrayList<>();

        for (File file : new File(path).listFiles()) {
            if (file.isDirectory()) {
                subdirectories.add(file.getName());
            }
        }
        return subdirectories;
    }

    public static List<String> getSoundFileNames(String path) {
        List<String> soundFiles = new ArrayList<>();

        for (File file : new File(path).listFiles()) {
            if (file.isFile() && isSoundFileName(file.getName())) {
                soundFiles.add(file.getName());
            }
        }
        return soundFiles;
    }

    private static boolean isSoundFileName(String filename) {
        return filename.endsWith(".mp3") || filename.endsWith(".wav");
    }
}

Use generic types in Filemanager

Use generic types in Filemanager


package uk.co.craigwarren.gascalc.model;

public class Cylinder {

	private double volume;
	private double pressure;
	private Gas gas;
	private double ambientTemperatureKelvin;

	public double getVolume() {
		return volume;
	}
	public void setVolume(double volume) {
		this.volume = volume;
	}
	public double getPressure() {
		return pressure;
	}
	public void setPressure(double pressure) {
		this.pressure = pressure;
	}
	public Gas getGas() {
		return gas;
	}
	public void setGas(Gas gas) {
		this.gas = gas;
	}

	public Cylinder(double volume, double pressure, Gas gas) {
		this.volume = volume;
		this.pressure = pressure;
		this.gas = gas;
	}

	public Cylinder(double volume, double pressure) {
		this(volume, pressure, Gas.air());
	}

	public Cylinder(double volume) {
		this(volume, 0);
	}
    public double getAmbientTemperatureKelvin() {
        return ambientTemperatureKelvin;
    }
    public void setAmbientTemperatureKelvin(double ambientTemperatureKelvin) {
        this.ambientTemperatureKelvin = ambientTemperatureKelvin;
    }

}

package uk.co.craigwarren.gascalc.model;

public class Cylinder {

	private double volume;
	private double pressure;
	private Gas gas;
	private double ambientTemperatureKelvin;

	public double getVolume() {
		return volume;
	}
	public void setVolume(double volume) {
		this.volume = volume;
	}
	public double getPressure() {
		return pressure;
	}
	public void setPressure(double pressure) {
		this.pressure = pressure;
	}
	public Gas getGas() {
		return gas;
	}
	public void setGas(Gas gas) {
		this.gas = gas;
	}

	public Cylinder(double volume, double pressure, Gas gas, double tempKelvin) {
	    if(tempKelvin == 0.0) {
	        throw new IllegalArgumentException("Cannot mix gas at absolute zero");
	    }
		this.volume = volume;
		this.pressure = pressure;
		this.gas = gas;
		this.ambientTemperatureKelvin = tempKelvin;
	}

	public Cylinder(double volume, double pressure) {
		this(volume, pressure, Gas.air(), 20.0);
	}

	public Cylinder(double volume) {
		this(volume, 0);
	}
    public double getAmbientTemperatureKelvin() {
        return ambientTemperatureKelvin;
    }
    public void setAmbientTemperatureKelvin(double ambientTemperatureKelvin) {
        this.ambientTemperatureKelvin = ambientTemperatureKelvin;
    }

}

Add temperature to cylinder constructor

Add temperature to cylinder constructor


package bj.pranie.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by noon on 13.10.16.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/", "/week", "/lastweek", "/wm", "/user/registration", "/user/restore", "/images/*", "/js/*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }
}

package bj.pranie.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Created by noon on 13.10.16.
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/", "/week" ,"/week/*", "/wm/*", "/user/registration", "/user/restore", "/images/*", "/js/*").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER");
    }
}

Update permited path to all users.

Update permited path to all users.