/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//

package javax.persistence;

public interface TupleElement<X> {
    Class<? extends X> getJavaType();

    String getAlias();
}

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//

package javax.persistence;

public interface TupleElement<X> {
    Class<X> getJavaType();

    String getAlias();
}

Revert last JPA EA7 change per Jeremy/Panaki for further testing


package com.amalgam.view;

import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public final class ViewUtils {
    private ViewUtils() {}

    /**
     * Convert the dips to pixels, based on density scale
     *
     * @param resources application resources
     * @param dip to be converted value
     * @return converted value(px)
     */
    public static int dipToPixel(Resources resources, int dip) {
        final float scale = resources.getDisplayMetrics().density;
        // add 0.5f to round the figure up to the nearest whole number
        return (int) (dip * scale + 0.5f);
    }

    /**
     * Convert the pixels to dips, based on density scale
     * @param windowManager the window manager of the display to use the scale density of
     * @param pixel
     * @return converted value(dip)
     */
    public static float pixelToDip(WindowManager windowManager, int pixel) {
        float dip = 0;
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        dip = metrics.scaledDensity * pixel;
        return dip;
    }
}

package com.amalgam.view;

import android.content.Context;
import android.content.res.Resources;
import android.hardware.display.DisplayManager;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.amalgam.content.ContextUtils;

public final class ViewUtils {
    private ViewUtils() {}

    public static int dipToPixel(Context context, int dip) {
        return dipToPixel(context.getResources(), dip);
    }

    /**
     * Convert the dips to pixels, based on density scale
     *
     * @param resources application resources
     * @param dip to be converted value
     * @return converted value(px)
     */
    public static int dipToPixel(Resources resources, int dip) {
        final float scale = resources.getDisplayMetrics().density;
        // add 0.5f to round the figure up to the nearest whole number
        return (int) (dip * scale + 0.5f);
    }

    public static float pixelToDip(Context context, int pixel) {
        return pixelToDip(ContextUtils.getWindowManager(context), pixel);
    }

    /**
     * Convert the pixels to dips, based on density scale
     * @param windowManager the window manager of the display to use the scale density of
     * @param pixel
     * @return converted value(dip)
     */
    public static float pixelToDip(WindowManager windowManager, int pixel) {
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.scaledDensity * pixel;
    }

    public static float sipToPixel(Context context, float sip) {
        return sipToPixel(context.getResources(), sip);
    }

    public static float sipToPixel(Resources resources, float sip) {
        float density = resources.getDisplayMetrics().scaledDensity;
        return sip * density;
    }

    public static float pixelToSip(Context context, float pixels) {
        DisplayMetrics metrics = new DisplayMetrics();
        float scaledDensity = metrics.scaledDensity;
        if (pixels == 0 || scaledDensity == 0) {
            return 1;
        }
        return pixels/scaledDensity;
    }
}

Add sip to pixel conversion


package org.sagebionetworks.dashboard;

import javax.annotation.Resource;

import org.sagebionetworks.dashboard.service.BridgeDynamoImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Schedules the work of importing Bridge data into data warehouse.
 */
@Component("bridgeScheduler")
public final class BridgeScheduler {

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

    @Resource
    private BridgeDynamoImporter bridgeDynamoImporter;

    /**
     * 12 pm UTC or 5 am PDT.  Make sure this happens after daily backup is done.
     */
    @Scheduled(cron="00 55 * * * *", zone="UTC")
    public void run() {
        logger.info("Begin importing Bridge DynamoDB tables to Redshift.");
        bridgeDynamoImporter.run();
        logger.info("Finished importing Bridge DynamoDB tables to Redshift.");
    }
}

package org.sagebionetworks.dashboard;

import javax.annotation.Resource;

import org.sagebionetworks.dashboard.service.BridgeDynamoImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Schedules the work of importing Bridge data into data warehouse.
 */
@Component("bridgeScheduler")
public final class BridgeScheduler {

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

    @Resource
    private BridgeDynamoImporter bridgeDynamoImporter;

    /**
     * 12 pm UTC or 5 am PDT.  Make sure this happens after daily backup is done.
     */
    @Scheduled(cron="00 00 12 * * *", zone="UTC")
    public void run() {
        logger.info("Begin importing Bridge DynamoDB tables to Redshift.");
        bridgeDynamoImporter.run();
        logger.info("Finished importing Bridge DynamoDB tables to Redshift.");
    }
}

Change back Bridge scheduler to 12 pm daily


package com.example.myapplication;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Add f2

    }
}

package com.example.myapplication;

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

public class MainActivity extends AppCompatActivity {

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

    }
}

Rebase interactive rebase in progress; onto d2cd27f


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * 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.jboss.as.quickstarts.greeter;

import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class Resources {

    // Expose an entity manager using the resource producer pattern
    @SuppressWarnings("unused")
    @PersistenceContext
    @Produces
    private EntityManager em;

    @Produces
    public Logger getLogger(InjectionPoint ip) {
        String category = ip.getMember().getDeclaringClass().getName();
        return Logger.getLogger(category);
    }

    @Produces
    @RequestScoped
    public FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

}

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
 * contributors by the @authors tag. See the copyright.txt in the
 * distribution for a full listing of individual contributors.
 *
 * 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.jboss.as.quickstarts.greeter;

import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class Resources {

    // Expose an entity manager using the resource producer pattern
    @PersistenceContext
    @Produces
    private EntityManager em;

    @Produces
    public Logger getLogger(InjectionPoint ip) {
        String category = ip.getMember().getDeclaringClass().getName();
        return Logger.getLogger(category);
    }

    @Produces
    @RequestScoped
    public FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

}

Fix JBDS import errors for greeter quickstart


package edu.northwestern.bioinformatics.studycalendar.domain.delta;

import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;

import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
import javax.persistence.Column;
import java.util.Set;

import org.hibernate.validator.NotNull;

/**
 * @author Rhett Sutphin
 */
@Entity // TODO
@DiscriminatorValue("add")
public class Add extends Change {
    private Integer newChildId;
    private Integer index;

    @Override
    @Transient
    public ChangeAction getAction() { return ChangeAction.ADD; }

    ////// BEAN PROPERTIES

    @Column (name = "new_value")
    public Integer getNewChildId() {
        return newChildId;
    }

    public void setNewChildId(Integer newChildId) {
        this.newChildId = newChildId;
    }

    @Column (name = "attribute")
    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(getClass().getSimpleName())
            .append("[id=").append(getId()).append("; child id ").append(getNewChildId());
        if (getIndex() != null) {
            sb.append(" at index ").append(getIndex());
        }
        return sb.append(']').toString();
    }
}

package edu.northwestern.bioinformatics.studycalendar.domain.delta;

import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;

import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
import javax.persistence.Column;
import java.util.Set;

import org.hibernate.validator.NotNull;

/**
 * @author Rhett Sutphin
 */
@Entity
@DiscriminatorValue("add")
public class Add extends Change {
    private Integer newChildId;
    private Integer index;

    @Override
    @Transient
    public ChangeAction getAction() { return ChangeAction.ADD; }

    ////// BEAN PROPERTIES

    @Column (name = "new_value")
    public Integer getNewChildId() {
        return newChildId;
    }

    public void setNewChildId(Integer newChildId) {
        this.newChildId = newChildId;
    }

    @Column (name = "attribute")
    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(getClass().getSimpleName())
            .append("[id=").append(getId()).append("; child id ").append(getNewChildId());
        if (getIndex() != null) {
            sb.append(" at index ").append(getIndex());
        }
        return sb.append(']').toString();
    }
}

Remove TODO for done thing


package org.realityforge.replicant.client;

/**
 * Interface implemented by imitations that need to be linked.
 */
public interface Linkable
{
  void link();

  void delink();
}

package org.realityforge.replicant.client;

/**
 * Interface implemented by imitations that need to be linked.
 */
public interface Linkable
{
  /**
   * Resolve any references to related entities.
   */
  void link();

  /**
   * Remove direct references to related entities and mark as unresolved.
   */
  void delink();
}

Add some basic javadoc documentation


package org.michaelbel.bottomsheet.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Date: Sut, Mar 3 2018
 * Time: 20:09 MSK
 *
 * @author Michael Bel
 */

@Retention(RetentionPolicy.CLASS)
@Target({
        ElementType.ANNOTATION_TYPE,
        ElementType.CONSTRUCTOR,
        ElementType.FIELD,
        ElementType.METHOD,
        ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {}

package org.michaelbel.bottomsheet.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Date: Sut, Mar 3 2018
 * Time: 20:09 MSK
 *
 * @author Michael Bel
 */

@Retention(RetentionPolicy.SOURCE)
@Target({
        ElementType.ANNOTATION_TYPE,
        ElementType.CONSTRUCTOR,
        ElementType.FIELD,
        ElementType.METHOD,
        ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {
    String version();
}

Update retention policy and add version field


package wumpus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

import wumpus.Environment.*;

/**
 * The iteration of plays that the player can take until reaches its end.
 */
public class Runner implements Iterable<Player>, Iterator<Player> {
    private static final int DEFAULT_MAX_ITERATIONS = 200;

    private final World world;
    private int iterations = 0;

    /**
     * The runner constructor.
     * @param world The world instance.
     */
    public Runner(World world) {
        this.world = world;
    }

    /**
     * Returns the iterator that can be user in a loop.
     * @return Itself
     */
    public Iterator<Player> iterator() {
        return this;
    }

    /**
     * Check if the game has ended.
     * @return
     */
    public boolean hasNext() {
        Player player = world.getPlayer();
        return iterations < DEFAULT_MAX_ITERATIONS &&
                player.isAlive() && player.getResult() != Result.WIN;
    }

    /**
     * Get player instance to calculate the next iteration.
     * @return The current player instance
     */
    public Player next() {
        if (!hasNext()) throw new NoSuchElementException();
        iterations++;
        return world.getPlayer();
    }

    /**
     * Operation not supported, throws an error.
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }

    /**
     * Get how many iterations have been made so far.
     * @return The amount of iterations
     */
    public int getDepth() {
        return iterations;
    }
}

package wumpus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

import wumpus.Environment.*;

/**
 * The iteration of plays that the player can take until reaches its end.
 */
public class Runner implements Iterable<Player>, Iterator<Player> {
    private static final int DEFAULT_MAX_ITERATIONS = 200;

    private final World world;
    private final String name;
    private int iterations = 0;

    /**
     * The runner constructor.
     * @param world The world instance.
     */
    public Runner(String name, World world) {
        this.name = name;
        this.world = world;
    }

    /**
     * Returns the iterator that can be user in a loop.
     * @return Itself
     */
    public Iterator<Player> iterator() {
        return this;
    }

    /**
     * Check if the game has ended.
     * @return
     */
    public boolean hasNext() {
        Player player = world.getPlayer();
        return iterations < DEFAULT_MAX_ITERATIONS &&
                player.isAlive() && player.getResult() != Result.WIN;
    }

    /**
     * Get player instance to calculate the next iteration.
     * @return The current player instance
     */
    public Player next() {
        if (!hasNext()) throw new NoSuchElementException();
        iterations++;
        return world.getPlayer();
    }

    /**
     * Operation not supported, throws an error.
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }

    /**
     * Get how many iterations have been made so far.
     * @return The amount of iterations
     */
    public int getDepth() {
        return iterations;
    }
}

Add a name to the runner


/*
 * IKToolExecutor.java
 *
 * Created on August 11, 2010, 12:38 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.opensim.tools.serializers;

import java.io.IOException;
import java.util.Observable;
import org.opensim.modeling.Model;
import org.opensim.tools.serializers.ToolExecutor.Operation;
import org.opensim.tracking.ForwardToolModel;
import org.opensim.tracking.ResultDisplayerInterface;

/**
 *
 * @author ayman
 */
public class ForwardToolExecutor extends ToolExecutor  {

    ForwardToolModel toolModel;

    /** Creates a new instance of IKToolExecutor */
    public ForwardToolExecutor(Model model, String setupFile, ResultDisplayerInterface displayer) throws IOException {
        super(model, setupFile);
        toolModel = new ForwardToolModel(model);
        toolModel.addResultDisplayer(displayer);
        //toolModel.loadSettings(setupFile);
        toolModel.addObserver(this);
    }

    public void execute() {
        toolModel.loadSettings(setupFile);
        toolModel.execute();
    }

    public void cancel() {
        toolModel.cancel();
    }

    public void update(Observable o, Object arg) {
          if (arg==ForwardToolModel.Operation.ExecutionStateChanged && !toolModel.isExecuting()){
             setChanged();
             notifyObservers(Operation.ExecutionFinished);
         }
    }

}

/*
 * IKToolExecutor.java
 *
 * Created on August 11, 2010, 12:38 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.opensim.tools.serializers;

import java.io.IOException;
import java.util.Observable;
import org.opensim.modeling.Model;
import org.opensim.tools.serializers.ToolExecutor.Operation;
import org.opensim.tracking.ForwardToolModel;
import org.opensim.tracking.ResultDisplayerInterface;

/**
 *
 * @author ayman
 */
public class ForwardToolExecutor extends ToolExecutor  {

    ForwardToolModel toolModel;

    /** Creates a new instance of IKToolExecutor */
    public ForwardToolExecutor(Model model, String setupFile, ResultDisplayerInterface displayer) throws IOException {
        super(model, setupFile);
        toolModel = new ForwardToolModel(model);
        toolModel.addResultDisplayer(displayer);
        //toolModel.loadSettings(setupFile);
        toolModel.addObserver(this);
    }

    public void execute() {
        toolModel.loadSettings(setupFile);
        toolModel.execute();
    }

    public void cancel() {
        toolModel.interrupt(true);
    }

    public void update(Observable o, Object arg) {
          if (arg==ForwardToolModel.Operation.ExecutionStateChanged && !toolModel.isExecuting()){
             setChanged();
             notifyObservers(Operation.ExecutionFinished);
         }
    }

}

Make stop button from custom gui keep partial results


package sk.tuke.cloud.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * @author Dominik Matta
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final PublicKeyProvider publicKeyProvider;

    @Autowired
    public SecurityConfiguration(PublicKeyProvider publicKeyProvider) {
        this.publicKeyProvider = publicKeyProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .apply(new JWTConfigurer(publicKeyProvider));
    }
}

package sk.tuke.cloud.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * @author Dominik Matta
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final PublicKeyProvider publicKeyProvider;

    @Autowired
    public SecurityConfiguration(PublicKeyProvider publicKeyProvider) {
        this.publicKeyProvider = publicKeyProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
                .authorizeRequests()
                .anyRequest().authenticated()
        .and()
                .apply(new JWTConfigurer(publicKeyProvider));
        // @formatter:on
    }
}

Disable code formatting in security configuration region


/*
 * See LICENSE file in distribution for copyright and licensing information.
 */
package ioke.lang;

import java.util.IdentityHashMap;

/**
 *
 * @author Ola Bini
 */
public class Context extends IokeObject {
    IokeObject ground;

    public IokeObject message;
    public IokeObject surroundingContext;

    public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
        super(runtime, documentation);
        this.ground = ground.getRealContext();
        this.message = message;
        this.surroundingContext = surroundingContext;

        if(runtime.context != null) {
            this.mimics(runtime.context);
        }

        setCell("self", getRealContext());
    }

    public void init() {
    }

    public IokeObject getRealContext() {
        return ground;
    }

    public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
        IokeObject nn = super.findCell(m, context, name, visited);

        if(nn == runtime.nul) {
            return ground.findCell(m, context, name, visited);
        } else {
            return nn;
        }
    }

    @Override
    public String toString() {
        return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
    }
}// Context

/*
 * See LICENSE file in distribution for copyright and licensing information.
 */
package ioke.lang;

import java.util.IdentityHashMap;

/**
 *
 * @author Ola Bini
 */
public class Context extends IokeObject {
    IokeObject ground;

    public IokeObject message;
    public IokeObject surroundingContext;

    public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
        super(runtime, documentation);
        this.ground = ground.getRealContext();
        this.message = message;
        this.surroundingContext = surroundingContext;

        if(runtime.context != null) {
            this.mimics(runtime.context);
        }

        setCell("self", getRealContext());
    }

    public void init() {
        setKind("Context");
    }

    public IokeObject getRealContext() {
        return ground;
    }

    public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
        IokeObject nn = super.findCell(m, context, name, visited);

        if(nn == runtime.nul) {
            return ground.findCell(m, context, name, visited);
        } else {
            return nn;
        }
    }

    @Override
    public String toString() {
        return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
    }
}// Context

Complete refactoring, including addition of kind to all core objects


package backupBasic.backup;
/*(c)2016, Tobias Hotz
 * Further Information can be found in Info.txt
 */

import backupBasic.util.i18n;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Logger;

/**
 * @author Tobias Hotz
 */
public class Main implements Thread.UncaughtExceptionHandler {

    private static final Logger logger = i18n.getLogger(Main.class);
	/**
	 * Verwaltet das Logging-System und gibt dann an den ArgParser ab
	 */
	public static void main(String[] args) {
		Thread.setDefaultUncaughtExceptionHandler(new Main());
        i18n.initLogging();
        ArgParser.parseArgs(args);
	}

	@Override
	public void uncaughtException(Thread t, Throwable e) {
		logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:");
		e.printStackTrace();
		if(!GraphicsEnvironment.isHeadless()) {
			JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") + "\n" + i18n.translate("Error") + ": "+ e +"\n" +  i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE);
		}
		System.exit(-1);
	}
}

package backupBasic.backup;
/*(c)2016, Tobias Hotz
 * Further Information can be found in Info.txt
 */

import backupBasic.util.i18n;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Logger;

/**
 * @author Tobias Hotz
 */
public class Main implements Thread.UncaughtExceptionHandler {
    private static final Logger logger = i18n.getLogger(Main.class);

	/**
	 * Verwaltet das Logging-System und gibt dann an den ArgParser ab
	 */
	public static void main(String[] args) {
		Thread.setDefaultUncaughtExceptionHandler(new Main());
        i18n.initLogging();
        ArgParser.parseArgs(args);
	}

	@Override
	public void uncaughtException(Thread t, Throwable e) {
	    try {
            logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:");
            e.printStackTrace();
            if(!GraphicsEnvironment.isHeadless())
                JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") +
                        "\n" + i18n.translate("Error") + ": " + e + "\n" + i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE);
            } catch(Exception e2) {
	            e.printStackTrace();
	            System.err.println("Errors while printing Error:");
	            e2.printStackTrace();
	            if(!GraphicsEnvironment.isHeadless())
	            JOptionPane.showMessageDialog(null, "An fatal error occurred, and the program crashed." +
                        "\nIn addition to that, it failed to translate this Message", "ERROR", JOptionPane.ERROR_MESSAGE);
            }
		System.exit(-1);
	}
}

Fix crash when showing crash information


package com.faforever.api.db;

import com.faforever.api.config.ApplicationProfile;
import org.springframework.context.annotation.Profile;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Component
@Profile(ApplicationProfile.PRODUCTION)
public class SchemaVersionVerifier implements PriorityOrdered {

  private static final String DB_COMPATIBILITY_VERSION = "35";

  private final SchemaVersionRepository schemaVersionRepository;

  public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository) {
    this.schemaVersionRepository = schemaVersionRepository;
  }

  @PostConstruct
  public void postConstruct() {
    String maxVersion = schemaVersionRepository.findMaxVersion()
      .orElseThrow(() -> new IllegalStateException("No database version is available"));

    Assert.state(Objects.equals(DB_COMPATIBILITY_VERSION, maxVersion),
      String.format("Database version is '%s' but this software requires '%s'", maxVersion, DB_COMPATIBILITY_VERSION));
  }

  @Override
  public int getOrder() {
    return HIGHEST_PRECEDENCE;
  }
}

package com.faforever.api.db;

import com.faforever.api.config.ApplicationProfile;
import org.springframework.context.annotation.Profile;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Component
@Profile(ApplicationProfile.PRODUCTION)
public class SchemaVersionVerifier implements PriorityOrdered {

  private static final String DB_COMPATIBILITY_VERSION = "43";

  private final SchemaVersionRepository schemaVersionRepository;

  public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository) {
    this.schemaVersionRepository = schemaVersionRepository;
  }

  @PostConstruct
  public void postConstruct() {
    String maxVersion = schemaVersionRepository.findMaxVersion()
      .orElseThrow(() -> new IllegalStateException("No database version is available"));

    Assert.state(Objects.equals(DB_COMPATIBILITY_VERSION, maxVersion),
      String.format("Database version is '%s' but this software requires '%s'", maxVersion, DB_COMPATIBILITY_VERSION));
  }

  @Override
  public int getOrder() {
    return HIGHEST_PRECEDENCE;
  }
}

Update required DB version to v43


package com.telecomsys.cmc.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;

/**
 * The schedule message model which encapsulates the request and response sent when the client requests details about a
 * scheduled message.
 */
@JsonRootName("schedulemessage")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder(alphabetic = true)
public class ScheduleMessage {

    /**
     * Message id of the scheduled message.
     */
    @JsonProperty("messageID")
    private Long messageId;

    /**
     * Message data.
     */
    private Message message;

    /**
     * Schedule data.
     */
    private Schedule schedule;

    /**
     * @return the messageId
     */
    public Long getMessageId() {
        return messageId;
    }

    /**
     * @param messageId the messageId to set
     */
    public void setMessageId(Long messageId) {
        this.messageId = messageId;
    }

    /**
     * @return the schedule
     */
    public Schedule getSchedule() {
        return schedule;
    }

    /**
     * @param schedule the schedule to set
     */
    public void setSchedule(Schedule schedule) {
        this.schedule = schedule;
    }

    /**
     * @return the message
     */
    public Message getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(Message message) {
        this.message = message;
    }
}

package com.telecomsys.cmc.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;

/**
 * The schedule message model which encapsulates the request and response sent when the client requests details about a
 * scheduled message.
 */
@JsonRootName("schedulemessage")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ScheduleMessage {

    /**
     * Message id of the scheduled message.
     */
    @JsonProperty("messageID")
    private Long messageId;

    /**
     * Message data.
     */
    private Message message;

    /**
     * Schedule data.
     */
    private Schedule schedule;

    /**
     * @return the messageId
     */
    public Long getMessageId() {
        return messageId;
    }

    /**
     * @param messageId the messageId to set
     */
    public void setMessageId(Long messageId) {
        this.messageId = messageId;
    }

    /**
     * @return the schedule
     */
    public Schedule getSchedule() {
        return schedule;
    }

    /**
     * @param schedule the schedule to set
     */
    public void setSchedule(Schedule schedule) {
        this.schedule = schedule;
    }

    /**
     * @return the message
     */
    public Message getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(Message message) {
        this.message = message;
    }
}

Remove order as the tests are independent of the order.


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.type.algebra;

public interface Infinite<T> {
	boolean isNaN(T a);
	boolean isInfinite(T a);
	// positive or negative can be determined with signum() for Ordered groups.
	// Complex has no concept of pos inf and neg inf.
}

Add missing license header to an interface


package pokefenn.totemic.apiimpl.totem;

import pokefenn.totemic.api.totem.TotemEffect;
import pokefenn.totemic.api.totem.TotemEffectAPI;
import pokefenn.totemic.api.totem.TotemEffectContext;

public enum TotemEffectApiImpl implements TotemEffectAPI {
    INSTANCE;

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, TotemEffectContext context) {
        return getDefaultRange(effect, DEFAULT_BASE_RANGE, repetition, context);
    }

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, int baseRange, TotemEffectContext context) {
        return baseRange + context.getTotemEffectMusic() / 32 + (context.getPoleSize() >= TotemEffectAPI.MAX_POLE_SIZE ? 1 : 0);
    }
}

package pokefenn.totemic.apiimpl.totem;

import pokefenn.totemic.api.totem.TotemEffect;
import pokefenn.totemic.api.totem.TotemEffectAPI;
import pokefenn.totemic.api.totem.TotemEffectContext;

public enum TotemEffectApiImpl implements TotemEffectAPI {
    INSTANCE;

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, TotemEffectContext context) {
        return getDefaultRange(effect, repetition, DEFAULT_BASE_RANGE, context);
    }

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, int baseRange, TotemEffectContext context) {
        return baseRange + context.getTotemEffectMusic() / 32 + (context.getPoleSize() >= TotemEffectAPI.MAX_POLE_SIZE ? 1 : 0);
    }
}

Fix getDefaultRange, wrong order of parameters


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blazzify.jasonium.ui;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;

/**
 *
 * @author Azzuwan Aziz <azzuwan@gmail.com>
 */
public class ServerTreeContextMenu extends ContextMenu {

    MenuItem connect = new MenuItem("Connect");
    MenuItem disconnect = new MenuItem("Disconnect");
    MenuItem remove = new MenuItem("Remove");

    public ServerTreeContextMenu() {
        connect.setOnAction((event) -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK);
        });
        disconnect.setOnAction((event) -> {
        });
        remove.setOnAction((event) -> {
        });
        this.getItems().addAll(connect, disconnect, remove);
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blazzify.jasonium.ui;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;

/**
 *
 * @author Azzuwan Aziz <azzuwan@gmail.com>
 */
public class ServerTreeContextMenu extends ContextMenu {

    MenuItem connect = new MenuItem("Connect");
    MenuItem disconnect = new MenuItem("Disconnect");
    MenuItem remove = new MenuItem("Remove");

    public ServerTreeContextMenu() {
        connect.setOnAction((event) -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK);
            alert.showAndWait();
        });
        disconnect.setOnAction((event) -> {
        });
        remove.setOnAction((event) -> {
        });
        this.getItems().addAll(connect, disconnect, remove);
    }

}

Refactor server tree context menu into it's own component


package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.synth.SynthLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testSynthLookAndFeel() {
        LookAndFeel plaf = new SynthLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testMetalLookAndFeel() {
        LookAndFeel plaf = new MetalLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

Use L&F that is available on JDK 1.3


/*
 * Copyright 2017, Google 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 io.opencensus.trace.unsafe;

import io.grpc.Context;
import io.opencensus.trace.Span;

/**
 * Util methods/functionality to interact with the {@link io.grpc.Context}.
 *
 * <p>Users must interact with the current Context via the public APIs in {@link
 * io.opencensus.trace.Tracer} and avoid usages of the {@link #CONTEXT_SPAN_KEY} directly.
 */
public final class ContextUtils {
  // No instance of this class.
  private ContextUtils() {}

  /** The {@link io.grpc.Context.Key} used to interact with {@link io.grpc.Context}. */
  public static final Context.Key<Span> CONTEXT_SPAN_KEY = Context.key("instrumentation-trace-key");
}

/*
 * Copyright 2017, Google 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 io.opencensus.trace.unsafe;

import io.grpc.Context;
import io.opencensus.trace.Span;

/**
 * Util methods/functionality to interact with the {@link io.grpc.Context}.
 *
 * <p>Users must interact with the current Context via the public APIs in {@link
 * io.opencensus.trace.Tracer} and avoid usages of the {@link #CONTEXT_SPAN_KEY} directly.
 */
public final class ContextUtils {
  // No instance of this class.
  private ContextUtils() {}

  /** The {@link io.grpc.Context.Key} used to interact with {@link io.grpc.Context}. */
  public static final Context.Key<Span> CONTEXT_SPAN_KEY = Context.key("opencensus-trace-span-key");
}

Rename trace io.grpc.Context key to opencensus-trace-span-key.


// Copyright 2017 Google 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 codeu.chat;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public final class TestRunner {
  public static void main(String[] args) {
     final Result result =
         JUnitCore.runClasses(
             codeu.chat.common.SecretTest.class,
             codeu.chat.relay.ServerTest.class,
             codeu.chat.server.BasicControllerTest.class,
             codeu.chat.server.RawControllerTest.class,
             codeu.chat.util.TimeTest.class,
             codeu.chat.util.UuidTest.class,
             codeu.chat.util.store.StoreTest.class
         );
      for (final Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

// Copyright 2017 Google 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 codeu.chat;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public final class TestRunner {
  public static void main(String[] args) {
     final Result result =
         JUnitCore.runClasses(
             codeu.chat.common.SecretTest.class,
             codeu.chat.relay.ServerTest.class,
             codeu.chat.server.BasicControllerTest.class,
             codeu.chat.server.RawControllerTest.class,
             codeu.chat.util.TimeTest.class,
             codeu.chat.util.UuidTest.class,
             codeu.chat.util.store.StoreTest.class,
             codeu.chat.util.TokenizerTest.class
         );
      for (final Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

Add TokenizerTest to the list of tests to run


package uk.gov.dvla.services.enquiry;

import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;

public interface DriverEnquiry extends ManagedService
{
    public static final String DRIVER_URI = "/driver/";
    public static final String CUSTOMER_PORTAL = "customer_portal";
    public static final String MIB = "mib";

    public static final String DLN_PARAM = "dln";
    public static final String ENQUIRY_ID_PARAM = "id";

    public static final String FORENAME_PARAM = "fn";
    public static final String SURNAME_PARAM = "sn";
    public static final String DOB_PARAM = "d";
    public static final String GENDER_PARAM = "g";
    public static final String POSTCODE_PARAM = "p";

	public Driver get(String dln);

	public Driver get(Person person);

    public Driver get(String forename, String surname, String dob,
                      String gender, String postCode);
}

package uk.gov.dvla.services.enquiry;

import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;

public interface DriverEnquiry extends ManagedService
{
    public static final String DRIVER_URI = "/driver/";
    public static final String CUSTOMER_PORTAL = "customer.portal";
    public static final String MIB = "mib";

    public static final String DLN_PARAM = "dln";
    public static final String ENQUIRY_ID_PARAM = "id";

    public static final String FORENAME_PARAM = "fn";
    public static final String SURNAME_PARAM = "sn";
    public static final String DOB_PARAM = "d";
    public static final String GENDER_PARAM = "g";
    public static final String POSTCODE_PARAM = "p";

	public Driver get(String dln);

	public Driver get(Person person);

    public Driver get(String forename, String surname, String dob,
                      String gender, String postCode);
}

Determine the rules that are run matching the context passed into the rules with the package name. Include some more tests. Remove redundant logging classes.


package org.opencb.opencga.server;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by pfurio on 04/10/16.
 */
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("Request " + request.getMethod());

        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.addHeader("Access-Control-Allow-Methods","GET,POST");
        resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Range");

        // Just ACCEPT and REPLY OK if OPTIONS
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {}

}

package org.opencb.opencga.server;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by pfurio on 04/10/16.
 */
public class CORSFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("Request " + request.getMethod());

        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.addHeader("Access-Control-Allow-Methods","GET,POST");
        resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Range, Authorization");

        // Just ACCEPT and REPLY OK if OPTIONS
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {}

}

Add Authorization to Access-Control-Allow-Headers list.


package game_objects.interactions;

/**
 * Created by mtvarkovsky on 12/10/16.
 */
public interface IHide {
}

package com.seven.game.game_objects.interactions;

public interface IHide {
    Boolean possibleToHide();
}

Add interface for GameObjects to be able to hide


package alien4cloud.plugin.marathon.config;

import alien4cloud.ui.form.annotation.FormProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author Adrian Fraisse
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FormProperties({ "marathonURL", "mesosDNS" })
public class MarathonConfig {

    private String marathonURL;

    private String mesosDNS;
}

package alien4cloud.plugin.marathon.config;

import alien4cloud.ui.form.annotation.FormProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author Adrian Fraisse
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FormProperties({ "marathonURL" })
public class MarathonConfig {

    private String marathonURL;
}

Remove mesosDNS url from configuration


package com.sangdol.experiment.portableDb;

import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.h2.jdbcx.JdbcConnectionPool;

/**
 * @author hugh
 */
public class ViewApplication extends Application<ViewConfiguration>{
    public static void main(String[] args) throws Exception{
        new ViewApplication().run(args);
    }

    @Override
    public String getName() {
        return "User view";
    }

    @Override
    public void initialize(Bootstrap<ViewConfiguration> bootstrap) {}

    @Override
    public void run(ViewConfiguration configuration, Environment environment) throws ClassNotFoundException {
        final ViewTable viewTable = new ViewTable();
        final ViewSimpleQuery viewSimpleQuery = new ViewSimpleQuery(viewTable);
        final ViewBatchQuery viewBatchQuery = new ViewBatchQuery(viewTable);
        final JdbcConnectionPool cp = JdbcConnectionPool.create("jdbc:h2:./view", "sa", ""); // TODO move to config
        final ViewDao viewDao = new ViewDao(cp, viewSimpleQuery, viewBatchQuery);
        final ViewResource resource = new ViewResource(viewDao);

        environment.healthChecks().register("database", new DatabaseHealthCheck(cp));
        environment.jersey().register(resource);
    }
}

package com.sangdol.experiment.portableDb;

import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.h2.jdbcx.JdbcConnectionPool;

/**
 * @author hugh
 */
public class ViewApplication extends Application<ViewConfiguration>{
    public static void main(String[] args) throws Exception{
        new ViewApplication().run(args);
    }

    @Override
    public String getName() {
        return "User view";
    }

    @Override
    public void initialize(Bootstrap<ViewConfiguration> bootstrap) {}

    @Override
    public void run(ViewConfiguration configuration, Environment environment) throws ClassNotFoundException {
        final ViewTable viewTable = new ViewTable();
        final ViewSimpleQuery viewSimpleQuery = new ViewSimpleQuery(viewTable);
        final ViewBatchQuery viewBatchQuery = new ViewBatchQuery(viewTable);

        // AUTO_SERVER=TRUE enables Automatic Mixed Mode which allows access of multiple processes.
        // Refer to http://h2database.com/html/features.html#auto_mixed_mode
        final JdbcConnectionPool cp = JdbcConnectionPool.create("jdbc:h2:./view;AUTO_SERVER=TRUE", "sa", "");
        final ViewDao viewDao = new ViewDao(cp, viewSimpleQuery, viewBatchQuery);
        final ViewResource resource = new ViewResource(viewDao);

        environment.healthChecks().register("database", new DatabaseHealthCheck(cp));
        environment.jersey().register(resource);
    }
}

Add AUTO_SERVER=TRUE for multiple processes access to the same db file


package com.packtpublishing.tddjava.friendships;

import java.util.*;

public class Friendships {
    private final Map<String, List<String>> friendships = new HashMap<>();

    public void makeFriends(String person1, String person2) {
        addFriend(person1, person2);
        addFriend(person2, person1);
    }

    public List<String> getFriendsList(String person) {
        if (!friendships.containsKey(person)) {
            return Collections.emptyList();
        }
        return friendships.get(person);
    }

    public boolean areFriends(String person1, String person2) {
        return friendships.containsKey(person1)
                && friendships.get(person1).contains(person2);
    }

    private void addFriend(String person, String friend) {
        if (!friendships.containsKey(person)) {
            friendships.put(person, new ArrayList<String>());
        }
        List<String> friends = friendships.get(person);
        if (!friends.contains(friend)) {
            friends.add(friend);
        }
    }
}

package com.packtpublishing.tddjava.friendships;

import java.util.*;

public class Friendships {
    private final Map<String, List<String>> friendships = new HashMap<String, List<String>>();

    public void makeFriends(String person1, String person2) {
        addFriend(person1, person2);
        addFriend(person2, person1);
    }

    public List<String> getFriendsList(String person) {
        if (!friendships.containsKey(person)) {
            return Collections.emptyList();
        }
        return friendships.get(person);
    }

    public boolean areFriends(String person1, String person2) {
        return friendships.containsKey(person1)
                && friendships.get(person1).contains(person2);
    }

    private void addFriend(String person, String friend) {
        if (!friendships.containsKey(person)) {
            friendships.put(person, new ArrayList<String>());
        }
        List<String> friends = friendships.get(person);
        if (!friends.contains(friend)) {
            friends.add(friend);
        }
    }
}

Use generic type instead of diamond operator for Java 6 compatibility


package net.domesdaybook.automata.base;

import net.domesdaybook.automata.State;
import net.domesdaybook.automata.Transition;
import net.domesdaybook.automata.TransitionFactory;
import net.domesdaybook.matcher.bytes.ByteMatcher;

/**
 * @author Matt Palmer
 */
public class ByteMatcherTransitionFactory implements TransitionFactory<ByteMatcher, ByteMatcher>{

  public Transition<ByteMatcher> create(final ByteMatcher source,
                                        final boolean ignoreInversion,
                                        final State<ByteMatcher> toState) {
    return new ByteMatcherTransition(source, toState);
  }

}

package net.domesdaybook.automata.base;

import net.domesdaybook.automata.State;
import net.domesdaybook.automata.Transition;
import net.domesdaybook.automata.TransitionFactory;
import net.domesdaybook.matcher.bytes.ByteMatcher;

/**
 * @author Matt Palmer
 */
public class ByteMatcherTransitionFactory implements TransitionFactory<ByteMatcher, ByteMatcher>{

  public Transition<ByteMatcher> create(final ByteMatcher source,
                                        final boolean ignoreInversion,
                                        final State<ByteMatcher> toState) {
    return new ByteMatcherTransition<ByteMatcher>(source, toState);
  }

}

Fix use of raw type.


/*
 * Copyright 2019 StreamSets 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.streamsets.datacollector.config;

import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;

/**
 * Enum for representing possible Cluster Type
 */
@GenerateResourceBundle
public enum SparkClusterType implements Label {
  AZURE_HD_INSIGHT("Apache Spark for HDInsight"),
  DATABRICKS("Databricks"),
  EMR("EMR"),
  DATAPROC("Dataproc"),
  YARN("Hadoop YARN"),
  KUBERNETES("Kubernetes Cluster (advanced users only)"),
  LOCAL("None (local)"),
  STANDALONE_SPARK_CLUSTER("Spark Standalone Cluster"),
  SQL_SERVER_BIG_DATA_CLUSTER("SQL Server 2019 Big Data Cluster"),
  ;

  private final String label;

  SparkClusterType(String label) {
    this.label = label;
  }

  @Override
  public String getLabel() {
    return label;
  }
}

/*
 * Copyright 2019 StreamSets 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.streamsets.datacollector.config;

import com.streamsets.pipeline.api.GenerateResourceBundle;
import com.streamsets.pipeline.api.Label;

/**
 * Enum for representing possible Cluster Type
 */
@GenerateResourceBundle
public enum SparkClusterType implements Label {
  AZURE_HD_INSIGHT("Apache Spark for HDInsight"),
  DATABRICKS("Databricks"),
  EMR("EMR"),
  DATAPROC("Dataproc"),
  YARN("Hadoop YARN"),
  KUBERNETES("Kubernetes Cluster"),
  LOCAL("None (local)"),
  STANDALONE_SPARK_CLUSTER("Spark Standalone Cluster"),
  SQL_SERVER_BIG_DATA_CLUSTER("SQL Server 2019 Big Data Cluster"),
  ;

  private final String label;

  SparkClusterType(String label) {
    this.label = label;
  }

  @Override
  public String getLabel() {
    return label;
  }
}

Update label for kubernetes selection in Spark configuration


/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.io.testtools;

import java.io.*;

/**
 * Base class for testcases doing tests with files.
 */
public abstract class FileBasedTestCase  {

    private static volatile File testDir;

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static File getTestDirectory() {
        if (testDir == null) {
            testDir = new File("test/io/").getAbsoluteFile();
        }
        testDir.mkdirs();
        return testDir;
    }

}

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.commons.io.testtools;

import java.io.*;
import static org.junit.Assert.fail;

/**
 * Base class for testcases doing tests with files.
 */
public abstract class FileBasedTestCase  {

    private static volatile File testDir;

    @SuppressWarnings("ResultOfMethodCallIgnored")
    public static File getTestDirectory() {
        if (testDir == null) {
            testDir = new File("target/test_io/").getAbsoluteFile();
        }
        testDir.mkdirs();
        if (!testDir.isDirectory()) {
            fail("Could not create directory " + testDir);
        }
        return testDir;
    }

}

Use temporary dir that can be fully deleted


package io.teknek.topship;

import java.util.Map;

public class SimpleTermExtractor implements TermExtractor{

  @Override
  public Map<String, Long> extractScores(Shop shop) {
    // TODO Auto-generated method stub
    return null;
  }

}

package io.teknek.topship;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/** This is the bare bones thing that works logically but basically
 * produces nothing useful as it will count a the etc as terms */
public class SimpleTermExtractor implements TermExtractor{

  @Override
  public Map<String, Long> extractScores(Shop shop) {
    Map<String,Long> termScore = new HashMap<String,Long>();
    for (Item item: shop.getItems()){
      StringTokenizer st = new StringTokenizer(item.getTitle(), " .!,?");
      while (st.hasMoreTokens()){
        String token = st.nextToken();
        scoreTerm(token, termScore);
      }
      st = new StringTokenizer(item.getDescription(), " .!,?");
      while (st.hasMoreTokens()){
        String token = st.nextToken();
        scoreTerm(token, termScore);
      }
    }
    return termScore;
  }

  private static void scoreTerm(String term, Map<String,Long> termScore){
    term = term.toLowerCase();
    if (term.endsWith("'s")){
      term = term.replace("'s", "");
    }
    if (term.endsWith("’s")){
      term = term.replace("’s", "");
    }
    if (termScore.containsKey(term)){
      termScore.put(term, termScore.get(term) + 1L);
    } else {
      termScore.put(term, 1L);
    }
  }
}

Use basic tokenizer to extract words


package org.workcraft.types;

import java.util.LinkedHashMap;

public class LinkedTwoWayMap<S, T> extends GeneralTwoWayMap<S, T> {
    public LinkedTwoWayMap() {
        super(new LinkedHashMap<S, T>(), new LinkedHashMap<T, S>());
    }

}

package org.workcraft.types;

import java.util.LinkedHashMap;

public class LinkedTwoWayMap<S, T> extends GeneralTwoWayMap<S, T> {
    public LinkedTwoWayMap() {
        super(new LinkedHashMap<>(), new LinkedHashMap<>());
    }
}

Use implicit parameters for specialisation of generic class


package forager.client;

import java.io.IOException;

import galileo.net.ClientMessageRouter;
import galileo.net.GalileoMessage;
import galileo.net.MessageListener;
import galileo.net.NetworkDestination;

public class Forager implements MessageListener {

    private NetworkDestination overlord;
    private ClientMessageRouter messageRouter;
    private boolean once = false;

    public Forager(NetworkDestination overlord) {
        this.overlord = overlord;
    }

    public void start()
    throws IOException {
        messageRouter = new ClientMessageRouter();
        messageRouter.addListener(this);
        messageRouter.connectTo(overlord);

        /* Join the network */
    }

    @Override
    public void onConnect(NetworkDestination endpoint) {

    }

    @Override
    public void onDisconnect(NetworkDestination endpoint) {
        //TODO: auto reconnect
    }

    @Override
    public void onMessage(GalileoMessage message) {

    }

    public static void main(String[] args)
    throws IOException {
        if (args.length < 2) {
            System.out.println("Usage: forager.client.Forager <host> <port>");
            System.exit(1);
        }

        String host = args[0];
        int port = Integer.parseInt(args[1]);
        NetworkDestination overlord = new NetworkDestination(host, port);

        Forager forager = new Forager(overlord);
        forager.start();
    }
}

package forager.client;

import java.io.IOException;

import forager.events.JoinEvent;

import galileo.event.EventWrapper;
import galileo.net.ClientMessageRouter;
import galileo.net.GalileoMessage;
import galileo.net.MessageListener;
import galileo.net.NetworkDestination;

public class Forager implements MessageListener {

    private NetworkDestination overlord;
    private ClientMessageRouter messageRouter;

    public Forager(NetworkDestination overlord) {
        this.overlord = overlord;
    }

    public void start()
    throws IOException {
        messageRouter = new ClientMessageRouter();
        messageRouter.addListener(this);
        messageRouter.connectTo(overlord);

        /* Join the network */
        JoinEvent join = new JoinEvent();
        messageRouter.sendMessage(overlord, EventWrapper.wrap(join));
    }

    @Override
    public void onConnect(NetworkDestination endpoint) {

    }

    @Override
    public void onDisconnect(NetworkDestination endpoint) {
        //TODO: auto reconnect
    }

    @Override
    public void onMessage(GalileoMessage message) {

    }

    public static void main(String[] args)
    throws IOException {
        if (args.length < 2) {
            System.out.println("Usage: forager.client.Forager <host> <port>");
            System.exit(1);
        }

        String host = args[0];
        int port = Integer.parseInt(args[1]);
        NetworkDestination overlord = new NetworkDestination(host, port);

        Forager forager = new Forager(overlord);
        forager.start();
    }
}

Send join message on startup


/*
 * Aerospike Client - Java Library
 *
 * Copyright 2013 by Aerospike, Inc. All rights reserved.
 *
 * Availability of this source code to partners and customers includes
 * redistribution rights covered by individual contract. Please check your
 * contract for exact rights and responsibilities.
 */
package com.aerospike.client.async;

import com.aerospike.client.AerospikeException;
import com.aerospike.client.cluster.Node;
import com.aerospike.client.listener.RecordSequenceListener;
import com.aerospike.client.policy.ScanPolicy;

public final class AsyncScanExecutor extends AsyncMultiExecutor {
	private final RecordSequenceListener listener;

	public AsyncScanExecutor(
		AsyncCluster cluster,
		ScanPolicy policy,
		RecordSequenceListener listener,
		String namespace,
		String setName,
		String[] binNames
	) throws AerospikeException {
		this.listener = listener;

		Node[] nodes = cluster.getNodes();
		completedSize = nodes.length;

		for (Node node : nodes) {
			AsyncScan async = new AsyncScan(this, cluster, (AsyncNode)node, policy, listener, namespace, setName, binNames);
			async.execute();
		}
	}

	protected void onSuccess() {
		listener.onSuccess();
	}

	protected void onFailure(AerospikeException ae) {
		listener.onFailure(ae);
	}
}

/*
 * Aerospike Client - Java Library
 *
 * Copyright 2013 by Aerospike, Inc. All rights reserved.
 *
 * Availability of this source code to partners and customers includes
 * redistribution rights covered by individual contract. Please check your
 * contract for exact rights and responsibilities.
 */
package com.aerospike.client.async;

import com.aerospike.client.AerospikeException;
import com.aerospike.client.ResultCode;
import com.aerospike.client.cluster.Node;
import com.aerospike.client.listener.RecordSequenceListener;
import com.aerospike.client.policy.ScanPolicy;

public final class AsyncScanExecutor extends AsyncMultiExecutor {
	private final RecordSequenceListener listener;

	public AsyncScanExecutor(
		AsyncCluster cluster,
		ScanPolicy policy,
		RecordSequenceListener listener,
		String namespace,
		String setName,
		String[] binNames
	) throws AerospikeException {
		this.listener = listener;

		Node[] nodes = cluster.getNodes();
		if (nodes.length == 0) {
			throw new AerospikeException(ResultCode.SERVER_NOT_AVAILABLE, "Scan failed because cluster is empty.");
		}

		completedSize = nodes.length;

		for (Node node : nodes) {
			AsyncScan async = new AsyncScan(this, cluster, (AsyncNode)node, policy, listener, namespace, setName, binNames);
			async.execute();
		}
	}

	protected void onSuccess() {
		listener.onSuccess();
	}

	protected void onFailure(AerospikeException ae) {
		listener.onFailure(ae);
	}
}

Throw exception when running scan/query and the cluster is empty.


package pro.jtaylor.timetracker.core;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pro.jtaylor.timetracker.core.dao.TimeEntry;

import java.util.List;

@Component
public class Tracker {
    @Autowired
    private List<TimeEntry> entries;

    /**
     * Add Method
     * @param int add for entries
     */

    public void add(TimeEntry entry) {
        entries.add(entry);
    }

    /**
     * Remove Method
     * @param int remove for entries
     */

    public void remove(TimeEntry entry) {
        entries.remove(entry);
    }

    /**
     * Size Method
     * @param int size for entries
     */

    public int size() {
        return entries.size();
    }

    /**
     * Get Method
     * @param TimeEntry get for entries
     */

    public TimeEntry get(int index) {

        // boolean vaild = false;
        // if (vaild == true) {
        // whatever
        //
        return entries.get(index);
    }
}

Update line end and EOF for build fail


package de.static_interface.sinkcity;

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

public enum CitySettings {

    FIRE(0b0000_0001),
    MOBS(0b0000_0010),
    TNT_BUILD(0b0000_0100),
    TNT_EXPLODE(0b0000_1000),
    EXPLOSION(0b0001_0000);

    private int activatedPattern;

    private CitySettings(int activatedPattern) {
        this.activatedPattern = activatedPattern;
    }

    public static List<CitySettings> getActivatedCitySettings(int citySettings) {
        List<CitySettings> activatedSettings = new ArrayList<CitySettings>();
        for (CitySettings settings : CitySettings.values()) {
            if ((citySettings & settings.activatedPattern) == settings.activatedPattern)
                activatedSettings.add(settings);
        }

        return activatedSettings;
    }

    public static boolean settingActivated(CitySettings setting, int citySettings) {
        return ((setting.activatedPattern & citySettings) == setting.activatedPattern);
    }
}

package de.static_interface.sinkcity;

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

public enum CitySettings {

    FIRE(0b0000_0001),
    MOBS(0b0000_0010),
    TNT_BUILD(0b0000_0100),
    TNT_EXPLODE(0b0000_1000),
    EXPLOSION(0b0001_0000),
    OPEN_CITY(0b0010_0000);

    private int activatedPattern;

    private CitySettings(int activatedPattern) {
        this.activatedPattern = activatedPattern;
    }

    public static List<CitySettings> getActivatedCitySettings(int citySettings) {
        List<CitySettings> activatedSettings = new ArrayList<CitySettings>();
        for (CitySettings settings : CitySettings.values()) {
            if ((citySettings & settings.activatedPattern) == settings.activatedPattern)
                activatedSettings.add(settings);
        }

        return activatedSettings;
    }

    public static boolean settingActivated(CitySettings setting, int citySettings) {
        return ((setting.activatedPattern & citySettings) == setting.activatedPattern);
    }
}

Switch from YML configuration files to XML configuration files.


package name.falgout.jeffrey.throwing;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

@FunctionalInterface
public interface RethrowChain<X extends Throwable, Y extends Throwable>
    extends Function<X, Optional<Y>> {
  public static <Y extends Throwable> RethrowChain<Throwable, Y> castTo(Class<Y> clazz) {
    return e -> Optional.ofNullable(clazz.isInstance(e) ? clazz.cast(e) : null);
  }

  default public RethrowChain<X, Y> connect(RethrowChain<X, Y> link) {
    Objects.requireNonNull(link);
    return x -> {
      Optional<Y> y = apply(x);
      if (y.isPresent()) {
        return y;
      }

      return link.apply(x);
    };
  }

  default public <Z extends Throwable> RethrowChain<X, Z> rethrow(
      Function<? super Y, ? extends Z> mapper) {
    Objects.requireNonNull(mapper);
    return x -> apply(x).map(mapper);
  }

  default public Function<X, Y> finish() {
    return finish(x -> {
      throw new AssertionError(x);
    });
  }

  default public Function<X, Y> finish(Function<? super X, ? extends Y> unhandledException) {
    Objects.requireNonNull(unhandledException);
    return x -> {
      return apply(x).orElseGet(() -> {
        if (x instanceof RuntimeException) {
          throw (RuntimeException) x;
        } else if (x instanceof Error) {
          throw (Error) x;
        }

        return unhandledException.apply(x);
      });
    };
  }
}

package name.falgout.jeffrey.throwing;

import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

@FunctionalInterface
public interface RethrowChain<X extends Throwable, Y extends Throwable>
    extends Function<X, Optional<Y>> {
  public static <Y extends Throwable> RethrowChain<Throwable, Y> castTo(Class<? extends Y> clazz) {
    return e -> Optional.ofNullable(clazz.isInstance(e) ? clazz.cast(e) : null);
  }

  default public RethrowChain<X, Y> connect(RethrowChain<X, Y> link) {
    Objects.requireNonNull(link);
    return x -> {
      Optional<Y> y = apply(x);
      if (y.isPresent()) {
        return y;
      }

      return link.apply(x);
    };
  }

  default public <Z extends Throwable> RethrowChain<X, Z> rethrow(
      Function<? super Y, ? extends Z> mapper) {
    Objects.requireNonNull(mapper);
    return x -> apply(x).map(mapper);
  }

  default public Function<X, Y> finish() {
    return finish(x -> {
      throw new AssertionError(x);
    });
  }

  default public Function<X, Y> finish(Function<? super X, ? extends Y> unhandledException) {
    Objects.requireNonNull(unhandledException);
    return x -> {
      return apply(x).orElseGet(() -> {
        if (x instanceof RuntimeException) {
          throw (RuntimeException) x;
        } else if (x instanceof Error) {
          throw (Error) x;
        }

        return unhandledException.apply(x);
      });
    };
  }
}

Allow castTo to automatically widen the generic bound.


package to.etc.domui.test.binding;

import org.junit.Assert;
import org.junit.Test;
import to.etc.domui.test.binding.order1.TestBindingOrder1;
import to.etc.domui.webdriver.core.AbstractWebDriverTest;

/**
 * @author Frits Jalvingh
 *         Created on 15-3-17.
 */
public class TestBindingOrder extends AbstractWebDriverTest {
	@Test
	public void testBinding1() throws Exception {
		wd().openScreen(TestBindingOrder1.class);

		//-- Switching country should switch city
		wd().select("country", "Netherlands");
		String city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("Amsterdam", city);

		wd().select("country", "USA");
		city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("New York", city);

		//-- Switching city to a city in another country should  change country
		wd().select("city", "Lelystad");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		//-- Switching city to another in the same country
		wd().select("city", "Amsterdam");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		Thread.sleep(10000);
	}
}

package to.etc.domui.test.binding;

import org.junit.Assert;
import org.junit.Test;
import to.etc.domui.test.binding.order1.TestBindingOrder1;
import to.etc.domui.webdriver.core.AbstractWebDriverTest;

/**
 * @author Frits Jalvingh
 *         Created on 15-3-17.
 */
public class TestBindingOrder extends AbstractWebDriverTest {

	/**
	 * https://etc.to/confluence/display/DOM/Tests%3A+data+binding
	 * @throws Exception
	 */
	@Test
	public void testBinding1() throws Exception {
		wd().openScreen(TestBindingOrder1.class);

		//-- Switching country should switch city
		wd().select("country", "Netherlands");
		String city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("Amsterdam", city);

		wd().select("country", "USA");
		city = wd().selectGetSelectedLabel("city");
		Assert.assertEquals("New York", city);

		//-- Switching city to a city in another country should  change country
		wd().select("city", "Lelystad");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		//-- Switching city to another in the same country
		wd().select("city", "Amsterdam");
		city = wd().selectGetSelectedLabel("country");
		Assert.assertEquals("Netherlands", city);

		Thread.sleep(10000);
	}
}

Add wiki note for test.


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

package com.google.gerrit.server.git;

import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.config.RepositoryConfig;
import com.google.inject.Inject;

/**
 * Module to install {@link MultiBaseLocalDiskRepositoryManager} rather than {@link
 * LocalDiskRepositoryManager} if needed.
 */
public class GitRepositoryManagerModule extends LifecycleModule {

  private final RepositoryConfig repoConfig;

  @Inject
  public GitRepositoryManagerModule(RepositoryConfig repoConfig) {
    this.repoConfig = repoConfig;
  }

  @Override
  protected void configure() {
    if (repoConfig.getAllBasePaths().isEmpty()) {
      install(new LocalDiskRepositoryManager.Module());
    } else {
      install(new MultiBaseLocalDiskRepositoryManager.Module());
    }
  }
}

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

package com.google.gerrit.server.git;

import com.google.gerrit.lifecycle.LifecycleModule;
import com.google.gerrit.server.ModuleImpl;
import com.google.gerrit.server.config.RepositoryConfig;
import com.google.inject.Inject;

/**
 * Module to install {@link MultiBaseLocalDiskRepositoryManager} rather than {@link
 * LocalDiskRepositoryManager} if needed.
 */
@ModuleImpl(name = GitRepositoryManagerModule.MANAGER_MODULE)
public class GitRepositoryManagerModule extends LifecycleModule {
  public static final String MANAGER_MODULE = "git-manager";

  private final RepositoryConfig repoConfig;

  @Inject
  public GitRepositoryManagerModule(RepositoryConfig repoConfig) {
    this.repoConfig = repoConfig;
  }

  @Override
  protected void configure() {
    if (repoConfig.getAllBasePaths().isEmpty()) {
      install(new LocalDiskRepositoryManager.Module());
    } else {
      install(new MultiBaseLocalDiskRepositoryManager.Module());
    }
  }
}

Add possibility to override MultiBaseLocalDiskRepositoryManager


package org.apache.ibatis.parsing;

import org.apache.ibatis.io.Resources;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

import java.io.Reader;

public class XPathParserTest {

  @Test
  public void shouldTestXPathParserMethods() throws Exception {
    String resource = "resources/nodelet_test.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    XPathParser parser = new XPathParser(reader, false, null, null);
    assertEquals((long)1970, parser.evalLong("/employee/birth_date/year"));
    assertEquals((short)6, parser.evalShort("/employee/birth_date/month"));
    assertEquals(15, parser.evalInteger("/employee/birth_date/day"));
    assertEquals(5.8f, parser.evalFloat("/employee/height"));
    assertEquals(5.8d, parser.evalDouble("/employee/height"));
    assertEquals("${id_var}", parser.evalString("/employee/@id"));
    assertEquals(Boolean.TRUE, parser.evalBoolean("/employee/active"));
    assertEquals("<id>${id_var}</id>", parser.evalNode("/employee/@id").toString().trim());
    assertEquals(7, parser.evalNodes("/employee/*").size());
    XNode node = parser.evalNode("/employee/height");
    assertEquals("employee/height", node.getPath());
    assertEquals("employee[${id_var}]_height", node.getValueBasedIdentifier());
  }

}

package org.apache.ibatis.parsing;

import org.apache.ibatis.io.Resources;
import static org.junit.Assert.assertEquals;
import org.junit.Test;

import java.io.Reader;

public class XPathParserTest {

  @Test
  public void shouldTestXPathParserMethods() throws Exception {
    String resource = "resources/nodelet_test.xml";
    Reader reader = Resources.getResourceAsReader(resource);
    XPathParser parser = new XPathParser(reader, false, null, null);
    assertEquals((Long)1970l, parser.evalLong("/employee/birth_date/year"));
    assertEquals((short) 6, (short) parser.evalShort("/employee/birth_date/month"));
    assertEquals((Integer) 15, parser.evalInteger("/employee/birth_date/day"));
    assertEquals((Float) 5.8f, parser.evalFloat("/employee/height"));
    assertEquals((Double) 5.8d, parser.evalDouble("/employee/height"));
    assertEquals("${id_var}", parser.evalString("/employee/@id"));
    assertEquals(Boolean.TRUE, parser.evalBoolean("/employee/active"));
    assertEquals("<id>${id_var}</id>", parser.evalNode("/employee/@id").toString().trim());
    assertEquals(7, parser.evalNodes("/employee/*").size());
    XNode node = parser.evalNode("/employee/height");
    assertEquals("employee/height", node.getPath());
    assertEquals("employee[${id_var}]_height", node.getValueBasedIdentifier());
  }

}

Fix test so that it works with Junit 4.6


/**
*
* Copyright 2003-2004 The Apache Software Foundation
*
*  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.apache.geronimo.tomcat;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.modeler.util.IntrospectionUtils;

public abstract class BaseGBean {

    protected void setParameters(Object object, Map map){
        if (map != null){
            Set keySet = map.keySet();
            Iterator iterator = keySet.iterator();
            while(iterator.hasNext()){
                String name = (String)iterator.next();
                String value = (String)map.get(name);

                IntrospectionUtils.setProperty(object, name, value);
            }
        }

    }

}

/**
*
* Copyright 2003-2004 The Apache Software Foundation
*
*  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.apache.geronimo.tomcat;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.tomcat.util.IntrospectionUtils;

public abstract class BaseGBean {

    protected void setParameters(Object object, Map map){
        if (map != null){
            Set keySet = map.keySet();
            Iterator iterator = keySet.iterator();
            while(iterator.hasNext()){
                String name = (String)iterator.next();
                String value = (String)map.get(name);

                IntrospectionUtils.setProperty(object, name, value);
            }
        }

    }

}

Use the Tomcat INtrospection utilities instead of commons modeler


package org.literacyapp.model.gson;

import java.util.Calendar;
import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson;

public class StudentImageGson extends BaseEntityGson {

    private DeviceGson device;

    private Calendar timeCollected;

    private String imageFileUrl;

    private StudentImageFeatureGson studentImageFeature;

    private StudentImageCollectionEventGson studentImageCollectionEvent;

    public DeviceGson getDevice() {
        return device;
    }

    public void setDevice(DeviceGson device) {
        this.device = device;
    }

    public Calendar getTimeCollected() {
        return timeCollected;
    }

    public void setTimeCollected(Calendar timeCollected) {
        this.timeCollected = timeCollected;
    }

    public String getImageFileUrl() {
        return imageFileUrl;
    }

    public void setImageFileUrl(String imageFileUrl) {
        this.imageFileUrl = imageFileUrl;
    }

    public StudentImageFeatureGson getStudentImageFeature() {
        return studentImageFeature;
    }

    public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) {
        this.studentImageFeature = studentImageFeature;
    }

    public StudentImageCollectionEventGson getStudentImageCollectionEvent() {
        return studentImageCollectionEvent;
    }

    public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) {
        this.studentImageCollectionEvent = studentImageCollectionEvent;
    }
}

package org.literacyapp.model.gson;

import java.util.Calendar;
import org.literacyapp.model.gson.analytics.StudentImageCollectionEventGson;

public class StudentImageGson extends BaseEntityGson {

    private Calendar timeCollected;

    private String imageFileUrl;

    private StudentImageFeatureGson studentImageFeature;

    private StudentImageCollectionEventGson studentImageCollectionEvent;

    public Calendar getTimeCollected() {
        return timeCollected;
    }

    public void setTimeCollected(Calendar timeCollected) {
        this.timeCollected = timeCollected;
    }

    public String getImageFileUrl() {
        return imageFileUrl;
    }

    public void setImageFileUrl(String imageFileUrl) {
        this.imageFileUrl = imageFileUrl;
    }

    public StudentImageFeatureGson getStudentImageFeature() {
        return studentImageFeature;
    }

    public void setStudentImageFeature(StudentImageFeatureGson studentImageFeature) {
        this.studentImageFeature = studentImageFeature;
    }

    public StudentImageCollectionEventGson getStudentImageCollectionEvent() {
        return studentImageCollectionEvent;
    }

    public void setStudentImageCollectionEvent(StudentImageCollectionEventGson studentImageCollectionEvent) {
        this.studentImageCollectionEvent = studentImageCollectionEvent;
    }
}

Remove device from student image


package org.zalando.pazuzu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfiguration {

    @Value("${pazuzu.registry.cors.allowedOrigins:}")
    private String allowedOrigins;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**").allowedOrigins(allowedOrigins);
            }
        };
    }
}

package org.zalando.pazuzu.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfiguration {

    @Value("${pazuzu.registry.cors.allowedOrigins:}")
    private String allowedOrigins;

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry
                        .addMapping("/api/**")
                        .allowedOrigins(allowedOrigins)
                        .allowedMethods("GET", "PUT", "POST", "DELETE");
            }
        };
    }
}

Set the allowed methods to all required ones.


package org.commcare.suite.model;

/**
 * Piece of required session data that is acquired via an xpath computation
 *
 * @author Phillip Mates (pmates@dimagi.com)
 */
public class ComputedDatum extends SessionDatum {
    public ComputedDatum() {

    }

    /**
     * @param id    Name used to access the computed data in the session instance
     * @param value XPath expression whose evaluation result is used as the data
     */
    public ComputedDatum(String id, String value) {
        super(id, value);
    }
}

package org.commcare.suite.model;

/**
 * Piece of required session data that is acquired via an xpath computation
 *
 * @author Phillip Mates (pmates@dimagi.com)
 */
public class ComputedDatum extends SessionDatum {
    @SuppressWarnings("unused")
    public ComputedDatum() {
        // used in serialization
    }

    /**
     * @param id    Name used to access the computed data in the session instance
     * @param value XPath expression whose evaluation result is used as the data
     */
    public ComputedDatum(String id, String value) {
        super(id, value);
    }
}

Add suppress unused & comment