/*
 * 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.guacamole;

import org.apache.guacamole.protocol.GuacamoleStatus;

/**
 * An exception which is thrown when a resource is no longer available because
 * it is closed.
 */
public class GuacamoleResourceClosedException extends GuacamoleClientException {

    /**
     * Creates a new GuacamoleResourceClosedException with the given message
     * and cause.
     *
     * @param message
     *     A human readable description of the exception that occurred.
     *
     * @param cause
     *     The cause of this exception.
     */
    public GuacamoleResourceClosedException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Creates a new GuacamoleResourceClosedException with the given message.
     *
     * @param message
     *     A human readable description of the exception that occurred.
     */
    public GuacamoleResourceClosedException(String message) {
        super(message);
    }

    /**
     * Creates a new GuacamoleResourceClosedException with the given cause.
     *
     * @param cause
     *     The cause of this exception.
     */
    public GuacamoleResourceClosedException(Throwable cause) {
        super(cause);
    }

    @Override
    public GuacamoleStatus getStatus() {
        return GuacamoleStatus.RESOURCE_CLOSED;
    }

}

GUACAMOLE-208: Define missing exception for the RESOURCE_CLOSED status code.


package hr.fer.java.vjezbe.zadatak4.component;

import org.springframework.stereotype.Component;

@Component
public class ZelBarComponent extends CoreComponent {

	@Override
	protected String setStudentName() {
		return "Zeljko";
	}

}

Add ZelBar component implementation Unknown userzelbar

Adds the ZelBar component into hr.fer.java.vjezbe.zadatak4.component package that implements the abstract CoreComponent and implements the setStudentName returning the student's name.


import java.util.Scanner;

/**
 * This program strips words of repeating letters, or reports if there are none.
 **/
public class RemoveDuplicateLetters {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Input word");
        String word = scanner.nextLine();
        String ans = "";

        for (int i = 0; i < word.length(); i++) {
            int count = 0;
            for (int j = 0; j < ans.length(); j++) {
                if (word.charAt(i) == ans.charAt(j)) {
                    count++;
                }
            }
            if (count == 0) {
                ans += word.charAt(i);
            }
        }

        if (word.equals(ans)) {
            System.out.println("No repeated letters");
        } else {
            System.out.println(ans);
        }
    }
}

Add problem 6 to unit 3

Add problem 6 to unit 3


/**
 * Copyright (C) 2015 The Gravitee team (http://gravitee.io)
 *
 * 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.gravitee.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Represents the version information.
 *
 * @author David BRASSELY (brasseld at gmail.com)
 * @author GraviteeSource Team
 */
public final class Version {

    /**
     * Represents the build id, which is a string like "b13".
     */
    public final String BUILD_ID;

    /**
     * Represents the complete build number
     */
    public final String BUILD_NUMBER;

    /**
     * Represents the major version, such as "2.0".
     */
    public final String MAJOR_VERSION;

    /**
     * Represents the latest Revision number.
     */
    public final String REVISION;

    /**
     * The Runtime Version.
     */
    public static final Version RUNTIME_VERSION = Version.create(Version.class.getResourceAsStream("/version.properties"));

    private Version(String buildId, String buildVersion, String majorVersion, String revision) {
        this.BUILD_ID = fixNull(buildId);
        this.BUILD_NUMBER = fixNull(buildVersion);
        this.MAJOR_VERSION = fixNull(majorVersion);
        this.REVISION = fixNull(revision);
    }

    public static Version create(InputStream is) {
        Properties props = new Properties();
        try {
            props.load(is);
        } catch (IOException e) {
            // ignore even if the property was not found. we'll treat everything as unknown
        } catch (Exception e) {
            //ignore even if property not found
        }

        return new Version(
                props.getProperty("build-id"),
                props.getProperty("build-version"),
                props.getProperty("major-version"),
                props.getProperty("revision"));
    }

    private String fixNull(String v) {
        if(v==null) return "unknown";
        return v;
    }

    public String toString() {
        return MAJOR_VERSION + " (build: " + BUILD_ID + ") revision#" + REVISION;
    }
}

chore: Add version class used to read data from a properties file available from classloader


package uk.me.graphe.client;

import java.util.Collection;

public class DrawingGraphML{

    private static Collection<EdgeDrawable> mEdgesToDraw;
    private static Collection<VertexDrawable> mVerticesToDraw;

    public static String getString(Collection<EdgeDrawable> edges,Collection<VertexDrawable> vertices){
        mEdgesToDraw = edges;
        mVerticesToDraw = vertices;
        return "hello world";
    }
}

Create class to convert graph to GaphML

Create class to convert graph to GaphML


package leetcode;

/**
 * https://leetcode.com/problems/house-robber-iii/
 */
public class Problem337 {
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    public int rob(TreeNode root) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Problem337 prob = new Problem337();

        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(2);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(3);
        root.right.right = new TreeNode(1);
        System.out.println(prob.rob(root)); // 7

        root = new TreeNode(3);
        root.left = new TreeNode(4);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(5);
        root.right.right = new TreeNode(1);
        System.out.println(prob.rob(root)); // 9
    }
}

Create a skeleton for problem 337

Create a skeleton for problem 337


package edu.northwestern.bioinformatics.studycalendar.domain;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;

/**
 * @author Rhett Sutphin
 */
public class OracleCompatibilityTest extends StudyCalendarTestCase {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @SuppressWarnings({ "unchecked" })
    public void testAllConfiguredSequencesLessThan30Characters() throws Exception {
        AnnotationSessionFactoryBean sessionFactoryBean
            = (AnnotationSessionFactoryBean) getDeployedApplicationContext().getBean("&sessionFactory");
        Iterator<PersistentClass> mappedClasses = sessionFactoryBean.getConfiguration().getClassMappings();
        while (mappedClasses.hasNext()) {
            PersistentClass pc =  mappedClasses.next();
            Class<?> clazz = pc.getMappedClass();
            GenericGenerator generator = clazz.getAnnotation(GenericGenerator.class);
            if (generator == null) {
                log.debug("{} has no declared generator", clazz.getName());
                continue;
            }
            Parameter sequence = null;
            for (Parameter parameter : generator.parameters()) {
                if ("sequence".equals(parameter.name())) {
                    sequence = parameter; break;
                }
            }
            if (sequence == null) {
                fail("Generator for " + clazz.getName() + " has no sequence parameter");
            }
            assertTrue("Oracle sequence for " + clazz.getName() + " is too long: " + sequence.value() + " (" + sequence.value().length() + " chars). It must be no more than 30 characters. Bering will generate an appropriately named sequence; be sure to configure the same one in the class annotation.",
                sequence.value().length() <= 30);
        }
    }
}

Test for checking that all configured (in the annotations) sequences for oracle are less than 30 characters

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1695 0d517254-b314-0410-acde-c619094fa49f


package com.bignerdranch.android.criminalintent;

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

public class CrimePagerActivity extends FragmentActivity {

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

Create activity for the new crime pager

Create activity for the new crime pager


/*******************************************************************************
 * Copyright (c) 2012 - 2015 Signal Iduna Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Signal Iduna Corporation - initial API and implementation
 * akquinet AG
 *******************************************************************************/
package org.testeditor.ui.parts.commons;

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

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

import org.eclipse.e4.core.contexts.ContextInjectionFactory;
import org.eclipse.e4.core.contexts.EclipseContextFactory;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.swt.widgets.Shell;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.testeditor.core.model.teststructure.TestCase;
import org.testeditor.core.model.teststructure.TestProject;
import org.testeditor.core.services.interfaces.TestProjectService;
import org.testeditor.ui.adapter.TestProjectServiceAdapter;

/**
 * Tests for the SearchTestStructureDialog.
 *
 */
public class SearchTestStructureDialogTest {

	private Shell shell;

	/**
	 * Tests the building of the dialog.
	 *
	 * @throws Exception
	 *             on test failure
	 */
	@Test
	public void testCreateDialogAndFillResultView() throws Exception {
		IEclipseContext context = EclipseContextFactory.create();

		context.set(TestProjectService.class, new TestProjectServiceAdapter() {
			@Override
			public List<TestProject> getProjects() {
				ArrayList<TestProject> list = new ArrayList<TestProject>();
				TestCase testCase = new TestCase();
				TestProject testProject = new TestProject();
				testCase.setName("MyTest");
				testProject.addChild(testCase);
				list.add(testProject);
				return list;
			}
		});
		SearchTestStructureDialog dialog = new SearchTestStructureDialog(shell) {
			@Override
			public Shell getShell() {
				return shell;
			}
		};
		ContextInjectionFactory.inject(dialog, context);
		assertNull(dialog.getSelectedTestStructure());
		dialog.createDialogArea(shell);
		dialog.createTestStructureNamesLoader().run();
		assertSame(1, dialog.getResultViewer().getTable().getItemCount());
	}

	/**
	 * Creates UI handle for test.
	 */
	@Before
	public void setup() {
		shell = new Shell();
	}

	/**
	 * Cleanup ui handles.
	 */
	@After
	public void teardown() {
		shell.dispose();
	}
}

Test the Dialog Result view.

Test the Dialog Result view.


/*
Copyright (c) 2016, Colorado State University
All rights reserved.

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 holder 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 io.sigpipe.sing.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Simple utility that consumes a list of Geohash strings and outputs their
 * respective binary forms. The command line version receives the Geohash
 * strings from stdin.
 *
 * @author malensek
 */
public class GeoBits {

    public static void main(String[] args) throws Exception {

        InputStreamReader in = new InputStreamReader(System.in);
        try (BufferedReader br = new BufferedReader(in)) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(GeoBits.geohashToBinString(line));
            }
        }
    }

    public static String geohashToBinString(String geohash) {
        long l = GeoHash.hashToLong(geohash);
        return Long.toBinaryString(l);
    }

}

Add utility class for printing binary GeoHashes


/*
 * Copyright 2013 Cloudera 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.cloudera.cdk.morphline.api;

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

import com.cloudera.cdk.morphline.base.PrettyPrinter;

public class PrettyPrinterTest extends Assert {

  @Test
  public void testBasic() throws Exception {
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/grokSyslogNgCisco.conf"});
    PrettyPrinter.main(new String[] {"target/test-classes/test-morphlines/parseComplexConfig.conf"});
  }

}

CDK-237: Add utility to nicely indent and format a morphline config file


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

import hudson.Extension;
import hudson.URLConnectionDecorator;
import jenkins.model.Jenkins;
import jenkins.util.SystemProperties;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URLConnection;

/**
 * Sets a Jenkins specific user-agent HTTP header for {@link HttpURLConnection}.
 *
 * @since TODO
 */
@Extension
@Restricted(NoExternalUse.class)
@Symbol("userAgent")
public class UserAgentURLConnectionDecorator extends URLConnectionDecorator {
    private static /* non-final for Groovy */ boolean DISABLED = SystemProperties.getBoolean(UserAgentURLConnectionDecorator.class.getName() + ".DISABLED");

    @Override
    public void decorate(URLConnection con) throws IOException {
        if (!DISABLED && con instanceof HttpURLConnection) {
            HttpURLConnection httpConnection = (HttpURLConnection) con;
            httpConnection.setRequestProperty("User-Agent", "Jenkins/" + Jenkins.getVersion());
        }
    }
}

Add a Jenkins User-Agent header to outgoing HTTP requests


import java.util.Scanner;

/**
 * Created by Nathan_Zeplowitz on 4/11/15.
 */
public class HorizontalLine {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number");
        int n = in.nextInt();
        for (int i = 0; i < n; i++)
            System.out.print("*");
    }

}

Add Second Exercise Horizontal Line

Add Second Exercise Horizontal Line


package org.agmip.core.types;

import java.util.Map;

/**
 *
 * @author Meng Zhang
 */
public interface DividableOutputTranslator {
    public void writeFile(String filePath, Map input, int size);
}

Add dividable interface for translator which could get divided translation result


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

package org.springframework.cloud.netflix.eureka.server;

import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.log4j.Log4JLoggingSystem;
import org.springframework.boot.test.OutputCapture;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import com.netflix.blitz4j.LoggingConfiguration;

/**
 * Tests for {@link Log4JLoggingSystem}.
 *
 * @author Phillip Webb
 */
public class Log4JLoggingSystemTests {

	@Rule
	public OutputCapture output = new OutputCapture();

	private final Log4JLoggingSystem loggingSystem = new Log4JLoggingSystem(getClass()
			.getClassLoader());

	private Logger logger;

	@Before
	public void setup() {
		System.setProperty("log4j.configuration", getPackagedConfigFile("log4j.properties"));
		logger = Logger.getLogger(getClass());
		LoggingConfiguration.getInstance().configure();
	}

	@Test
	@Ignore("gh-48")
	public void setLevel() throws Exception {
		this.loggingSystem.beforeInitialize();
		this.loggingSystem.initialize(null, null);
		this.logger.debug("Hello");
		this.loggingSystem.setLogLevel("org.springframework.cloud", LogLevel.DEBUG);
		this.logger.debug("Hello");
		assertThat(StringUtils.countOccurrencesOf(this.output.toString(), "Hello"),
				equalTo(1));
	}

	private final String getPackagedConfigFile(String fileName) {
		try {
			return new ClassPathResource(fileName, Log4JLoggingSystem.class).getURL().toString();
		}
		catch (IOException e) {
			throw new IllegalStateException("Cannot create URL", e);
		}
	}
}

Add ignored test to show that blitz4j is not responding

Blitz4j is definitely preventing the log levels from being changed at runtime
through the normal Spring boot channels.

Fixes gh-48


/*
 * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.controller.netconf.mapping.api;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class HandlingPriorityTest {

    @Test
    public void testHandlingPriority() throws Exception {

        assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 0);
        assertTrue(HandlingPriority.CANNOT_HANDLE.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == -1);
        assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.CANNOT_HANDLE) == 1);

        assertTrue(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_MAX_PRIORITY) == -1);
        assertTrue(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 1);
        assertTrue(HandlingPriority.getHandlingPriority(Integer.MIN_VALUE).compareTo(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY) == 0);

        HandlingPriority prio = HandlingPriority.getHandlingPriority(10);
        assertTrue(prio.increasePriority(1).compareTo(HandlingPriority.getHandlingPriority(11)) == 0);

        assertFalse(HandlingPriority.CANNOT_HANDLE.getPriority().isPresent());
        assertFalse(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.equals(new Object()));
        assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY, HandlingPriority.getHandlingPriority(Integer.MAX_VALUE));
        assertEquals(HandlingPriority.HANDLE_WITH_MAX_PRIORITY.hashCode(), HandlingPriority.getHandlingPriority(Integer.MAX_VALUE).hashCode());
    }
}

Add netconf-mapping-api test for HandlingPriority

Change-Id: I29a6fdaab266acd42c5355101769bb82c14135fc
Signed-off-by: Tomas Cere <0a8853d56a412aee48c4c5a5a6d548b976ff286c@cisco.com>


package leetcode.decode_ways;

public class Solution {
    public int numDecodings(String s) {
    	char[] chars = s.toCharArray();
    	int lens = chars.length;
    	if(lens == 0) return 0;
    	char prev = 0;
    	int cur_end = 1, cur_prev = 0;
    	for(int i = 0; i < lens; i++){
    		int next_end = 0, next_prev = 0;
    		next_prev = cur_end;
    		if(chars[i] == '0'){
    			if(prev == '1' || prev == '2'){
    				next_end += cur_prev;
    			}else{
    				next_end = 0;
    			}
    		}else{
    			next_end = cur_end; // 1 digit ends at char[i]
    			if(prev == '2'){
    				if(chars[i] >= '1' && chars[i] <= '6'){
    					next_end += cur_prev; // 2 digit '2x' ends at char[i]
    				}
    			}else if(prev == '1'){
    				next_end += cur_prev;
    			}
    		}
    		prev = chars[i];
    		cur_end = next_end;
    		cur_prev = next_prev;
    	}
    	return cur_end;
    }

    public static void main(String[] args){
    	System.err.println(new Solution().numDecodings(""));
    }
}

Add java solution for 91. Decode Ways

Add java solution for 91. Decode Ways

91. Decode Ways: https://leetcode.com/problems/decode-ways/


package it.unibg.alasc.examples;

public class SemanticException extends Exception {

	public SemanticException() {
		// TODO Auto-generated constructor stub
	}

	public SemanticException(String arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public SemanticException(Throwable arg0) {
		super(arg0);
		// TODO Auto-generated constructor stub
	}

	public SemanticException(String arg0, Throwable arg1) {
		super(arg0, arg1);
		// TODO Auto-generated constructor stub
	}

}

Add the exception class that implements the semantic exception.


package bullshit_paper;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;

public class MarkovChain {
	private HashMap<String, LinkedList<String> > graph;

	MarkovChain(){
		graph = new HashMap<>();
	}

	public void build(List<String> sentences){

		for(String s: sentences){
			List<String> cur = Parser.parseSentence(s);
			cur.add(".");

			for(int i=-1; i<cur.size()-1; ++i){
				LinkedList<String> tmp;
				String from;

				if(i == -1){
					from = "#";
					tmp = graph.get(from);
				}
				else{
					from = cur.get(i);
					tmp = graph.get(from);
				}

				if(tmp == null){
					tmp = new LinkedList<String>();
				}

				tmp.add(cur.get(i+1));
				graph.put(from, tmp);
			}
		}

		for(Entry<String, LinkedList<String>> entry: graph.entrySet()){
			LinkedList<String> tmp = entry.getValue();
			Collections.shuffle(tmp);
			graph.put(entry.getKey(),tmp);
		}

	}

	public String generateRandomText(int length){
		StringBuilder builder = new StringBuilder();
		Random random = new Random();

		for(int i=0; i<length; ++i){
			String cur = "#";

			while(cur != "."){
				LinkedList<String> list = graph.get(cur);
				int size = list.size();
				cur = list.get(random.nextInt(size));

				if(cur != "."){
					builder.append(" "+cur);
				}
			}

			builder.append(".");
		}

		return builder.toString();
	}

}

Add simple random text generator

Add simple random text generator


package christmas;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

import static java.util.Calendar.*;

/**
 *  A program that counts down to Christmas.
 *
 *  @author  Joel Abrahamsson
 *  @version %G%
 */
public class Countdown extends JFrame
{
  private static long MILLIS_PER_DAY    = 86400000L;
  private static long MILLIS_PER_HOUR   = 3600000L;
  private static long MILLIS_PER_MINUTE = 60000L;

  private Calendar christmas;
  private JLabel label;

  /**
   *  Creates a new Coundown-object.
   */
  public Countdown()
  {
    super("Christmas countdown");

    christmas = getChristmasCalendar();

    setDefaultCloseOperation(EXIT_ON_CLOSE);

    // Create label
    label = new JLabel(formatTimeString(getTimeToChristmas()), JLabel.CENTER);

      label.setPreferredSize(new Dimension(320, 64));

    getContentPane().add(label);
    pack();

    // Create and start timer
    Timer timer = new Timer(250, new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        label.setText(formatTimeString(getTimeToChristmas()));
      }
    });
    timer.start();
  }

  /**
   *  Formats a string from the given time.
   *
   *  @param milliseconds time in milliseconds
   *
   *  @return             formatted string
   */
  private String formatTimeString(long milliseconds)
  {
    long days = milliseconds / MILLIS_PER_DAY;
    milliseconds %= MILLIS_PER_DAY;

    long hours = milliseconds / MILLIS_PER_HOUR;
    milliseconds %= MILLIS_PER_HOUR;

    long minutes = milliseconds / MILLIS_PER_MINUTE;
    milliseconds %= MILLIS_PER_MINUTE;

    long seconds = milliseconds / 1000;

    return String.format("%d days %d hours %d minutes %d seconds", days, hours, minutes, seconds);
  }

  /**
   *  Returns a Calendar representing Christmas (December 24th) the current year.
   *
   *  @return Calendar-object representing Christmas
   */
  private Calendar getChristmasCalendar()
  {
    Calendar christmas = Calendar.getInstance();

    christmas.set(Calendar.MONTH, 12);
    christmas.set(Calendar.DAY_OF_MONTH, 24);

    return christmas;
  }

  /**
   *  Returns the time left to Christmas (in milliseconds).
   *
   *  @return time left to Christmas (in milliseconds)
   */
  private long getTimeToChristmas()
  {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(christmas.getTimeInMillis() - calendar.getTimeInMillis());

    calendar.set(MONTH, 0);

    return calendar.getTimeInMillis();
  }

  public static void main(String[] args)
  {
    Countdown countdown = new Countdown();
    countdown.setVisible(true);
  }
}

Create a program that countdown to Christmas (December 24th)


package forklift.decorators;

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;

/**
 * Marks an object to have its properties populated with data from the JMS message
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Message {
}

Add a way to mark a field within a processor to have the data injected into the field from the JMS message.


// Copyright 2019 Google LLC
//
// 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
//
//     https://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.sps.data;

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

/**
 *
 */
public class ProductDetectionData {
  private List<String> labels;
  private List<String> logos;
  private List<String> colors;

  public ProductDetectionData(List<String> labels, List<String> logos, List<String> colors) {
    // shallow copy
    this.labels = new ArrayList<String>(labels);
    this.logos = new ArrayList<String>(logos);
    this.colors = new ArrayList<String>(colors);
  }

  public List<String> getLabels() {
    return labels;
  }

  public List<String> getLogos() {
    return logos;
  }

  public List<String> getColors() {
    return colors;
  }
}

Add data class for storing image recognition data


package sed;

import java.io.IOException;

import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetLoader;

public class XMLLoader implements AssetLoader {

    @Override
    public Object load(AssetInfo assetInfo) throws IOException {
        SAXBuilder builder = new SAXBuilder();
        try {
            return builder.build(assetInfo.openStream()).getRootElement();
        } catch(JDOMException ex) {
            throw new IOException(ex);
        }
    }

}

Add XML loader for jME3 asset loader architecture


package org.msgpack;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.msgpack.annotation.Message;
import org.msgpack.type.ArrayValue;
import org.msgpack.type.Value;

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

/**
 * User: takeshita
 * Create: 11/10/17 23:17
 */
public class TestNestedList {

    MessagePack messagePack;

    @Before
    public void before(){
        messagePack = new MessagePack();
    }

    @Test
    public void testTestNestedList() throws IOException {
        NestedList obj = new NestedList();
        obj.list.add(list("aaa", "bbb"));
        obj.list.add(list(new MyClass("obj1"), new MyClass("obj2")));

        byte[] bytes = messagePack.write(obj);

        // Can't unpack as NestedList
        Value unpacked = messagePack.read(bytes);
        ArrayValue root = unpacked.asArrayValue();
        ArrayValue list1 = root.getElementArray()[0].asArrayValue();
        ArrayValue list2 = root.getElementArray()[1].asArrayValue();

        Assert.assertEquals("aaa",list1.getElementArray()[0].asIntegerValue().getInt());
        Assert.assertEquals("bbb",list1.getElementArray()[1].asIntegerValue().getInt());
        Assert.assertEquals("obj1",messagePack.convert(list2.getElementArray()[0],MyClass.class).name);
        Assert.assertEquals("obj2",messagePack.convert(list2.getElementArray()[1],MyClass.class).name);

    }

    private List<?> list( Object ... elements){
        List<Object> list = new ArrayList();
        for(Object o : elements){
            list.add(o);
        }
        return list;
    }

    @Message
    public static class NestedList{
        public List<List> list = new ArrayList<List>();

    }

    @Message
    public static class MyClass{
        String name;

        public MyClass(){}
        public MyClass(String n ){ name = n;}
    }

}

Add new test case which serialize nested list.


package leetcode.rotate_array;

public class Solution {
    int gcd(int a, int b){
        while(b != 0){
            int tmp = a;
            a = b;
            b = tmp % b;
        }
        return a;
    }
    public void rotate(int[] nums, int k) {
        if(nums == null || nums.length == 0) return;
        int length = nums.length;
        k = (k % length + length) % length;
        int g = gcd(length, k);
        for(int i = 0; i < g; i++){
            int tmp = nums[i];
            int cur = i;
            for(int j = 0; j < length / g - 1; j++){
                nums[cur] = nums[(cur - k + length) % length];
                cur = (cur - k + length) % length;
            }
            nums[cur] = tmp;
        }
    }

    public static void main(String[] args){
        int[] ary = new int[]{1, 2, 3, 4};
        new Solution().rotate(ary, 4);
        for(int x : ary){
            System.err.print(x + " ");
        }
        System.err.println("");
    }
}

Add java solution for 189. Rotate Array

Add java solution for 189. Rotate Array

189. Rotate Array: https://leetcode.com/problems/rotate-array/


/*
 * Copyright 2006 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.jorphan.math;

/**
 * Class to calculate various items that don't require all previous results to be saved:
 * - mean = average
 * - standard deviation
 * - minimum
 * - maximum
 */
public class Calculator {

	private double sum = 0;

	private double sumOfSquares = 0;

	private double mean = 0;

	private double deviation = 0;

	private int count = 0;

	private long bytes = 0;

	private long maximum = Long.MIN_VALUE;

	private long minimum = Long.MAX_VALUE;

	public void clear() {
		maximum = Long.MIN_VALUE;
		minimum = Long.MAX_VALUE;
		sum = 0;
		sumOfSquares = 0;
		mean = 0;
		deviation = 0;
		count = 0;
	}

	public void addValue(long newValue) {
		count++;
		minimum=Math.min(newValue, minimum);
		maximum=Math.max(newValue, maximum);
		double currentVal = newValue;
		sum += currentVal;
		sumOfSquares += currentVal * currentVal;
		// Calculate each time, as likely to be called for each add
		mean = sum / count;
		deviation = Math.sqrt((sumOfSquares / count) - (mean * mean));
	}

	public void addBytes(long newValue) {
		bytes += newValue;
	}

	public long getTotalBytes() {
		return bytes;
	}

	public double getMean() {
		return mean;
	}

	public double getStandardDeviation() {
		return deviation;
	}

	public long getMin() {
		return minimum;
	}

	public long getMax() {
		return maximum;
	}

	public int getCount() {
		return count;
	}
}

Add cheaper calculator (no need to save results)

git-svn-id: https://svn.apache.org/repos/asf/jakarta/jmeter/branches/rel-2-1@405491 13f79535-47bb-0310-9956-ffa450edef68

Former-commit-id: fa4fc7c5dfae488de7844dac26466d681ce216c8


import java.util.Iterator;
import java.util.Date;
import java.util.ArrayList;
import java.util.List;
import dk.netarkivet.common.utils.FilterIterator;
import dk.netarkivet.harvester.datamodel.Domain;
import dk.netarkivet.harvester.datamodel.DomainConfiguration;
import dk.netarkivet.harvester.datamodel.DomainDAO;

public class TestSnapShotHarvestDomainConfigRetrieval {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Testing first step snapshot harvest" +  new Date());
        DomainDAO dao = DomainDAO.getInstance();

        Iterator<DomainConfiguration> i = new FilterIterator<Domain, DomainConfiguration>(
                dao.getAllDomainsInSnapshotHarvestOrder()) {
            public DomainConfiguration filter(Domain domain) {
                if (domain.getAliasInfo() == null
                        || domain.getAliasInfo().isExpired()) {
                    return domain.getDefaultConfiguration();
                } else {
                    return null;
                }
            }
        };
        System.out.println("Iterator initialized " + new Date());
        long count = 0;
        List<DomainConfiguration> subset = new ArrayList<DomainConfiguration>();
        while (i.hasNext()) {
            count++;
            if (subset.size() >= 10000) {
                subset = new ArrayList<DomainConfiguration>();
                System.out.println("collected " + subset.size() + "  configs at " + new Date());
            }
            DomainConfiguration dc = i.next();
            subset.add(dc);
            if (count % 100 == 0) {
                System.out.println("#" + count + ": (conf-name, domain)= (" + dc.getName()
                        + ", " + dc.getDomainName() + ") at " + new Date());
            }
        }
    }
}

Test program for testing speed on retrieving DomainConfigs for snapshot harvests


package model.effects;

import model.Effect;
import model.stats.Stat;
import model.unit.Unit;

public class ModifyAttribute extends Effect {

	public ModifyAttribute(String name, String attribute, double power) {
		super(name,attribute);
		this.addStat(new Stat("Power",power));
	}

	@Override
	public void enact(Unit target) {
		target.getStatCollection("Attributes").setStat(this.getID(),
				target.getStatCollection("Attributes").getValue(this.getID())+this.getValue("Power"));
	}

	@Override
	public Effect copy() {
		return new ModifyAttribute(this.getName(),this.getID(),this.getValue("Power"));
	}

}

package model.effects;

import model.Effect;
import model.stats.Stat;
import model.unit.Unit;

public class ModifyAttribute extends Effect {

	public ModifyAttribute(String name, String attribute, double power) {
		super(name,attribute);
		this.addStat(new Stat("Power",power));
	}

	@Override
	public void enact(Unit target) {
		target.getStatCollection("Attributes").setStat(this.getID(),
				target.getStatCollection("Attributes").getValue(this.getID())+this.getValue("Power"));
		if(target.getStatCollection("Attributes").getValue("Health")<=0){
			target.getPlayer().removeUnit(target);
			target.getCurrentTile().removeUnit(target);
			target.getPlayer().getModel().destroyUnit(target);
		}
	}

	@Override
	public Effect copy() {
		return new ModifyAttribute(this.getName(),this.getID(),this.getValue("Power"));
	}

}

Destroy units properly using Custom Abilities


// Use a BufferedReader to read characters from the console.
import java.io.*;

class ReadChars {
	public static void main(String args[]) throws IOException {
		char c;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.println("Enter characters, period to quit.");

		// read characters
		do {
			c = (char) br.read();
			System.out.println(c);
		} while(c != '.');
	}
}

Use a BufferedReader to read characters from the console

http://ideone.com/qYOd8p


package org.jstanier.tweetscheduler.main;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

import com.jstanier.tweetscheduler.main.Config;

@RunWith(MockitoJUnitRunner.class)
public class ConfigTest {

	@Test
	public void whenConfigIsCreated_thenNoExceptionIsThrown() {
		new Config();
	}
}

Add unit test for Config

Add unit test for Config


import java.util.HashMap;

public class ContainsDuplicates {
    public boolean containsDuplicate(int[] nums) {
        HashMap<Integer, Integer> occurrenceCountMap = new HashMap<>();
        for (int num : nums) {
            if (occurrenceCountMap.containsKey (num))
                return true;
            else
                occurrenceCountMap.put (num, 1);
        }
        return false;
    }

    public static void main (String[] args) {
        ContainsDuplicates test = new ContainsDuplicates ();
        int[] testArray1 = {1, 2, 3, 4, 5};
        int[] testArray2 = {1, 1, 455};
        int[] testArray3 = {};
        System.out.println(test.containsDuplicate (testArray1));
        System.out.println(test.containsDuplicate (testArray2));
        System.out.println(test.containsDuplicate (testArray3));
    }
}

Check if array has duplicate values

Check if array has duplicate values


package retryable.asyncTask;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class)
public class ConcreteAsyncTaskTest {

  ConcreteAsyncTask<String, Void, Object> concreteAsyncTask;

  @Mock RetryableAsyncTask retryableAsyncTask;

  @Before
  public void setUp() {
    initMocks(this);

    concreteAsyncTask = new ConcreteAsyncTask<>(retryableAsyncTask);
  }

  @Test
  public void itDelegatesToParentTaskOnPreExecute() {
    concreteAsyncTask.execute();

    verify(retryableAsyncTask).onPreExecute();
  }

  @Test
  public void itDelegatesToParentTaskOnDoingBackgroundTask() {
    String params = "foo";

    concreteAsyncTask.execute(params);

    verify(retryableAsyncTask).doInBackground(params);
  }

  @Test
  public void itDelegatesToParentTaskOnPostExecute() {
    concreteAsyncTask.execute();

    verify(retryableAsyncTask).onPostExecute(null);
  }

}

Add unit test for ConcreteAsyncTask

Add unit test for ConcreteAsyncTask


/*
 * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 * Mateusz Parzonka - initial API and implementation
 */
package prm4j.indexing.map;

import static org.junit.Assert.*;

import org.junit.Test;

public class MinimalMapTest {

    @Test
    public void size_1() throws Exception {
	MinimalMap<MockEntry> map = new MockMap();
	assertEquals(0, map.size());
	String a = "a";
	map.get(a);
	assertEquals(1, map.size());
	map.get(a);
	assertEquals(1, map.size());
	map.get("b");
	assertEquals(2, map.size());
    }

    @Test
    public void get_1() throws Exception {
	MinimalMap<MockEntry> map = new MockMap();
	String a = "a";
	MockEntry x = map.get(a);
	MockEntry y = map.get(a);
	assertEquals(x, y);
    }

    static class MockMap extends MinimalMap<MockEntry> {

	@Override
	protected MockEntry[] createInitialArray(int size) {
	    return new MockEntry[size];
	}

	@Override
	protected MockEntry createEntry(Object key, int hashCode) {
	    return new MockEntry(key, hashCode);
	}

    }

    static class MockEntry implements MinimalMapEntry<MockEntry> {

	private final Object key;
	private final int hashCode;
	private MockEntry next;

	public MockEntry(Object key, int hashCode) {
	    this.key = key;
	    this.hashCode = hashCode;
	}

	@Override
	public int getHashCode() {
	    return hashCode;
	}

	@Override
	public Object getKey() {
	    return key;
	}

	@Override
	public MockEntry next() {
	    return next;
	}

	@Override
	public void setNext(MockEntry nextEntry) {
	    next = nextEntry;
	}

    }

}

Add initial tests for MinimalMap

Add initial tests for MinimalMap


package com.k13n.soliton;

import java.util.Random;

public class RobustSolitonGenerator implements SolitonGenerator {
  private Random random;
  private int k;
  private double c, delta, R, beta;

  public RobustSolitonGenerator(int k, double c, double delta, long seed) {
    this.k = k;
    this.c = c;
    this.delta = delta;
    random = new Random(seed);
    R = computeR();
    beta = computeBeta();
  }

  public RobustSolitonGenerator(int k, double c, double delta) {
    this(k, c, delta, new Random().nextLong());
  }

  private double computeR() {
    return c * Math.log(k / delta) * Math.sqrt(k);
  }

  private double computeBeta() {
    double sum = 0;
    for (int i = 1; i <= k; i++)
      sum += idealSoliton(i) + unnormalizedRobustSoliton(i);
    return sum;
  }

  @Override
  public int next() {
    double u = random.nextDouble();
    return inverseTransformSampling(u);
  }

  private int inverseTransformSampling(double u) {
     double sum = 0;
     int index = 1;
     while (sum <= u)
       sum += normalizedRobustSoliton(index++);
     return index - 1;
  }

  private double normalizedRobustSoliton(int i) {
    return (idealSoliton(i) + unnormalizedRobustSoliton(i)) / beta;
  }

  private double unnormalizedRobustSoliton(int i) {
    if (1 <= i && i <= Math.floor(k/R)-1)
      return R / (i*k);
    else if (i == Math.floor(k / R))
      return R * Math.log(R / delta) / k;
    else
      return 0;
  }

  private double idealSoliton(int i) {
    if (i == 1)
      return 1.0 / k;
    else
      return 1.0 / (i * (i-1));
  }

}

Implement a robust soliton random number generator


package net.sf.jabref.logic.pdf;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.HashMap;
import java.util.List;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;

public class PdfCommentImporter {

    private List pdfPages;
    private PDPage page;
    public PdfCommentImporter() {

    }

    /**
     * Imports the comments from a pdf specified by its URI
     * @param pathToPDF the URI specifying the document
     * @return a hasmap with the unique name as key and the notes content as value
     */
    public HashMap<String, String> importNotes(final URI pathToPDF){

        PDDocument pdf;
        HashMap<String, String> annotationsMap = new HashMap<>();
        try {
            pdf = importPdfFile(pathToPDF);

            pdfPages = pdf.getDocumentCatalog().getAllPages();
            for(int i = 0; i < pdfPages.size(); i++){
                page = (PDPage) pdfPages.get(i);
                for(PDAnnotation annotation : page.getAnnotations()){
                    annotationsMap.put(annotation.getAnnotationName(), annotation.getContents());
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return annotationsMap;
    }

    private PDDocument importPdfFile(final URI pathToPDF) throws IOException {
        File file = new File(pathToPDF);
        return PDDocument.load(file);
    }
}

Add importer class to extract pdf file comments


/*
 * (C) Copyright 2018 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.wdm.test;

import org.junit.Before;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;

import io.github.bonigarcia.wdm.WebDriverManager;
import io.github.bonigarcia.wdm.base.BrowserTestParent;

/**
 * Test with HtmlUnit browser (which uses void driver manager).
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class HtmlUnitTest extends BrowserTestParent {

    private static Class<? extends WebDriver> webDriverClass;

    @BeforeClass
    public static void setupClass() {
        webDriverClass = HtmlUnitDriver.class;
        WebDriverManager.getInstance(webDriverClass).setup();
    }

    @Before
    public void htmlUnitTest()
            throws InstantiationException, IllegalAccessException {
        driver = webDriverClass.newInstance();
    }

}

Include HtmlUnit test (to check void driver manager)


package binarytree;

import datastructures.tree.BinarySearchTree;
import datastructures.tree.TreeNode;

public class CheckBSTHasDeadEnd {
  private BinarySearchTree<Integer> tree = null;
  private TreeNode<Integer> root = null;

  public CheckBSTHasDeadEnd() {
    tree = new BinarySearchTree<Integer>();
  }

  public void constructTree(String[] input) {
    for (String line : input) {
      String[] values = line.split(" ");
      String action = values[0];

      switch (action) {
      case "insertRoot":
        tree = new BinarySearchTree<Integer>();
        root = tree.insertRoot(Integer.parseInt(values[1]));
        break;
      case "insert":
        tree.insert(root, Integer.parseInt(values[1]));
        break;
      }
    }
  }

  public boolean hasDeadEnd() {
    return hasDeadEnd(root, new Range(0, Integer.MAX_VALUE));
  }

  private boolean hasDeadEnd(TreeNode<Integer> root, Range range) {
    if(root == null) {
      return false;
    } else if (root.left == null && root.right == null) {
      return Math.abs(root.data - range.min) <= 1 && Math.abs(range.max - root.data) <= 1;
    } else {
      return hasDeadEnd(root.left, new Range(range.min, root.data)) || hasDeadEnd(root.right, new Range(root.data, range.max));
    }
  }

  private class Range {
    private int min;
    private int max;

    Range(int min, int max) {
      this.min = min;
      this.max = max;
    }
  }
}

Add solution for CheckBST has dead end

Add solution for CheckBST has dead end


package com.example.timber.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import timber.log.Timber;

@SuppressLint("Registered") //
public class LintActivity extends Activity {
  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Below are some examples of how NOT to use Timber
    /*
    Log.d("TAG", "msg");

    Timber.w(String.format("%s", "arg0"));

    Exception e = new Exception();
    Timber.d("%s", e);

    Timber.d("Hello, " + "world!");

    Timber.d("%s %s", "arg0");

    Timber.d("%s", "arg0", "arg1");

    Timber.d("%d", "arg0");

    Timber.tag("abcdefghijklmnopqrstuvwx");

    Timber.tag("tag").d("%s %s", "arg0");

    Timber.tag("tag").d("%s", "arg0", "arg1");

    Timber.tag("tag").d("%d", "arg0");

    Timber.tag("abcdefghijklmnopqrstuvw" + "x");

    Timber.tag("abcdefghijklmnopqrstuvw" + new String("x"));
    */
  }
}

Add Timber lint failure examples

Add Timber lint failure examples

Lint failures should display in the IDE again once the fix discussed here
is released: https://issuetracker.google.com/issues/62914381#comment10

This commit showcases the current suite of checks with some failure
examples.


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem58;

/**
 * Implement an algorithm to find the kth to last element of a singly linked list. Can you do it
 * using recursion?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindKthElement {

}

Add statement to problem 58

Add statement to problem 58


/*
 * 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.imaging.formats.tiff.photometricinterpreters;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class PhotometricInterpreterLogLuvTest {

    @Test
    public void testConstructor() {
        int samplesPerPixel = 8;
        int[] bitsPerSample = new int[] {1, 2, 3};
        int predictor = 1;
        int width = 800;
        int height = 600;
        PhotometricInterpreterLogLuv p = new PhotometricInterpreterLogLuv(samplesPerPixel, bitsPerSample, predictor,
                width, height);
        assertEquals(samplesPerPixel, p.samplesPerPixel);
        for (int i = 0; i < bitsPerSample.length; i++) {
            assertEquals(bitsPerSample[i], p.getBitsPerSample(i));
        }
        assertEquals(predictor, p.predictor);
        assertEquals(width, p.width);
        assertEquals(height, p.height);
    }
}

Add base test for PhotometricInterpreterLogLuv


package io.github.saidie.plantuml_api;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.validation.constraints.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Embeddable
@NoArgsConstructor
@AllArgsConstructor
public class IdpId implements Serializable {
    @NotNull
    @Enumerated(EnumType.STRING)
    private FederationType type;

    @NotNull
    @Column(nullable = false)
    private String id;

    public enum FederationType {
        TWITTER
    }
}

Add a class representing IdP identifier

Add a class representing IdP identifier


package jmetest.renderer.loader;

import com.jme.app.SimpleGame;
import com.jme.scene.model.ms3d.MilkLoader;
import com.jme.scene.model.XMLparser.XMLWriter;
import com.jme.scene.model.XMLparser.SAXReader;
import com.jme.scene.Node;

import java.net.URL;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;

/**
 * Started Date: Jun 5, 2004
 *
 * Class test the XMLWriter and SAXReader classes
 *
 * @author Jack Lindamood
 */
public class TestXMLWriter extends SimpleGame{
    public static void main(String[] args) {
        new TestXMLWriter().start();
    }
    protected void simpleInitGame() {
        MilkLoader mi=new MilkLoader();
        URL MSFile=TestMilkLoader.class.getClassLoader().getResource(
        "jmetest/data/model/msascii/run.ms3d");
        mi.setBase(TestMilkLoader.class.getClassLoader().getResource(
        "jmetest/data/model/msascii/"));
        Node mi1=mi.load(MSFile);
        mi1.setLocalScale(.1f);
        ByteArrayOutputStream BO=new ByteArrayOutputStream();
        XMLWriter r=new XMLWriter(BO);
        try {
            r.writeScene(mi1);
        } catch (IOException e) {
            System.out.println("Error writting");
        }
        SAXReader sr=new SAXReader();
        Node qq=sr.loadXML(new ByteArrayInputStream(BO.toByteArray()));
        rootNode.attachChild(qq);

    }

}

Test the XMLWriter and SAXReader classes

git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@1173 75d07b2b-3a1a-0410-a2c5-0572b91ccdca


package com.utilities;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mene on 11/27/2016.
 */

public class HttpRequester {

    private String host;
    private Integer port;

    private HttpRequester(){}

    public HttpRequester(String address){

        this();
        host = address.split(":")[0];
        port = Integer.parseInt(address.split(":")[1]);
    }

    public void postRequest(String enpoint, JSONObject params) throws IOException, URISyntaxException {
        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI uriConfig = new URI("http", null, this.host, this.port, enpoint, null, null);
        HttpPost httpPostRequest = new HttpPost(uriConfig);

        StringEntity paramString = new StringEntity(params.toString());
        paramString.setContentType("application/json");
        httpPostRequest.setEntity(paramString);
        CloseableHttpResponse response = httpclient.execute(httpPostRequest);

        try {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                EntityUtils.consume(entity);
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status +", " + response.getStatusLine().getReasonPhrase());
            }

        } finally {
            response.close();
        }
    }

}

Add http request support and first snippet to perform game registration inside the Engine.


/*
 * Transient.java June 2007
 *
 * Copyright (C) 2007, Niall Gallagher <niallg@users.sf.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 */

package simple.xml;

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

/**
 * The Transient annotation is an optional annotation
 * that can be used within an XML class schema to mark a method or
 * field as being transient, which indicates that it does not take
 * part in serialization or deserialization. This is used only as
 * a means to illustrate to the reader of your class that this has
 * not impact on the XML representation of the object. Fields or
 * methods annotated with this will be ignored, as will those that
 * contain no XML annotations.
 *
 * @author Niall Gallagher
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface Transient {
}

Add the optional transient annotation

Add the optional transient annotation


package de.lmu.ifi.dbs.elki.visualization.batikutil;

import org.w3c.dom.Element;

import de.lmu.ifi.dbs.elki.visualization.svg.SVGPlot;

/**
 * This helper class will replace a node in an SVG plot,
 * as soon as the tree is unlocked by the rendering engine.
 *
 * @author Erich Schubert
 *
 */
public class NodeReplacer extends RunWhenReadyAndVisible {
  private SVGPlot plot;
  private String id;
  private Element newe;

  /**
   * Setup a SVG node replacement.
   *
   * @param newe New element
   * @param plot SVG plot to process
   * @param id Node ID to replace
   */
  public NodeReplacer(Element newe, SVGPlot plot, String id) {
    super();
    this.newe = newe;
    this.plot = plot;
    this.id = id;
  }

  @Override
  public void run() {
    Element olde = plot.getIdElement(id);
    if (olde != null) {
      olde.getParentNode().replaceChild(newe, olde);
      plot.putIdElement(id, newe);
    }
  }
}

Add Batik helper to replace a named node in the SVG tree.


package com.google.sps.servlets;

import com.google.sps.tasks.TaskScheduler;
import javax.servlet.http.HttpServlet;

public abstract class QueueServlet extends HttpServlet {
  protected TaskScheduler.Builder getTaskBuilder() {
    return TaskScheduler.builder();
  }
}

Add abstract class with TaskBuilder.Builder getter.


package fi.jgke.tagger.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import fi.jgke.tagger.domain.Tag;
import fi.jgke.tagger.domain.Type;
import fi.jgke.tagger.repository.TagRepository;
import fi.jgke.tagger.repository.TypeRepository;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@WebAppConfiguration
@SpringBootTest
@Transactional
public class HealthTest {

    @Autowired
    private WebApplicationContext webAppContext;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
    }

    @Test
    public void isHealthy() throws Exception {
        mockMvc.perform(get("/health"))
                .andExpect(content().contentType("application/hal+json;charset=UTF-8"))
                .andExpect(jsonPath("$.version").exists())
                .andExpect(jsonPath("$.healthy").value(true));

    }
}

Add simple test for /health

Add simple test for /health


package com.mistraltech.bog.core.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Identifies the property in the builder that the annotated method is a getter for.
 * <p>
 * Useful for overriding defaults assumed by the builder generators.
 */
@Target(METHOD)
@Retention(RUNTIME)
public @interface GetsProperty {
    /**
     * The name of the property to be returned
     *
     * @return the ValueContainer for the property
     */
    String value();
}

Add annotation for identifying a getter method (a method that returns the ValueContainer for a property).


/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 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 org.openqa.selenium.lift;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

/**
 * Interface for objects that provide a context (maintaining any state) for web tests.
 * @author rchatley (Robert Chatley)
 *
 */
public interface TestContext {

	public abstract void goTo(String url);

	public abstract void assertPresenceOf(Finder<WebElement, WebDriver> finder);

	public abstract void assertPresenceOf(
			Matcher<Integer> cardinalityConstraint,
			Finder<WebElement, WebDriver> finder);

	public abstract void type(String input, Finder<WebElement, WebDriver> finder);

	public abstract void clickOn(Finder<WebElement, WebDriver> finder);

	public abstract void waitFor(Finder<WebElement, WebDriver> finder, long timeout);

	public abstract void quit();

}

/*
Copyright 2007-2009 WebDriver committers
Copyright 2007-2009 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 org.openqa.selenium.lift;

import org.hamcrest.Matcher;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.lift.find.Finder;

/**
 * Interface for objects that provide a context (maintaining any state) for web tests.
 * @author rchatley (Robert Chatley)
 *
 */
public interface TestContext {

  void goTo(String url);

  void assertPresenceOf(Finder<WebElement, WebDriver> finder);

  void assertPresenceOf(Matcher<Integer> cardinalityConstraint,
      Finder<WebElement, WebDriver> finder);

  void type(String input, Finder<WebElement, WebDriver> finder);

  void clickOn(Finder<WebElement, WebDriver> finder);

  void waitFor(Finder<WebElement, WebDriver> finder, long timeout);

  void quit();

}

JasonLeyba: Remove unnecessary modifiers and cleanup whitespace.

r12481


package com.redhat.ceylon.compiler.js;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.redhat.ceylon.compiler.typechecker.model.Module;

/** A container for things we need to keep per-module. */
class JsOutput {
    private File outfile;
    private Writer writer;
    private final Set<String> s = new HashSet<String>();
    final Map<String,String> requires = new HashMap<String,String>();
    final MetamodelVisitor mmg;
    protected JsOutput(Module m) throws IOException {
        mmg = new MetamodelVisitor(m);
    }
    protected Writer getWriter() throws IOException {
        if (writer == null) {
            outfile = File.createTempFile("jsout", ".tmp");
            writer = new FileWriter(outfile);
        }
        return writer;
    }
    protected File close() throws IOException {
        writer.close();
        return outfile;
    }
    void addSource(String src) {
        s.add(src);
    }
    Set<String> getSources() { return s; }
}

Move this class out of JsCompiler into its own


package com.sec.ax.restful.utils;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 *
 * @author heesik.jeon
 *
 */

public class FormatHelper {

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

    /**
     * @param object
     * @return
     */
    public static String printPretty(Object object) {

		logger.debug("..");

    	Gson gson = new GsonBuilder().setPrettyPrinting().create();

    	String json = gson.toJson(object);

    	return json;

    }

}

Add util to enable json pretty print

Add util to enable json pretty print


package uk.ac.ebi.quickgo.annotation.validation;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import static uk.ac.ebi.quickgo.annotation.validation.QuickGoValidation.toDb;

/**
 * @author Tony Wardell
 * Date: 10/11/2016
 * Time: 13:22
 * Created with IntelliJ IDEA.
 */
public class ReferenceDBXRefEntityValidation implements ConstraintValidator<ReferenceValidator, String[]> {

    @Autowired
    DBXRefEntityValidation dbxRefEntityValidation;

    //@Value("${annotation.validation.reference.databases}")
    List<String> referenceDatabases = Arrays.asList("pmid","doi","go_ref","reactome");

    @Override public void initialize(ReferenceValidator constraintAnnotation) {}

    @Override public boolean isValid(String[] values, ConstraintValidatorContext context) {
        return values == null ||
                Stream.of(values).allMatch(this::validReference) && dbxRefEntityValidation.isValid(values, context);
    }

    private boolean validReference(String s) {

        if(s == null){
            return false;
        }

        if(s.trim().isEmpty()){
            return false;
        }

        if(!s.contains(":")){
            return true;
        }

        return referenceDatabases.contains(toDb.apply(s));
    }
}

Validate references against OK list of databases.


package fitnesse.testsystems.slim.tables;

import org.junit.Test;

import static org.junit.Assert.*;

public class DisgracerTest {

  @Test
  public void disgraceClassName() {
    assertEquals("classname", Disgracer.disgraceClassName("classname"));
    assertEquals("className", Disgracer.disgraceClassName("className"));
    assertEquals("ClassName", Disgracer.disgraceClassName("class name"));
  }

  @Test
  public void disgraceMethodName() {
    assertEquals("methodName", Disgracer.disgraceMethodName("method name"));
    assertEquals("methodname", Disgracer.disgraceMethodName("methodname"));
    assertEquals("MethodName", Disgracer.disgraceMethodName("Method name"));
  }
}

Add unit test for Disgracer class.

Add unit test for Disgracer class.


/*
 * Copyright © 2015 John H Uckele. All rights reserved.
 */

package io.vivarium.client.task;

import java.nio.channels.NotYetConnectedException;

import org.java_websocket.handshake.ServerHandshake;

import com.fasterxml.jackson.core.JsonProcessingException;

import io.vivarium.client.TaskClient;
import io.vivarium.net.jobs.Job;
import io.vivarium.net.messages.CreateJob;

public class CreateJobTask extends Task
{
    private Job _job;

    public CreateJobTask(Job job)
    {
        _job = job;
    }

    @Override
    public void onOpen(TaskClient client, ServerHandshake handshakedata)
    {
        try
        {
            CreateJob message = new CreateJob(_job);
            client.send(client.getMapper().writeValueAsString(message));
        }
        catch (NotYetConnectedException | JsonProcessingException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onMessage(TaskClient client, String message)
    {
        // No reply expected
        // TODO: We should get an ack, and if we don't get the ack we should resend a CreateJob message periodically.
    }

    @Override
    public void onClose(TaskClient client, int code, String reason, boolean remote)
    {
    }

    @Override
    public void onError(TaskClient client, Exception ex)
    {
    }
}

Create Job task for TaskClient

[7] Create Job task for TaskClient


import java.util.Scanner;

public class CountBitsOne {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int n = scan.nextInt();
        System.out.println(countPositiveBits(n));
    }

    public static int countPositiveBits(int n) {
        int count = 0;

        while (n > 0) {
            if ((n & 1) == 1) {
                count++;
            }
            n >>= 1;
        }

        return count;
    }
}

Solve homework2-problem7: Count of Bits One


package leetcode.restore_ip_addresses;

import java.util.ArrayList;

public class Solution {
	public static final int IP_BYTES = 4;
	public void dfs(ArrayList<String> ans, char[] input, int offset, int length, int[] ipaddr, int depth){
		if(offset == length && depth == IP_BYTES){
			ans.add(ipaddr[0] + "." + ipaddr[1] + "." + ipaddr[2] + "." + ipaddr[3]);
		}else if(offset < length && depth < IP_BYTES){
			ipaddr[depth] = input[offset] - '0';
			dfs(ans, input, offset + 1, length, ipaddr, depth + 1);
			if(offset + 2 <= length){
				int d = (input[offset] - '0') * 10 + (input[offset + 1] - '0');
				if(d >= 10){
					ipaddr[depth] = d;
					dfs(ans, input, offset + 2, length, ipaddr, depth + 1);
				}
			}
			if(offset + 3 <= length){
				int d = (input[offset] - '0') * 100 + (input[offset + 1] - '0') * 10 + (input[offset + 2] - '0');
				if(d >= 100 && d < 256){
					ipaddr[depth] = d;
					dfs(ans, input, offset + 3, length, ipaddr, depth + 1);
				}
			}
		}
	}

	public ArrayList<String> restoreIpAddresses(String s) {
        ArrayList<String> ans = new ArrayList<String>();
        dfs(ans, s.toCharArray(), 0, s.length(), new int[4], 0);
        return ans;
    }

	public static void main(String[] args){
		ArrayList<String> ans = new Solution().restoreIpAddresses("999101");
		for(String s : ans){
			System.err.println(s);
		}
	}
}

Add java solution for 93. Restore IP Addresses

93. Restore IP Addresses: https://leetcode.com/problems/restore-ip-addresses/


package integration;

import com.codeborne.selenide.*;
import org.junit.Before;
import org.junit.Test;

import static com.codeborne.selenide.CollectionCondition.*;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import static com.codeborne.selenide.Selenide.$$;

public class LazyEvaluationTest extends IntegrationTest {

  static SelenideElement h1 = $("h1");
  static SelenideElement button = $("#double-clickable-button");

  static SelenideElement input1 = $$("input").first();
  static SelenideElement input2 = $$("input").last();
  static SelenideElement input3 = $$("input").get(1);

  static ElementsCollection inputs = $$("input").filterBy(visible);

  @Before
  public void openTestPageWithImages() {
    openFile("page_with_jquery.html");
  }

  @Test
  public void singleElementLazyFound() {
    h1.shouldBe(visible);
    button.click();
  }

  @Test
  public void collectionRelatedLazyOperations() {
    input1.shouldBe(visible);
    input2.shouldBe(visible);
    input3.shouldBe(visible);
    inputs.shouldHave(sizeGreaterThanOrEqual(1));
  }

}

Test for lazy evaluations is added (failing at the moment)


/*****************************************************************
JADE - Java Agent DEvelopment Framework is a framework to develop
multi-agent systems in compliance with the FIPA specifications.
Copyright (C) 2000 CSELT S.p.A.

The updating of this file to JADE 2.0 has been partially supported by the IST-1999-10211 LEAP Project

GNU Lesser General Public License

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA  02111-1307, USA.
*****************************************************************/

package jade.domain.KBManagement;

/**
 * @author Elisabetta Cortese - TILab
 *
 */
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.KBManagement.*;

import java.util.Date;

public class DFLeaseManager implements LeaseManager{

	public Date getLeaseTime(Object item){
		if(item instanceof DFAgentDescription){
			return ((DFAgentDescription) item).getLeaseTime();
		}
		else{
			return DEFAULT_LEASE_TIME;
		}
	}

	public void setLeaseTime(Object item, Date lease){

		if(item instanceof DFAgentDescription){
			if(isValid(lease)){
				((DFAgentDescription) item).setLeaseTime(lease);
			}
			else{
				((DFAgentDescription) item).setLeaseTime(DEFAULT_LEASE_TIME);
			}
		}
	}

	public Object grantLeaseTime(Object item){
		// Always grant the requested lease time
		return item;
	}

	public boolean isValid(Date lease){

		if(lease.getTime() >= System.currentTimeMillis() || lease.getTime() == -1)
			return true;
		return false;
	}

}

Implement the lease manager for DF

Implement the lease manager for DF


package leetcode;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

/**
 * https://leetcode.com/problems/lru-cache/
 */
public class Problem146 {
    public static class LRUCache {
        private final Map<Integer, Integer> map = new HashMap<>();
        private final LinkedList<Integer> list = new LinkedList<>();
        private final int capacity;

        public LRUCache(int capacity) {
            this.capacity = capacity;
        }

        public int get(int key) {
            if (map.containsKey(key)) {
                list.addLast(key);
                list.removeFirst();
            }
            return map.getOrDefault(key, -1);
        }

        public void set(int key, int value) {
            if (!map.containsKey(key)) {
                list.addLast(key);
            }
            map.put(key, value);
            if (map.size() -1 == capacity) {
                int removedKey = list.removeFirst();
                map.remove(removedKey);
            }
        }
    }

    public static void main(String[] args) {
        LRUCache lru = new LRUCache(2);
//        lru.set(2, 1);
//        lru.set(1, 1);
//        System.out.println(lru.get(2)); // 1
//        lru.set(4, 1);
//        System.out.println(lru.get(1)); // -1
//        System.out.println(lru.get(2)); // 1
//        lru.set(5, 1);
//        lru.set(6, 1);
//        System.out.println(lru.get(1)); // -1
//        System.out.println(lru.get(2)); // -1
//        System.out.println(lru.get(3)); // -1
//        System.out.println(lru.get(4)); // -1
//        System.out.println(lru.get(5)); // 1
//        System.out.println(lru.get(6)); // 1

        lru.set(2, 1);
        System.out.println("1. " + lru.map);
        System.out.println("1. " + lru.list);
        lru.set(1, 1);
        System.out.println("2. " + lru.map);
        System.out.println("2. " + lru.list);
        lru.set(2, 3);
        System.out.println("3. " + lru.map);
        System.out.println("3. " + lru.list);
        lru.set(4, 1);
        System.out.println("4. " + lru.map);
        System.out.println("4. " + lru.list);
        System.out.println(lru.get(1)); // -1
        System.out.println(lru.get(2)); // 3
        System.out.println("5. " + lru.map);
        System.out.println("5. " + lru.list);
    }
}

Create a skeleton for problem 146

Create a skeleton for problem 146


/*
 * Copyright 2017 The Chromium Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
package io.flutter.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;

public interface AnalyticAction {

  void actionPerformed(AnActionEvent e, String analyticId);
}

Define interface for actions to run with custom analytics


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem79;

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

/**
 * Given an array full of integers implement a merge sort algorithm to sort the content inside
 * the array.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MergeSort extends SortingAlgorithm {

  @Override public void sort(int[] numbers) {

  }
}

Add statement to problem 79

Add statement to problem 79


package guitests;

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

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

import seedu.malitio.commons.exceptions.DataConversionException;
import seedu.malitio.commons.util.ConfigUtil;
import seedu.malitio.model.Malitio;
import seedu.malitio.storage.StorageManager;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;

/**
 * Assumes storage and file utils are working
 *
 */
//@@author a0126633j
public class SaveCommandTest extends MalitioGuiTest {
    private static final String DEFAULT_FILE_NAME = "malitio.xml";
    private static final String TEST_FILE_PATH = "src/test/data/tempDataForSaveCommand/test1/";
    private static final String DEFAULT_FILE_PATH = "src/test/data/tempDataForSaveCommand/";

    // a storage manager to read data from xml file
    private StorageManager storageManager = new StorageManager("random", "random");

    private Malitio original = getInitialData();
    private String originalFilePath;

    @Before
    public void getOriginalFilePath() throws DataConversionException {
        originalFilePath = ConfigUtil.readConfig("./config.json/").get().getMalitioFilePath();
    }

    @Test
    public void save() throws DataConversionException, IOException {

    //save default file location
    commandBox.runCommand("save " + DEFAULT_FILE_PATH);
    assertSaveSuccessful(DEFAULT_FILE_PATH);

    //save in new file location
    commandBox.runCommand("save " + TEST_FILE_PATH);
    assertSaveSuccessful(TEST_FILE_PATH);
    assertFileDeletionSuccessful(DEFAULT_FILE_PATH);

    //save default file location again
    commandBox.runCommand("save " + DEFAULT_FILE_PATH);
    assertSaveSuccessful(DEFAULT_FILE_PATH);
    assertFileDeletionSuccessful(TEST_FILE_PATH);

    //orginal save file location should be preserved after the tests
    ConfigUtil.changeMalitioSaveDirectory(originalFilePath);
    }

    /**
     * Asserts new file is present and consistent with Malitio data
     * @throws DataConversionException
     * @throws IOException
     */
    public void assertSaveSuccessful(String newFileLocation) throws DataConversionException, IOException {
        File f = new File(newFileLocation + DEFAULT_FILE_NAME);
        if(f.exists()) {
            assertEquals(original, new Malitio(storageManager.readMalitio(newFileLocation + DEFAULT_FILE_NAME).get()));
        } else {
            assertTrue(false);
        }
    }

    /**
     * Asserts old file is successfully deleted
     */
    public void assertFileDeletionSuccessful(String oldFileLocation) {
        File f = new File(oldFileLocation + DEFAULT_FILE_NAME);
        assertFalse(f.exists());
    }
}

Add testing for save command

Add testing for save command


// Copyright 2008 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 com.google.gerrit.server;

import com.google.gerrit.client.Gerrit;
import com.google.gwtjsonrpc.client.CookieAccess;
import com.google.gwtjsonrpc.server.ActiveCall;
import com.google.gwtjsonrpc.server.JsonServlet;
import com.google.gwtjsonrpc.server.SignedToken;
import com.google.gwtjsonrpc.server.XsrfException;
import com.google.gwtorm.client.OrmException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

/**
 * Base JSON servlet to ensure the current user is not forged.
 */
public abstract class GerritJsonServlet extends JsonServlet {
  private GerritServer server;

  @Override
  public void init(final ServletConfig config) throws ServletException {
    super.init(config);

    try {
      server = GerritServer.getInstance();
    } catch (OrmException e) {
      throw new ServletException("Cannot configure GerritServer", e);
    } catch (XsrfException e) {
      throw new ServletException("Cannot configure GerritServer", e);
    }
  }

  @Override
  protected SignedToken createXsrfSignedToken() throws XsrfException {
    try {
      return GerritServer.getInstance().getXsrfToken();
    } catch (OrmException e) {
      throw new XsrfException("Cannot configure GerritServer", e);
    }
  }

  @Override
  protected abstract Object createServiceHandle() throws Exception;

  @Override
  protected String xsrfUser(final ActiveCall call) {
    final String idstr = CookieAccess.getTokenText(Gerrit.ACCOUNT_COOKIE);
    return idstr != null ? "account" + idstr : "anonymous";
  }

  @Override
  protected boolean xsrfValidate(final ActiveCall call) throws XsrfException {
    final String usertok = CookieAccess.get(Gerrit.ACCOUNT_COOKIE);
    if (usertok == null || server.getAccountToken().checkToken(usertok, null)) {
      return super.xsrfValidate(call);
    } else {
      LoginServlet.forceLogout(call.getHttpServletResponse());
      return false;
    }
  }
}

Define a base servlet for use within Gerrit RPC servers

This servlet can be subclassed to define the servlet for each
RemoteJsonService implementation needed within Gerrit.

Signed-off-by: Shawn O. Pearce <f3ea74d906fa9fe97c1fef6bad9cb871485c7045@google.com>


package org.matthewjwhite.stata.util;

import com.stata.sfi.SFIToolkit;

public class Conversion {
	public static double real(boolean b) {
		return b ? 1.0 : 0.0;
	}

	public static String string(double x) {
		return SFIToolkit.formatValue(x, "%24.0g").trim();
	}

	public static String string(boolean b) {
		return string(real(b));
	}
}

Add class for converting to Stata values


package com.christofferklang.pyxl;

import com.intellij.psi.tree.TokenSet;
import com.jetbrains.python.PythonDialectsTokenSetContributor;
import com.jetbrains.python.PythonTokenSetContributor;
import org.jetbrains.annotations.NotNull;

public class PyxlTokenSetContributor extends PythonTokenSetContributor {
    @NotNull
    @Override
    public TokenSet getExpressionTokens() {
        return TokenSet.orSet(super.getExpressionTokens(), TokenSet.create(PyxlElementTypes.PYXL_TAG_REFERENCE));
    }
}

Add PYXL_TAG_REFERENCE as a reference token


package com.librato.metrics;

import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import junit.framework.TestCase;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;

import java.io.IOException;
import java.util.SortedMap;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;

public class LibratoReporterTest extends TestCase {

    class FailingRegistry extends MetricRegistry {
        AtomicInteger timesAttempted = new AtomicInteger();

        @Override
        public SortedMap<String, Gauge> getGauges(MetricFilter filter) {
            timesAttempted.addAndGet(1);
            throw new RuntimeException("test-exception");
        }
    }

    public void testIsResilientToExceptionsInReport() throws Exception {
        FailingRegistry registry = new FailingRegistry();
        HttpPoster poster = new HttpPoster() {
            public Future<Response> post(String userAgent, String payload) throws IOException {
                return null;
            }
        };
        LibratoReporter reporter = LibratoReporter.builder(registry, "test-username", "test-token", "test-source")
                .setHttpPoster(poster)
                .build();
        // assert that it doesn't throw an exception
        reporter.report();
        // verify the failure occurred
        Assert.assertThat(registry.timesAttempted.get(), CoreMatchers.equalTo(1));
    }
}

Test case for librato-reporter not failing from report


package ca.ualberta.lard.model;

/**
 * A CommentRequest is a structure that aids in the retrieving of comments. It unifies the arguments passed around, by being a single structure
 * in which the client can say any number of things they expect of the comment they want. All parameters are optional, and if any of them are set
 * it is assumed the user is requesting Comments relevant to that parameter.
 * @author Troy Pavlek
 *
 */
public class CommentRequest {

	/**
	 * The most important parameter. If the CommentRequest contains an ID, then the user is searching for a specific, single comment.
	 */
	private String id;
	/**
	 * If the location property is set, Comments nearest this location will be returned over those further from this location.
	 */
	private GeoLocation location;
	/**
	 * Do we only want to search threads, or are replies acceptable also?
	 */
	private boolean topLevel;
	/**
	 * Do we only want comments with pictures?
	 */
	private boolean hasPicture;
	/**
	 * The number of results we want returned
	 */
	private int resultSize;

	/**
	 * Instantiates the Comment Request
	 * <p>
	 * All the constructor does is instantiates the object with our expected return size. The user should be setting the remainder of the parameters of the
	 * CommentRequest with the available setters.
	 * </p>
	 * @param num The number of results we want. We may get less, but we will never get more.
	 */
	public CommentRequest(int num) {
		this.resultSize = num;
	}

	public void setId(String id) {
		this.id = id;
	}

	public void setLocation(GeoLocation loc) {
		this.location = loc;
	}

	public void onlyThreads() {
		this.topLevel = true;
	}

	public void onlyReplies() {
		this.topLevel = false;
	}

	public void withPictures() {
		this.hasPicture = true;
	}

	public void withoutPictures() {
		this.hasPicture = false;
	}

}

Comment request created. No tests created, because it has literally zero logic. It's a glorified struct


package google.main;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class MessageBuilderTest {

	@Test
	public void testBuilderWithNull() {
		String expected = "Dla zapytania 'foo' Google niczego nie znalazło.";
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(null).build();
		assertEquals(expected, actual);
	}

	@Test
	public void testBuilderWithZero() {
		String expected = "Dla zapytania 'foo' Google niczego nie znalazło.";
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(0L).build();
		assertEquals(expected, actual);
	}

	@Test
	public void testBuilderWithoutFormatting() {
		String expected = "Dla zapytania 'foo' Google znalazło ok. 700 wyników.";
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(700L).build();
		assertEquals(expected, actual);
	}

	@Test
	public void testBuilderWithFormatting() {
		String number = String.format("%,d", 50_000L);
		String expected = String.format("Dla zapytania 'foo' Google znalazło ok. %s wyników.",
				number);
		String actual = new MessageBuilder().withQuery("foo").withNumberOfResults(50_000L).build();
		assertEquals(expected, actual);
	}

}

Add JUnit tests for MessageBuilder.

Add JUnit tests for MessageBuilder.


package com.greenyetilab;

import com.greenyetilab.utils.log.NLog;

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

/**
 * Various file utilities
 */
public class FileUtils {
    public static String readUtf8(final InputStream in) throws IOException {
        InputStreamReader reader = new InputStreamReader(in, "UTF-8");
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[1024];
        while (true) {
            int length = reader.read(buffer);
            if (length == -1) {
                break;
            }
            sb.append(buffer);
        }
        return sb.toString();
    }

    public static void writeUtf8(final OutputStream out, String text) throws IOException {
        byte[] buffer = text.getBytes("UTF-8");
        out.write(buffer);
        out.flush();
    }
}

Add utils to read and write strings from/to files


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

package com.legendzero.lzlib.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Lambdas {

    public static boolean isNull(Object object) {
        return object == null;
    }

    public static boolean notNull(Object object) {
        return object != null;
    }

    public static <T extends Comparable<T>> boolean greaterThan(T object1, T object2) {
        return object1.compareTo(object2) > 0;
    }

    public static <T extends Comparable<T>> boolean lessThan(T object1, T object2) {
        return object1.compareTo(object2) < 0;
    }

    public static <T extends Comparable<T>> boolean greaterThanOrEqual(T object1, T object2) {
        return object1.compareTo(object2) >= 0;
    }

    public static <T extends Comparable<T>> boolean lessThanOrEqual(T object1, T object2) {
        return object1.compareTo(object2) <= 0;
    }
}

Add some common lambda conditions

Add some common lambda conditions