package com.thaiopensource.xml.dtd.app;

import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdParser;
import com.thaiopensource.xml.dtd.om.Dtd;
import com.thaiopensource.xml.dtd.parse.DtdParserImpl;

public class Driver {
  public static void main (String args[]) throws IOException {
    DtdParser dtdParser = new DtdParserImpl();
    Dtd dtd = dtdParser.parse(args[0], new FileEntityManager());
    String enc = EncodingMap.getJavaName(dtd.getEncoding());
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out,
								 enc));
    CharRepertoire cr = CharRepertoire.getInstance(enc);
    new SchemaWriter(new XmlWriter(w, cr)).writeDtd(dtd);
    w.flush();
  }
}

package com.thaiopensource.xml.dtd.app;

import java.io.IOException;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;

import com.thaiopensource.xml.out.CharRepertoire;
import com.thaiopensource.xml.out.XmlWriter;
import com.thaiopensource.xml.util.EncodingMap;
import com.thaiopensource.xml.dtd.om.DtdParser;
import com.thaiopensource.xml.dtd.om.Dtd;
import com.thaiopensource.xml.dtd.parse.DtdParserImpl;

public class Driver {
  public static void main (String args[]) throws IOException {
    DtdParser dtdParser = new DtdParserImpl();
    Dtd dtd = dtdParser.parse(args[0], new FileEntityManager());
    new RelaxNgWriter(null).writeDtd(dtd);
    String enc = EncodingMap.getJavaName(dtd.getEncoding());
    BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out,
								 enc));
    CharRepertoire cr = CharRepertoire.getInstance(enc);
    new SchemaWriter(new XmlWriter(w, cr)).writeDtd(dtd);
    w.flush();
  }
}

Call RelaxNgWriter as a temporary hack.

Call RelaxNgWriter as a temporary hack.


package com.exphc.FreeTrade;

import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.command.*;
import org.bukkit.entity.*;

public class FreeTrade extends JavaPlugin {
    Logger log = Logger.getLogger("Minecraft");

    public void onEnable() {
        log.info("FreeTrade enabled");
    }

    public void onDisable() {
        log.info("FreeTrade disabled");
    }

    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        Player player;
        String wanted, giving;

        if (!cmd.getName().equalsIgnoreCase("want")) {
            return false;
        }

        // /want
        if (args.length == 0) {
            return showOutstanding(sender);
        }

        // /want help
        if (args[0].equalsIgnoreCase("help")) {
            return showHelp(sender);
        }

        if (sender instanceof Player) {
            player = (Player)sender;
        } else {
            // TODO: get player from name as first argument
            sender.sendMessage("this command can only be run by a player");
        }

        if (args.length < 2) {
            return false;
        }

        wanted = args[0];
        if (args[1].equalsIgnoreCase("for")) {
            giving = args[2];
        } else {
            giving = args[1];
        }

        sender.sendMessage("you want " + wanted + " for " + giving);

        return true;
    }

    public boolean showOutstanding(CommandSender sender) {
        sender.sendMessage("TODO: show open orders");

        return false;
    }

    public boolean showHelp(CommandSender sender) {
        sender.sendMessage("TODO: show help");
        // TODO: hook into built-in bukkit help? /help?

        return false;
    }
}

package com.exphc.FreeTrade;

import java.util.logging.Logger;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.command.*;
import org.bukkit.entity.*;

public class FreeTrade extends JavaPlugin {
    Logger log = Logger.getLogger("Minecraft");

    public void onEnable() {
        log.info("FreeTrade enabled");
    }

    public void onDisable() {
        log.info("FreeTrade disabled");
    }

    public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
        Player player;
        String wanted, giving;

        if (!cmd.getName().equalsIgnoreCase("want")) {
            return false;
        }

        // /want
        if (args.length == 0) {
            return showOutstanding(sender);
        }

        if (sender instanceof Player) {
            player = (Player)sender;
        } else {
            // TODO: get player from name as first argument
            sender.sendMessage("this command can only be run by a player");
        }

        if (args.length < 2) {
            return false;
        }

        wanted = args[0];
        if (args[1].equalsIgnoreCase("for")) {
            giving = args[2];
        } else {
            giving = args[1];
        }

        sender.sendMessage("you want " + wanted + " for " + giving);

        return true;
    }

    public boolean showOutstanding(CommandSender sender) {
        sender.sendMessage("TODO: show open orders");

        return false;
    }
}

Remove /want help; already is invalid usage so shows default help


package won.matcher.service.nodemanager.service;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import won.matcher.service.common.event.HintEvent;

/**
 * Created by hfriedrich on 06.07.2016.
 *
 * Currently the hint "database" is just implemented as an in memory bloom filter so that (best guess) duplicate
 * checks are possible to avoid sending duplicate hints. In a future version this might be changed to a persistent
 * hint database.
 */
@Component
@Scope("singleton")
public class HintDBService
{
  private BloomFilter savedHints;

  public HintDBService() {
    savedHints = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 100000, 0.001);
  }

  public void saveHint(HintEvent hint) {
    savedHints.put(getHintIdentificationString(hint));
  }

  public boolean mightHintSaved(HintEvent hint) {
    return savedHints.mightContain(getHintIdentificationString(hint));
  }

  private String getHintIdentificationString(HintEvent hint) {
    return hint.getFromNeedUri() + hint.getFromWonNodeUri() + hint.getToNeedUri() + hint.getToWonNodeUri();
  }
}

package won.matcher.service.nodemanager.service;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import won.matcher.service.common.event.HintEvent;

/**
 * Created by hfriedrich on 06.07.2016.
 *
 * Currently the hint "database" is just implemented as an in memory bloom filter so that (best guess) duplicate
 * checks are possible to avoid sending duplicate hints. In a future version this might be changed to a persistent
 * hint database.
 */
@Component
@Scope("singleton")
public class HintDBService
{
  private BloomFilter savedHints;

  public HintDBService() {
    savedHints = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 100000000, 0.001);
  }

  public void saveHint(HintEvent hint) {
    savedHints.put(getHintIdentificationString(hint));
  }

  public boolean mightHintSaved(HintEvent hint) {
    return savedHints.mightContain(getHintIdentificationString(hint));
  }

  private String getHintIdentificationString(HintEvent hint) {
    return hint.getFromNeedUri() + hint.getFromWonNodeUri() + hint.getToNeedUri() + hint.getToWonNodeUri();
  }
}

Make duplicate match filter less likely to produce false positives


package edu.oregonstate.cope.clientRecorder;

import static org.junit.Assert.*;

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

import edu.oregonstate.cope.tests.util.StubFileProvider;

public class RecorderPropertiesTest {

	private RecorderProperties properties;
	private StubFileProvider fileProvider;

	@Before
	public void setup() {
		fileProvider = new StubFileProvider();
		properties = new RecorderProperties(fileProvider);
	}

	@Test
	public void testAddNull() {
		properties.addProperty(null, null);
		assertNull(properties.getProperty(null), null);
		assertTrue(fileProvider.isCurrentFileEmpty());
	}

	@Test
	public void testAddEmpty() throws Exception {
		properties.addProperty("", "");
		assertTrue(fileProvider.isCurrentFileEmpty());
	}

	@Test
	public void testAddNonEmpty() throws Exception {
		properties.addProperty("k", "v");
		assertEquals("v", properties.getProperty("k"));
		assertEquals("v", new RecorderProperties(fileProvider).getProperty("k"));
	}
}

package edu.oregonstate.cope.clientRecorder;

import static org.junit.Assert.*;

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

import edu.oregonstate.cope.tests.util.StubFileProvider;

public class RecorderPropertiesTest {

	private RecorderProperties properties;
	private StubFileProvider fileProvider;

	@Before
	public void setup() {
		fileProvider = new StubFileProvider();
		properties = new RecorderProperties(fileProvider);
	}

	@Test
	public void testAddNull() {
		properties.addProperty(null, null);
		assertNull(properties.getProperty(null), null);
		assertTrue(fileProvider.isCurrentFileEmpty());
	}

	@Test
	public void testAddEmpty() throws Exception {
		properties.addProperty("", "");
		assertTrue(fileProvider.isCurrentFileEmpty());
	}

	@Test
	public void testAddOneKey() throws Exception {
		properties.addProperty("k", "v");
		testForKey("k", "v");
	}

	@Test
	public void testAddTwoKeys() throws Exception {
		properties.addProperty("k1", "v1");
		properties.addProperty("k2", "v2");

		testForKey("k1", "v1");
		testForKey("k2", "v2");
	}

	private void testForKey(String key, String value) {
		assertEquals(value, properties.getProperty(key));
		assertEquals(value, new RecorderProperties(fileProvider).getProperty(key));
	}
}

Test for multiple key insertions added

Test for multiple key insertions added


package io.quarkus.elytron.security.runtime;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

/**
 *
 */
@ConfigRoot(phase = ConfigPhase.RUN_TIME)
public final class SecurityConfig {
    /**
     * The configuration for the {@linkplain org.wildfly.security.auth.realm.LegacyPropertiesSecurityRealm}
     */
    @ConfigItem
    public PropertiesRealmConfig file;
    /**
     * The configuration for the {@linkplain org.wildfly.security.auth.realm.SimpleMapBackedSecurityRealm}
     */
    @ConfigItem
    public MPRealmConfig embedded;
}

package io.quarkus.elytron.security.runtime;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigPhase;
import io.quarkus.runtime.annotations.ConfigRoot;

/**
 *
 */
@ConfigRoot(phase = ConfigPhase.BUILD_AND_RUN_TIME_FIXED)
public final class SecurityConfig {
    /**
     * The configuration for the {@linkplain org.wildfly.security.auth.realm.LegacyPropertiesSecurityRealm}
     */
    @ConfigItem
    public PropertiesRealmConfig file;
    /**
     * The configuration for the {@linkplain org.wildfly.security.auth.realm.SimpleMapBackedSecurityRealm}
     */
    @ConfigItem
    public MPRealmConfig embedded;
}

Make security config be fixed at build time


package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Delete the session cookie and sign out user
@WebServlet("/sign-out")
public class Logout extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    final int maxAge = 0;
    Cookie newCookie = new Cookie("session", " ");
    newCookie.setMaxAge(maxAge); // Set the expiration date to immediate deletion
    response.addCookie(newCookie);
    response.sendRedirect("/index.html"); // Go back to the main page
  }
}

package com.google.sps.servlets;

import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// Delete the session cookie and sign out user
@WebServlet("/sign-out")
public class Logout extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    final int maxAge = 0;
    Cookie newCookie = new Cookie("session", "");
    newCookie.setMaxAge(maxAge); // Set the expiration date to immediate deletion
    response.addCookie(newCookie);
    response.sendRedirect("/index.html"); // Go back to the main page
  }
}

Set session cookie to an empty string w/o space.


/*
 *  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.tomcat.util.net;

public class Constants {

    /**
     * Name of the system property containing
     * the tomcat instance installation path
     */
    public static final String CATALINA_BASE_PROP = "catalina.base";

    /**
     * Has security been turned on?
     */
    public static final boolean IS_SECURITY_ENABLED =
        (System.getSecurityManager() != null);
}

/*
 *  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.tomcat.util.net;

public class Constants {

    /**
     * Name of the system property containing
     * the tomcat instance installation path
     */
    public static final String CATALINA_BASE_PROP = "catalina.base";
}

Remove unused code identified by the UCDetector

git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1636563 13f79535-47bb-0310-9956-ffa450edef68


package com.atlassian.pageobjects.elements.test.pageobjects.page;

import com.atlassian.pageobjects.Page;
import com.atlassian.pageobjects.elements.Element;
import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.ElementFinder;

import javax.inject.Inject;

import static com.atlassian.pageobjects.elements.query.TimedAssertions.assertTrueByDefaultTimeout;

/**
 * Represents the dynamicpage.html page
 */
public class DynamicPage implements Page
{
    @ElementBy(id = "nameTextBox")
    Element nameTextBox;

    @ElementBy(id = "helloWorldButton")
    Element helloWorldButton;

    @ElementBy(id = "messageSpan")
    Element messageSpan;

    @ElementBy(id = "createFieldSetButton")
    Element createFieldSetButton;

    @Inject
    ElementFinder elementFinder;

    public String getUrl()
    {
         return "/html/dynamicpage.html";
    }

    public DynamicPage createFieldSet()
    {
        createFieldSetButton.click();
        assertTrueByDefaultTimeout(nameTextBox.timed().isVisible());
        return this;
    }

    public DynamicPage helloWorld(String name)
    {
        nameTextBox.clear().type(name);
        helloWorldButton.click();
        assertTrueByDefaultTimeout(messageSpan.timed().isVisible());
        return this;
    }

    public String getMessage()
    {
        return messageSpan.getText();
    }

    public ElementFinder getElementFinder()
    {
        return elementFinder;
    }
}

package com.atlassian.pageobjects.elements.test.pageobjects.page;

import com.atlassian.pageobjects.Page;
import com.atlassian.pageobjects.elements.Element;
import com.atlassian.pageobjects.elements.ElementBy;
import com.atlassian.pageobjects.elements.ElementFinder;

import javax.inject.Inject;

import static com.atlassian.pageobjects.elements.query.Poller.waitUntilTrue;

/**
 * Represents the dynamicpage.html page
 */
public class DynamicPage implements Page
{
    @ElementBy(id = "nameTextBox")
    Element nameTextBox;

    @ElementBy(id = "helloWorldButton")
    Element helloWorldButton;

    @ElementBy(id = "messageSpan")
    Element messageSpan;

    @ElementBy(id = "createFieldSetButton")
    Element createFieldSetButton;

    @Inject
    ElementFinder elementFinder;

    public String getUrl()
    {
         return "/html/dynamicpage.html";
    }

    public DynamicPage createFieldSet()
    {
        createFieldSetButton.click();
        waitUntilTrue(nameTextBox.timed().isVisible());
        return this;
    }

    public DynamicPage helloWorld(String name)
    {
        nameTextBox.clear().type(name);
        helloWorldButton.click();
        waitUntilTrue(messageSpan.timed().isVisible());
        return this;
    }

    public String getMessage()
    {
        return messageSpan.getText();
    }

    public ElementFinder getElementFinder()
    {
        return elementFinder;
    }
}

Fix compilation error from previous checkin.


/*
 * Copyright 2021 Wultra s.r.o.
 *
 * 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.getlime.security.powerauth.lib.nextstep.model.response;

import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.OtpStatus;
import lombok.Data;

import javax.validation.constraints.NotNull;

/**
 * Response object used for creating an OTP.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
@Data
public class CreateOtpResponse {

    @NotNull
    private String otpName;
    @NotNull
    private String userId;
    @NotNull
    private String otpId;
    @NotNull
    private String otpValue;
    @NotNull
    private OtpStatus otpStatus;

}

/*
 * Copyright 2021 Wultra s.r.o.
 *
 * 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.getlime.security.powerauth.lib.nextstep.model.response;

import io.getlime.security.powerauth.lib.nextstep.model.entity.enumeration.OtpStatus;
import lombok.Data;

import javax.validation.constraints.NotNull;

/**
 * Response object used for creating an OTP.
 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
@Data
public class CreateOtpResponse {

    @NotNull
    private String otpName;
    private String userId;
    @NotNull
    private String otpId;
    @NotNull
    private String otpValue;
    @NotNull
    private OtpStatus otpStatus;

}

Allow OTP creation without user ID

Allow OTP creation without user ID


package net.sf.jabref.gui.help;

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

import org.junit.Test;

import static junit.framework.TestCase.assertEquals;

public class HelpFileTest {
    private final String jabrefHelp = "http://help.jabref.org/en/";
    @Test
    public void referToValidPage() throws IOException {
        for (HelpFile help : HelpFile.values()) {
            URL url = new URL(jabrefHelp + help.getPageName());
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            assertEquals(200, http.getResponseCode());
        }
    }
}

package net.sf.jabref.gui.help;

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

import org.junit.Test;

import static junit.framework.TestCase.assertEquals;

public class HelpFileTest {
    private final String jabrefHelp = "http://help.jabref.org/en/";
    @Test
    public void referToValidPage() throws IOException {
        for (HelpFile help : HelpFile.values()) {
            URL url = new URL(jabrefHelp + help.getPageName());
            HttpURLConnection http = (HttpURLConnection) url.openConnection();
            http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64)");
            assertEquals(200, http.getResponseCode());
        }
    }
}

Set user agent to fix 403 status error

Set user agent to fix 403 status error


package com.thaiopensource.relaxng;

import org.xml.sax.Locator;
import com.thaiopensource.datatype.Datatype;

class ValuePattern extends SimplePattern {
  String str;
  Datatype dt;

  ValuePattern(Datatype dt, String str, Locator locator) {
    super(combineHashCode(VALUE_HASH_CODE, str.hashCode()), locator);
    this.str = str;
  }

  boolean matches(Atom a) {
    return a.matchesDatatypeValue(dt, str);
  }

  boolean samePattern(Pattern other) {
    if (getClass() != other.getClass())
      return false;
    return (dt.equals(((ValuePattern)other).dt)
	    && str.equals(((ValuePattern)other).str));
  }

  void accept(PatternVisitor visitor) {
    visitor.visitValue(dt, str);
  }
}

package com.thaiopensource.relaxng;

import org.xml.sax.Locator;
import com.thaiopensource.datatype.Datatype;

class ValuePattern extends SimplePattern {
  String str;
  Datatype dt;

  ValuePattern(Datatype dt, String str, Locator locator) {
    super(combineHashCode(VALUE_HASH_CODE, str.hashCode()), locator);
    this.dt = dt;
    this.str = str;
  }

  boolean matches(Atom a) {
    return a.matchesDatatypeValue(dt, str);
  }

  boolean samePattern(Pattern other) {
    if (getClass() != other.getClass())
      return false;
    if (!(other instanceof ValuePattern))
      return false;
    return (dt.equals(((ValuePattern)other).dt)
	    && str.equals(((ValuePattern)other).str));
  }

  void accept(PatternVisitor visitor) {
    visitor.visitValue(dt, str);
  }
}

Fix a couple of bugs.

Fix a couple of bugs.


package interpres.ast;

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

import interpres.language.DefinitionTable;
import interpres.language.values.Value;

public class StringLiteral extends AST {
  private String literal;

  public StringLiteral(String literal) {
    this.literal = literal;
  }

  public Value evaluate(DefinitionTable definitionTable) {
    List<String> instructions = new ArrayList<String>();

    for (int i = literal.length() - 1; i >= 0; i--) {
      instructions.add("LOADL " + (int) literal.charAt(i));
    }

    return new interpres.language.values.List(instructions);
  }

  public String quote() {
    return this.literal;
  }
}

package interpres.ast;

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

import interpres.language.DefinitionTable;
import interpres.language.values.Value;

public class StringLiteral extends AST {
  private String literal;

  public StringLiteral(String literal) {
    this.literal = literal;
  }

  public Value evaluate(DefinitionTable definitionTable) {
    return ListExpression.buildFunctionCall("asm.loads", new QuotedExpression(this)).evaluate(definitionTable);
  }

  public String quote() {
    return this.literal;
  }
}

Call asm.loads when a string is encountered


package redis.clients.jedis;

import java.io.IOException;
import java.net.UnknownHostException;

import redis.clients.util.FixedResourcePool;

public class JedisPool extends FixedResourcePool<Jedis> {
    private String host;
    private int port;
    private int timeout;

    public JedisPool(String host) {
	this.host = host;
	this.port = Protocol.DEFAULT_PORT;
    }

    public JedisPool(String host, int port) {
	this.host = host;
	this.port = port;
    }

    public JedisPool(String host, int port, int timeout) {
	this.host = host;
	this.port = port;
	this.timeout = timeout;
    }

    @Override
    protected Jedis createResource() {
	Jedis jedis = new Jedis(this.host, this.port, this.timeout);
	try {
	    jedis.connect();
	} catch (UnknownHostException e) {
	    throw new JedisException(e);
	} catch (IOException e) {
	    throw new JedisException(e);
	}
	return jedis;
    }

    @Override
    protected void destroyResource(Jedis jedis) {
	jedis.quit();
	try {
	    jedis.disconnect();
	} catch (IOException e) {
	    throw new JedisException(e);
	}
    }

    @Override
    protected boolean isResourceValid(Jedis jedis) {
	return jedis.ping().equals("OK");
    }
}

package redis.clients.jedis;

import java.io.IOException;
import java.net.UnknownHostException;

import redis.clients.util.FixedResourcePool;

public class JedisPool extends FixedResourcePool<Jedis> {
    private String host;
    private int port;
    private int timeout;

    public JedisPool(String host) {
	this.host = host;
	this.port = Protocol.DEFAULT_PORT;
    }

    public JedisPool(String host, int port) {
	this.host = host;
	this.port = port;
    }

    public JedisPool(String host, int port, int timeout) {
	this.host = host;
	this.port = port;
	this.timeout = timeout;
    }

    @Override
    protected Jedis createResource() {
	Jedis jedis = new Jedis(this.host, this.port, this.timeout);
	try {
	    jedis.connect();
	} catch (UnknownHostException e) {
	    throw new JedisException(e);
	} catch (IOException e) {
	    throw new JedisException(e);
	}
	return jedis;
    }

    @Override
    protected void destroyResource(Jedis jedis) {
	jedis.quit();
	try {
	    jedis.disconnect();
	} catch (IOException e) {
	    throw new JedisException(e);
	}
    }

    @Override
    protected boolean isResourceValid(Jedis jedis) {
	return jedis.ping().equals("PONG");
    }
}

Fix for GH-4, isResourceValid should check for PONG not OK


package com.nincraft.ninbot.command;

import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class DabCommand extends AbstractCommand {

    public DabCommand() {
        length = 3;
        name = "dab";
        description = "Adds all dab emojis to the last message of the user named";
    }

    @Override
    public void executeCommand(MessageReceivedEvent event) {
        val content = event.getMessage().getContent();
        if (isCommandLengthCorrect(content)) {
            val channel = event.getChannel();
            val dabUser = content.split(" ")[2];
            int count = 0;
            int maxDab = 10;
            for (Message message : channel.getIterableHistory()) {
                if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) {
                    dabOnMessage(message);
                    break;
                }
                if (count >= maxDab) {
                    MessageUtils.reactUnsuccessfulResponse(event.getMessage());
                    break;
                }
                count++;
            }
        } else {
            MessageUtils.reactUnsuccessfulResponse(event.getMessage());
        }
    }

    private void dabOnMessage(Message message) {
        val guild = message.getGuild();

        for (val emote : guild.getEmotes()) {
            if (emote.getName().contains("dab")) {
                MessageUtils.addReaction(message, emote);
            }
        }
    }
}

package com.nincraft.ninbot.command;

import com.nincraft.ninbot.util.MessageUtils;
import lombok.val;
import net.dv8tion.jda.core.entities.Message;
import net.dv8tion.jda.core.events.message.MessageReceivedEvent;

public class DabCommand extends AbstractCommand {

    public DabCommand() {
        length = 3;
        name = "dab";
        description = "Adds all dab emojis to the last message of the user named";
    }

    @Override
    public void executeCommand(MessageReceivedEvent event) {
        val content = event.getMessage().getContent();
        if (isCommandLengthCorrect(content)) {
            val channel = event.getChannel();
            val dabUser = content.split(" ")[2].replaceFirst("@", "");
            int count = 0;
            int maxDab = 10;
            for (Message message : channel.getIterableHistory()) {
                if (message.getAuthor().getName().equalsIgnoreCase(dabUser)) {
                    dabOnMessage(message);
                    break;
                }
                if (count >= maxDab) {
                    MessageUtils.reactUnsuccessfulResponse(event.getMessage());
                    break;
                }
                count++;
            }
        } else {
            MessageUtils.reactUnsuccessfulResponse(event.getMessage());
        }
    }

    private void dabOnMessage(Message message) {
        val guild = message.getGuild();

        for (val emote : guild.getEmotes()) {
            if (emote.getName().contains("dab")) {
                MessageUtils.addReaction(message, emote);
            }
        }
    }
}

Remove @ from user on Dab command

Remove @ from user on Dab command


package novoda.lib.sqliteprovider.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;

/**
 * Parsing .sql files and get single statements suitable for insertion.
 */
public class SQLFile {

    private BufferedReader reader;

    private List<String> statements;

    private boolean inComment = false;

    public void parse(Reader in) throws IOException {
        reader = new BufferedReader(in);
        statements = new ArrayList<String>();
        String line = null;
        while ((line = reader.readLine()) != null) {
            line.trim();
            if (line.length() == 0) {
                continue;
            }
            if (line.startsWith("--"))
                continue;

            if (line.startsWith("/*")) {
                inComment = true;
                continue;
            }

            if (line.endsWith("*/") && inComment == true) {
                inComment = false;
                continue;
            }

            if (inComment == true)
                continue;

            statements.add(line);
        }
        reader.close();
    }

    public List<String> getStatements() {
        return statements;
    }

    public static List<String> statementsFrom(Reader reader) throws IOException {
        SQLFile file = new SQLFile();
        file.parse(reader);
        return file.getStatements();
    }

    public static List<String> statementsFrom(File sqlfile) throws IOException {
        FileReader reader = new FileReader(sqlfile);
        SQLFile file = new SQLFile();
        file.parse(reader);
        return file.getStatements();
    }
}

package novoda.lib.sqliteprovider.util;

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

/**
 * Parsing .sql files and get single statements suitable for insertion.
 */
public class SQLFile {

    private BufferedReader reader;

    private List<String> statements;

    private boolean inComment = false;

    public void parse(Reader in) throws IOException {
        reader = new BufferedReader(in);
        statements = new ArrayList<String>();
        String line = null;
        while ((line = reader.readLine()) != null) {
            line = line.trim();
            if (line.length() == 0) {
                continue;
            }
            if (line.startsWith("--"))
                continue;

            if (line.startsWith("/*")) {
                inComment = true;
                continue;
            }

            if (line.endsWith("*/") && inComment == true) {
                inComment = false;
                continue;
            }

            if (inComment == true)
                continue;

            statements.add(line);
        }
        reader.close();
    }

    public List<String> getStatements() {
        return statements;
    }

    public static List<String> statementsFrom(Reader reader) throws IOException {
        SQLFile file = new SQLFile();
        file.parse(reader);
        return file.getStatements();
    }

    public static List<String> statementsFrom(File sqlfile) throws IOException {
        FileReader reader = new FileReader(sqlfile);
        SQLFile file = new SQLFile();
        file.parse(reader);
        return file.getStatements();
    }
}

Fix for line trimming so it is actually in use


public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(String...args){}

  public static String readFile()

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

public class Wift {

  /**
   *  Wift - The BASIC Programming Language
   *
   *        BASIC FUNCTIONALITY:
   *            - STRINGS []
   *            - INTEGERS []
   *            - ARITHMETIC []
   *            - VARIABLES []
   *
   *        FUNCTIONS:
   *            - PRINT []
   *            - INPUT []
   *            - IF []
   *            - FOR []
   *
   *
   */

  public static void main(String...args){}

  public static String readFile(String filePath)

  //        #readFile() -> char content
  //        #tokenize() -> list
  //        #parse()    -> symbol table

}

Set "String filePath" for "readFile()" :mag:


/**
 * Copyright (c) 2015 Spotify AB.
 *
 * 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.spotify.sshagentproxy;

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

public interface AgentProxy extends Closeable {

  /**
   * Get a list of public keys from the ssh-agent.
   * @return A list of {@link Identity}
   */
  List<Identity> list() throws IOException;

  /**
   * Ask the ssh-agent to sign some data in the form of an array of bytes.
   * @param identity    An array of bytes for data to be signed.
   * @param data        An array of bytes for data to be signed.
   * @return            An array of bytes of signed data.
   */
  byte[] sign(final Identity identity, final byte[] data) throws IOException;
}

/**
 * Copyright (c) 2015 Spotify AB.
 *
 * 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.spotify.sshagentproxy;

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

public interface AgentProxy extends Closeable {

  /**
   * Get a list of public keys from the ssh-agent.
   * @return A list of {@link Identity}
   */
  List<Identity> list() throws IOException;

  /**
   * Ask the ssh-agent to hash and sign some data in the form of an array of bytes.
   *
   * According to the ssh-agent specs:
   * "Upon receiving this request, the agent will look up the private key that
   * corresponds to the public key contained in key_blob. It will use this
   * private key to sign the "data" and produce a signature blob using the
   * key type-specific method described in RFC 4253 section 6.6 "Public Key
   * Algorithms".
   * @param identity    An array of bytes for data to be signed.
   * @param data        An array of bytes for data to be signed.
   * @return            An array of bytes of signed data.
   */
  byte[] sign(final Identity identity, final byte[] data) throws IOException;
}

Update java docs for sign()

Update java docs for sign()


package storm2013.commands;

import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;
import storm2013.Robot;

/**
 * Spins up the firing wheel.
 * @author evan1026
 */
public class SpinUp extends Command {
    private Timer _onTargetTimer = new Timer();

    /**
     * Creates a new instance blahdy blahdy blah.
     */
    public SpinUp(){
        requires(Robot.shooter);
    }

    /**
     * {@inheritDoc}
     */
    protected void initialize() {
        Robot.shooter.getPIDController().setSetpoint(3400);
        Robot.shooter.getPIDController().enable();
        _onTargetTimer.start();
        _onTargetTimer.reset();
    }

    /**
     * {@inheritDoc}
     */
    protected void execute() {
    }

    /**
     * {@inheritDoc}
     */
    protected boolean isFinished() {
        return Robot.shooter.getPIDController().onTarget();
    }

    /**
     * {@inheritDoc}
     */
    protected void end() {
    }

    /**
     * {@inheritDoc}
     */
    protected void interrupted() {
        end();
    }
}

package storm2013.commands;

import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.command.Command;
import storm2013.Robot;

/**
 * Spins up the firing wheel.
 * @author evan1026
 */
public class SpinUp extends Command {
    private Timer _onTargetTimer = new Timer();

    /**
     * Creates a new instance blahdy blahdy blah.
     */
    public SpinUp(){
        requires(Robot.shooter);
    }

    /**
     * {@inheritDoc}
     */
    protected void initialize() {
        Robot.shooter.getPIDController().setSetpoint(3400);
        Robot.shooter.getPIDController().enable();
        _onTargetTimer.start();
        _onTargetTimer.reset();
    }

    /**
     * {@inheritDoc}
     */
    protected void execute() {
        if(!Robot.shooter.onTarget()) {
            _onTargetTimer.reset();
        }
    }

    /**
     * {@inheritDoc}
     */
    protected boolean isFinished() {
        return _onTargetTimer.get() > 0.3;
    }

    /**
     * {@inheritDoc}
     */
    protected void end() {
    }

    /**
     * {@inheritDoc}
     */
    protected void interrupted() {
        end();
    }
}

Add timer for spin up finish

Add timer for spin up finish


package calculator;

public interface CalculatorIF {
    /**
     * @return Given two integers, m and n, returns the result of m/n
     */
    int divide(int m, int n);
    /**
     * @return Given two integers, m and n, returns the result of m*n
     */
    int multiply(int m, int n);
    /**
     * @returs Given two integers, m and n, returns the result of m+n
     */
    int sum(int m, int n);
}

package calculator;

public interface CalculatorIF {
    /**
     * @return Given two integers, m and n, returns the result of m/n
     */
    int divide(int m, int n);
    /**
     * @return Given two integers, m and n, returns the result of m*n
     */
    int multiply(int m, int n);

    /**
     * @return Given two integers, m and n, returns the result of m-n
     */
    int subtract(int m, int n);
    /**
     * @returs Given two integers, m and n, returns the result of m+n
     */
    int sum(int m, int n);
}

Add subtract to the Calculator interface


package som.langserv;

import java.util.function.Consumer;

import io.typefox.lsapi.MessageParams;
import io.typefox.lsapi.ShowMessageRequestParams;
import io.typefox.lsapi.services.WindowService;

public class SomWindow implements WindowService {

  @Override
  public void onShowMessage(final Consumer<MessageParams> callback) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onShowMessageRequest(final Consumer<ShowMessageRequestParams> callback) {
    // TODO Auto-generated method stub
  }

  @Override
  public void onLogMessage(final Consumer<MessageParams> callback) {
    // TODO Auto-generated method stub
  }
}

package som.langserv;

import java.util.function.Consumer;

import io.typefox.lsapi.MessageParams;
import io.typefox.lsapi.ShowMessageRequestParams;
import io.typefox.lsapi.services.WindowService;

public class SomWindow implements WindowService {

  private Consumer<MessageParams> showCallback;
  private Consumer<MessageParams> logCallback;
  private Consumer<ShowMessageRequestParams> showRequestCallback;

  @Override
  public void onShowMessage(final Consumer<MessageParams> callback) {
    this.showCallback = callback;
  }

  @Override
  public void onShowMessageRequest(final Consumer<ShowMessageRequestParams> callback) {
    this.showRequestCallback = callback;
  }

  @Override
  public void onLogMessage(final Consumer<MessageParams> callback) {
    this.logCallback = callback;
  }

  public void show(final MessageParams msg) {
    if (showCallback == null) {
      ServerLauncher.logErr("[SomWindow] showCallback == null on show(.)");
      return;
    }

    showCallback.accept(msg);
  }

  public void log(final MessageParams msg) {
    if (logCallback == null) {
      ServerLauncher.logErr("[SomWindow] logCallback == null on log(.)");
      return;
    }

    logCallback.accept(msg);
  }
}

Implement sending of UI messages and logs to IDE

Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>


package nl.r0b3rtk.jmoribus.spring;

public class SpringRunner {

    public SpringRunner()
    {
        // default constructor
    }
}

package nl.r0b3rtk.jmoribus.spring;

public class SpringRunner {

    public SpringRunner(String applicationContextLocation)
    {
        // default constructor
    }
}

Add default constructor to test Travis

Add default constructor to test Travis


package com.google.sps.tool;

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

import com.google.sps.tool.GoogleTranslate;

public class GoogleTranslateTest {

  @Test
  public void translateHelloToSpanish() {
    assertEquals("Hola", GoogleTranslate.translateText("hello", "es"));
  }

  @Test
  public void translateHelloToVietnamese() {
    assertEquals("xin chào", GoogleTranslate.translateText("hello", "vi"));
  }

  @Test
  public void translateHelloToChineseTraditional() {
    assertEquals("你好", GoogleTranslate.translateText("hello", "zh-CN"));
  }

  @Test
  public void translateHelloToJapanese() {
    assertEquals("こんにちは", GoogleTranslate.translateText("hello", "ja"));
  }
}

package com.google.sps.tool;

import org.junit.Test;
import org.junit.Assert;
import static org.junit.Assert.assertNotNull;
import com.google.sps.tool.GoogleTranslate;

public class GoogleTranslateTest {

  @Test
  public void translateHelloToSpanish() {
    assertNotNull(GoogleTranslate.translateText("hello", "es"));
  }

  @Test
  public void translateHelloToVietnamese() {
    assertNotNull(GoogleTranslate.translateText("hello", "vi"));
  }

  @Test
  public void translateHelloToChineseTraditional() {
    assertNotNull(GoogleTranslate.translateText("hello", "zh-CN"));
  }

  @Test
  public void translateHelloToJapanese() {
    assertNotNull(GoogleTranslate.translateText("hello", "ja"));
  }
}

Add assertNotNull instead to isolate dependency on API result


package ryhma57.references;

import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;

public class Book extends Reference {
    private static EnumSet<BibtexReferenceField> existingFields;
    private static EnumSet<BibtexReferenceField> requiredFields;

    static {
        EnumSet<BibtexReferenceField> optionals;
        Book.requiredFields = Reference.createFieldSet(AUTHOR,
                TITLE, YEAR, PUBLISHER);
        optionals = Reference.createFieldSet(VOLUME,
                NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);

        Book.existingFields = Reference.createExistingSet(
                Book.requiredFields, optionals);
    }

    public Book(String id, String author, String title, String year, String publisher) {
        super(existingFields, requiredFields, "book");
        setID(id);
        setField(AUTHOR, author);
        setField(TITLE, title);
        setField(YEAR, year);
        setField(PUBLISHER, publisher);
    }
}

package ryhma57.references;

import java.util.EnumSet;
import ryhma57.backend.BibtexReferenceField;
import static ryhma57.backend.BibtexReferenceField.*;

public class Book extends Reference {
    private static EnumSet<BibtexReferenceField> existingFields;
    private static EnumSet<BibtexReferenceField> requiredFields, optionalFields;

    static {
        Book.requiredFields = Reference.createFieldSet(AUTHOR,
                TITLE, YEAR, PUBLISHER);
        Book.optionalFields = Reference.createFieldSet(VOLUME,
                NUMBER, SERIES, ADDRESS, EDITION, MONTH, NOTE);
        Book.existingFields = Reference.createExistingSet(
                Book.requiredFields, Book.optionalFields);
    }

    public Book(String id, String author, String title, String year, String publisher) {
        super(existingFields, requiredFields, "book");
        setID(id);
        setField(AUTHOR, author);
        setField(TITLE, title);
        setField(YEAR, year);
        setField(PUBLISHER, publisher);
    }
    public Book() {
        super(existingFields, requiredFields, "book");
    }
}

Simplify the book class even more.

Simplify the book class even more.


package nu.studer.gradle.rocker;

import org.gradle.api.Project;

import java.util.Objects;

final class RockerVersion {

    private static final String PROJECT_PROPERTY = "rockerVersion";
    private static final String DEFAULT = "1.2.2";

    private final String versionString;

    private RockerVersion(String versionString) {
        this.versionString = versionString;
    }

    static void applyDefaultVersion(Project project) {
        project.getExtensions().getExtraProperties().set(PROJECT_PROPERTY, DEFAULT);
    }

    static RockerVersion fromProject(Project project) {
        return from(Objects.requireNonNull(project.getExtensions().getExtraProperties().get(PROJECT_PROPERTY)).toString());
    }

    private static RockerVersion from(String versionString) {
        return new RockerVersion(versionString);
    }

    String asString() {
        return versionString;
    }

}

package nu.studer.gradle.rocker;

import org.gradle.api.Project;

import java.util.Objects;

final class RockerVersion {

    private static final String PROJECT_PROPERTY = "rockerVersion";
    private static final String DEFAULT = "1.3.0";

    private final String versionString;

    private RockerVersion(String versionString) {
        this.versionString = versionString;
    }

    static void applyDefaultVersion(Project project) {
        project.getExtensions().getExtraProperties().set(PROJECT_PROPERTY, DEFAULT);
    }

    static RockerVersion fromProject(Project project) {
        return from(Objects.requireNonNull(project.getExtensions().getExtraProperties().get(PROJECT_PROPERTY)).toString());
    }

    private static RockerVersion from(String versionString) {
        return new RockerVersion(versionString);
    }

    String asString() {
        return versionString;
    }

}

Set Rocker default version to 1.3.0

Set Rocker default version to 1.3.0


package com.bookbase.app.model.dao;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;

import com.bookbase.app.model.entity.Book;

import java.util.List;

@Dao
public interface BookDao {

    @Insert
    void insertAll(List<Book> books);

    @Insert
    long insert(Book book);

    @Query("SELECT * FROM Book")
    List<Book> getBooks();

    @Query("SELECT * FROM Book where bookId = :id")
    Book getSingleBook(int id);

    @Query("DELETE FROM Book")
    void deleteAll();

    @Update
    int update(Book book);

    @Delete
    int deleteBook(Book book);

}

package com.bookbase.app.model.dao;

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;

import com.bookbase.app.model.entity.Book;

import java.util.List;

@Dao
public interface BookDao {

    @Insert
    void insertAll(List<Book> books);

    @Insert
    long insert(Book book);

    @Query("SELECT * FROM Book")
    List<Book> getBooks();

    @Query("SELECT * FROM Book where bookId = :id")
    Book getSingleBook(int id);

    @Query("DELETE FROM Book")
    void deleteAll();

    @Update
    int update(Book book);

    @Delete
    void deleteBook(Book book);

}

Change return type of deletedBook as was never used


package lucene4ir.predictor.pre;

import lucene4ir.predictor.PreQPPredictor;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.Query;

import java.io.IOException;

/**
 * Created by Harry Scells on 28/8/17.
 */
public class QSQPPredictor extends PreQPPredictor {

    public QSQPPredictor(IndexReader ir) {
        super(ir);
    }

    public String name() {
        return "QueryScope";
    }

    @Override
    public double scoreQuery(String qno, Query q) {
        // Number of documents containing at least one of the query terms.
        double Nq = Double.POSITIVE_INFINITY;
        String[] termTuples = q.toString().split(" ");

        for (String termTuple : termTuples) {
            String[] terms = termTuple.split(":");
            if (terms.length == 2) {
                String term = terms[1];
                try {
                    double df = getDF(term);
                    // What is the smallest possible df?
                    if (df < Nq && df > 0) {
                        Nq = df;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return -Math.log((1 + Nq) / (1 + reader.numDocs()));
    }
}

package lucene4ir.predictor.pre;

import lucene4ir.predictor.PreQPPredictor;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by Harry Scells on 28/8/17.
 */
public class QSQPPredictor extends PreQPPredictor {

    public QSQPPredictor(IndexReader ir) {
        super(ir);
    }

    public String name() {
        return "QueryScope";
    }

    @Override
    public double scoreQuery(String qno, Query q) {
        // Number of documents containing at least one of the query terms.
        Set<Integer> Nq = new HashSet<>();
        IndexSearcher searcher = new IndexSearcher(reader);
        String[] termTuples = q.toString().split(" ");

        for (String termTuple : termTuples) {
            String[] terms = termTuple.split(":");
            if (terms.length == 2) {
                String term = terms[1];
                try {
                    // Add the docs that contain this term to the set Nq.
                    TermQuery query = new TermQuery(new Term("all", term));
                    TopDocs docs = searcher.search(query, reader.numDocs());
                    for (ScoreDoc scoreDoc : docs.scoreDocs) {
                        Nq.add(scoreDoc.doc);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    System.exit(1);
                }
            }
        }

        return -Math.log((1.0 + Nq.size()) / (1.0 + reader.numDocs()));
    }
}

Fix bug with Query Scope predictor.

Fix bug with Query Scope predictor.


package hackerrank;

import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/sherlock-and-the-beast
 */
public class SherlockAndTheBeast {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // TODO
    }
}

package hackerrank;

import java.util.Scanner;

/**
 * https://www.hackerrank.com/challenges/sherlock-and-the-beast
 */
public class SherlockAndTheBeast {
    private static int sherlockAndTheBeast(int n) {
        // TODO
        return 0;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int testCases = in.nextInt();
        for (int t = 0; t < testCases; t++) {
            int n = in.nextInt();
            System.out.println(sherlockAndTheBeast(n));
        }
    }
}

Update Sherlock and the Beast

Update Sherlock and the Beast


package org.gluu.demo.rest;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

@Path("/demo")
public class DemoEndpoint {

	@GET
	@Path("/status")
	public Response listClients() {
		return Response.ok("success").build();
	}

}

package org.gluu.demo.rest;

import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;

@Path("/demo")
public class DemoEndpoint {

	@Inject
	private Logger log;

	@GET
	@Path("/status")
	public Response listClients() {
		log.info("Get request to demo endpoint");
		return Response.ok("success").build();
	}

}

Add log message about request to demo endpoint


package org.cf.smalivm.opcode;

import org.cf.smalivm.SideEffect;

public abstract class Op {

    private final int address;
    private final int[] childAddresses;
    private final String opName;

    Op(int address, String opName, int childAddress) {
        this(address, opName, new int[] { childAddress });
    }

    Op(int address, String opName, int[] childAddresses) {
        this.address = address;
        this.opName = opName;
        this.childAddresses = childAddresses;
    }

    public final int getAddress() {
        return address;
    }

    public final String getName() {
        return opName;
    }

    public final int[] getPossibleChildren() {
        return childAddresses;
    }

    public SideEffect.Level sideEffectLevel() {
        return SideEffect.Level.NONE;
    }

    @Override
    public abstract String toString();

}

package org.cf.smalivm.opcode;

import org.cf.smalivm.SideEffect;

public abstract class Op {

    private int address;
    private int[] childAddresses;
    private final String opName;

    Op(int address, String opName, int childAddress) {
        this(address, opName, new int[] { childAddress });
    }

    Op(int address, String opName, int[] childAddresses) {
        this.address = address;
        this.opName = opName;
        this.childAddresses = childAddresses;
    }

    public final int getAddress() {
        return address;
    }

    public final String getName() {
        return opName;
    }

    public final int[] getPossibleChildren() {
        return childAddresses;
    }

    public SideEffect.Level sideEffectLevel() {
        return SideEffect.Level.NONE;
    }

    public void setAddress(int address) {
        this.address = address;
    }

    public void setPossibleChildren(int[] childAddresses) {
        this.childAddresses = childAddresses;
    }

    @Override
    public abstract String toString();

}

Make op address and child addresses mutable


package edu.pdx.spi.verticles;

import io.vertx.core.AbstractVerticle;

public class Deploy extends AbstractVerticle {
  @Override
  public void start() {
    System.out.println("Starting server...");

    vertx.deployVerticle("edu.pdx.spi.verticles.DataSource");
    vertx.deployVerticle("edu.pdx.spi.verticles.Server");
  }
}

package edu.pdx.spi.verticles;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;

public class Deploy extends AbstractVerticle {
  @Override
  public void start() {
    System.out.println("Starting server...");
    DeploymentOptions workerOptions = new DeploymentOptions().setWorker(true).setConfig(this.config());
    DeploymentOptions normalOptions = new DeploymentOptions().setConfig(this.config());

    if (!this.config().getBoolean("debug")) {
      vertx.deployVerticle("edu.pdx.spi.verticles.SstoreConnector", workerOptions);
    }

    vertx.deployVerticle("edu.pdx.spi.verticles.DataSource", normalOptions);
    vertx.deployVerticle("edu.pdx.spi.verticles.Server", normalOptions);
  }
}

Add deployment, and set s-store verticle to a worker. Also add debug check.


package tehnut.xtones.compat;

import mcp.mobius.waila.api.*;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.translation.I18n;
import tehnut.xtones.block.BlockXtone;

import javax.annotation.Nonnull;
import java.util.List;

@WailaPlugin
public class CompatWaila implements IWailaPlugin {

    @Override
    public void register(IWailaRegistrar registrar) {
        registrar.registerHeadProvider(new DataProviderXtones(), BlockXtone.class);
    }

    public static class DataProviderXtones implements IWailaDataProvider {
        @Override
        @Nonnull
        public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
            currenttip.add(I18n.translateToLocalFormatted("tooltip.xtones.type", itemStack.getItemDamage() + 1));
            return currenttip;
        }
    }
}

package tehnut.xtones.compat;

import mcp.mobius.waila.api.*;
import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack;
import tehnut.xtones.block.BlockXtone;

import javax.annotation.Nonnull;
import java.util.List;

@WailaPlugin
public class CompatWaila implements IWailaPlugin {

    @Override
    public void register(IWailaRegistrar registrar) {
        registrar.registerHeadProvider(new IWailaDataProvider() {
            @Nonnull
            @Override
            public List<String> getWailaHead(ItemStack itemStack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
                currenttip.add(I18n.format("tooltip.xtones.type", itemStack.getItemDamage() + 1));
                return currenttip;
            }
        }, BlockXtone.class);
    }
}

Move Hwyla integration into a lambda

Move Hwyla integration into a lambda


/*
  Suppose you have a lot of files in a directory named Exercisei_j, where
  i and j are digits. Write a program that pads a 0 before i if i is a single
  digit. For example, a file named Exercise2_1 in a directory will be renamed
  to Exercise02_1. Use the following command to run your program:

  java E12_28 *
*/

import java.io.File;

public class E12_28 {
  public static void main(String[] args) {
    for (String s: args) {
      File file = new File(s);
      if (s.matches(".*Exercise\\d_\\d+.*")) {
        StringBuilder sb = new StringBuilder(s);
        int index = sb.indexOf("Exercise");
        sb.insert((index + 8), "0");
        File newName = new File(sb.toString());
        file.renameTo(newName);
      }
    }
  }
}

/*
  Suppose you have a lot of files in a directory named Exercisei_j, where
  i and j are digits. Write a program that pads a 0 before i if i is a single
  digit. For example, a file named Exercise2_1 in a directory will be renamed
  to Exercise02_1. Use the following command to run your program:

  java E12_28 *
*/

import java.io.File;

public class E12_28 {
  public static void main(String[] args) {
    for (String s: args) {
      File file = new File(s);
      StringBuilder sb = new StringBuilder(s);
      if (s.matches("Exercise\\d_\\d+")) {
        sb.insert(8, "0");
      }
      File newName = new File(sb.toString());
      file.renameTo(newName);
    }
  }
}

Modify solution to fit the exercise specification more closely


/**
 * Place-holder for dataset package info
 *
 *
 */
package com.continuuity.api.data.lib;

/**
 * This package is deprecated. Please use {@link com.continuuity.api.data.DataSet}s for info.
 *
 */
package com.continuuity.api.data.lib;

Add package info for lib

Add package info for lib


package de.otto.edison.jobtrigger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

/*
Extend the basePackages to de.otto.edison so SpringBoot is able to find
the components configured by edison-microservice
*/
@ComponentScan(basePackages = "de.otto.edison")
@PropertySource(value="/version.properties", ignoreResourceNotFound = true)
@SpringBootApplication
public class Server {

    private static ApplicationContext ctx;

    public static ApplicationContext applicationContext() {
        return ctx;
    }

    public static void main(String[] args) {
        ctx = new SpringApplication(Server.class).run(args);
    }
}

package de.otto.edison.jobtrigger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;

/*
Extend the basePackages to de.otto.edison so SpringBoot is able to find
the components configured by edison-microservice
*/
@ComponentScan(basePackages = "de.otto")
@PropertySource(value="/version.properties", ignoreResourceNotFound = true)
@SpringBootApplication
public class Server {

    private static ApplicationContext ctx;

    public static ApplicationContext applicationContext() {
        return ctx;
    }

    public static void main(String[] args) {
        ctx = new SpringApplication(Server.class).run(args);
    }
}

Use de.otto for component scan

Use de.otto for component scan


package net.ripe.db.whois.common;

import javax.annotation.concurrent.Immutable;
import java.util.regex.Pattern;

@Immutable
public final class Message {
    public static final Pattern BEGINNING_OF_LINE_PERCENT_SIGNS = Pattern.compile("^%+ ");

    private final Messages.Type type;
    private final String text;
    private final Object[] args;
    private final String formattedText;

    public Message(final Messages.Type type, final String text, final Object... args) {
        this.type = type;
        this.text = text;
        this.args = args;
        this.formattedText = args.length == 0 ? text : String.format(text, args);
    }

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

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

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Message message = (Message) o;
        return type == message.type && formattedText.equals(message.formattedText);
    }

    @Override
    public int hashCode() {
        int result = type.hashCode();
        result = 31 * result + formattedText.hashCode();
        return result;
    }

    public Messages.Type getType() {
        return type;
    }

    public String getFormattedText() {
        return formattedText;
    }

    public String getText() {
        return text;
    }

    public Object[] getArgs() {
        return args;
    }
}

package net.ripe.db.whois.common;

import javax.annotation.concurrent.Immutable;

@Immutable
public final class Message {

    private final Messages.Type type;
    private final String text;
    private final Object[] args;
    private final String formattedText;

    public Message(final Messages.Type type, final String text, final Object... args) {
        this.type = type;
        this.text = text;
        this.args = args;
        this.formattedText = args.length == 0 ? text : String.format(text, args);
    }

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

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

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Message message = (Message) o;
        return type == message.type && formattedText.equals(message.formattedText);
    }

    @Override
    public int hashCode() {
        int result = type.hashCode();
        result = 31 * result + formattedText.hashCode();
        return result;
    }

    public Messages.Type getType() {
        return type;
    }

    public String getFormattedText() {
        return formattedText;
    }

    public String getText() {
        return text;
    }

    public Object[] getArgs() {
        return args;
    }
}

Print all the messages on a QueryException (not just the length).


/*
 * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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
 */
import org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory;
import org.opendaylight.yangtools.yang.xpath.impl.AntlrXPathParserFactory;

module org.opendaylight.yangtools.yang.xpath.impl {
    exports org.opendaylight.yangtools.yang.xpath.impl.di;

    provides YangXPathParserFactory with AntlrXPathParserFactory;

    requires java.xml;
    requires org.opendaylight.yangtools.yang.common;
    requires org.opendaylight.yangtools.yang.xpath.api;
    requires org.opendaylight.yangtools.yang.xpath.antlr;
    requires org.slf4j;

    // Annotations
    requires static javax.inject;
    requires static metainf.services;
    requires static org.eclipse.jdt.annotation;
    requires static org.osgi.service.component.annotations;
}

/*
 * Copyright (c) 2020 PANTHEON.tech, s.r.o. 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
 */
import org.opendaylight.yangtools.yang.xpath.api.YangXPathParserFactory;
import org.opendaylight.yangtools.yang.xpath.impl.AntlrXPathParserFactory;

module org.opendaylight.yangtools.yang.xpath.impl {
    exports org.opendaylight.yangtools.yang.xpath.impl.di;

    provides YangXPathParserFactory with AntlrXPathParserFactory;

    requires java.xml;
    requires org.opendaylight.yangtools.yang.common;
    requires org.opendaylight.yangtools.yang.xpath.api;
    requires org.opendaylight.yangtools.yang.xpath.antlr;
    requires org.slf4j;

    // Annotations
    requires static com.github.spotbugs.annotations;
    requires static javax.inject;
    requires static metainf.services;
    requires static org.eclipse.jdt.annotation;
    requires static org.osgi.service.component.annotations;
}

Add missing spotbugs annotations in xpath-impl

Somehow we have been missing this annotation import, fix that up.

Change-Id: Ib39814bca421b6518f7e1bb0e8c8ec38350747fb
Signed-off-by: Robert Varga <91ae5aa8c7a9f7e57b701db766e23e544aaa6ae9@pantheon.tech>


package com.powerdata.openpa.psse;

import com.powerdata.openpa.tools.AbstractBaseObject;

public class PsseBaseObject extends AbstractBaseObject
{
	PsseBaseList<?> _plist;

	public PsseBaseObject(PsseBaseList<?> list, int ndx)
	{
		super(list, ndx);
		_plist = list;
	}

	public PsseModel getPsseModel() {return _plist.getPsseModel();}
}

package com.powerdata.openpa.psse;

import com.powerdata.openpa.tools.AbstractBaseObject;

public class PsseBaseObject extends AbstractBaseObject
{
	PsseBaseList<?> _plist;
	int _hashcode;

	public PsseBaseObject(PsseBaseList<?> list, int ndx)
	{
		super(list, ndx);
		_plist = list;
		_hashcode = list.getClass().hashCode() + getClass().hashCode() + ndx;
	}

	public PsseModel getPsseModel() {return _plist.getPsseModel();}
	@Override
	public int hashCode()
	{
		return _hashcode;
	}

	@Override
	public boolean equals(Object obj)
	{
		if (obj instanceof PsseBaseObject)
		{
			PsseBaseObject o = (PsseBaseObject)obj;
			return _ndx == o._ndx && _plist.hashCode() == o._plist.hashCode();
		}
		return false;
	}
}

Make hashcode and equals work for power objects


package beaform.dao;

import static org.junit.Assert.assertFalse;

import java.util.concurrent.CountDownLatch;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.Test;

@SuppressWarnings("static-method")
public class ShutDownHookTest {

	@Test
	public void testHook() throws InterruptedException {
		EntityManagerFactory entityManagerFact = Persistence.createEntityManagerFactory("test");
		EntityManager entityManager = entityManagerFact.createEntityManager();
		ShutDownHook hook = new ShutDownHook(entityManager, entityManagerFact);
		CountDownLatch latch = new CountDownLatch(1);

		Runnable withsync = new Runnable() {

			@Override
			public void run() {
				hook.run();
				latch.countDown();
			}
		};
		Thread thread = new Thread(withsync);
		thread.start();
		latch.await();
		assertFalse("Entity manager isn't closed", entityManager.isOpen());
		assertFalse("Entity manager factory isn't closed", entityManagerFact.isOpen());
	}
}

package beaform.dao;

import static org.junit.Assert.assertFalse;

import java.util.concurrent.CountDownLatch;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.Test;

@SuppressWarnings("static-method")
public class ShutDownHookTest {

	@Test
	public void testHook() throws InterruptedException {
		final EntityManagerFactory entityManagerFact = Persistence.createEntityManagerFactory("test");
		final EntityManager entityManager = entityManagerFact.createEntityManager();
		final ShutDownHook hook = new ShutDownHook(entityManager, entityManagerFact);
		final CountDownLatch latch = new CountDownLatch(1);

		Runnable withsync = new Runnable() {

			@Override
			public void run() {
				hook.run();
				latch.countDown();
			}
		};
		Thread thread = new Thread(withsync);
		thread.start();
		latch.await();
		assertFalse("Entity manager isn't closed", entityManager.isOpen());
		assertFalse("Entity manager factory isn't closed", entityManagerFact.isOpen());
	}

	@Test
	public void testHookAlreadyClosed() throws InterruptedException {
		final EntityManagerFactory entityManagerFact = Persistence.createEntityManagerFactory("test");
		final EntityManager entityManager = entityManagerFact.createEntityManager();
		final ShutDownHook hook = new ShutDownHook(entityManager, entityManagerFact);

		entityManager.close();
		entityManagerFact.close();

		final CountDownLatch latch = new CountDownLatch(1);

		Runnable withsync = new Runnable() {

			@Override
			public void run() {
				hook.run();
				latch.countDown();
			}
		};
		Thread thread = new Thread(withsync);
		thread.start();
		latch.await();
		assertFalse("Entity manager isn't closed", entityManager.isOpen());
		assertFalse("Entity manager factory isn't closed", entityManagerFact.isOpen());
	}
}

Add additional test for the shutdown hook


package com.aviras.mrassistant.models;

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

import io.realm.annotations.PrimaryKey;

/**
 * Represent order
 * <p/>
 * Created by ashish on 8/6/16.
 */
public class Order {

    @PrimaryKey
    private int id;

    private Doctor doctor;

    private List<Medicine> medicines = new ArrayList<>();

    private long createdDate;
    private long expectedDeliveryDate;
    private long actualDeliveryDate;
}

package com.aviras.mrassistant.models;

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

import io.realm.annotations.PrimaryKey;

/**
 * Represent order
 * <p/>
 * Created by ashish on 8/6/16.
 */
public class Order {

    @PrimaryKey
    private int id;

    private Doctor doctor;

    private List<OrderItem> items = new ArrayList<>();

    private long createdDate;
    private long expectedDeliveryDate;
    private long actualDeliveryDate;

    public int getId() {
        return id;
    }

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

    public Doctor getDoctor() {
        return doctor;
    }

    public void setDoctor(Doctor doctor) {
        this.doctor = doctor;
    }

    public List<OrderItem> getItems() {
        return items;
    }

    public void setItems(List<OrderItem> items) {
        this.items = items;
    }

    public long getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(long createdDate) {
        this.createdDate = createdDate;
    }

    public long getExpectedDeliveryDate() {
        return expectedDeliveryDate;
    }

    public void setExpectedDeliveryDate(long expectedDeliveryDate) {
        this.expectedDeliveryDate = expectedDeliveryDate;
    }

    public long getActualDeliveryDate() {
        return actualDeliveryDate;
    }

    public void setActualDeliveryDate(long actualDeliveryDate) {
        this.actualDeliveryDate = actualDeliveryDate;
    }
}

Correct the definition of order

Correct the definition of order


/*
 *  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.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 */

package lizard.comms.thrift;

import org.apache.jena.atlas.lib.InternalErrorException ;
import org.apache.thrift.protocol.TCompactProtocol ;
import org.apache.thrift.protocol.TJSONProtocol ;
import org.apache.thrift.protocol.TProtocol ;
import org.apache.thrift.protocol.TTupleProtocol ;
import org.apache.thrift.transport.TTransport ;

public class ThriftLib {

    /** Choose the wire-representation : compact is the normal choice */
    public static TProtocol protocol(TTransport transport) {
        if ( true ) return new TCompactProtocol(transport) ;
        if ( false ) return new TTupleProtocol(transport) ;
        if ( false ) return new TJSONProtocol(transport) ;
        throw new InternalErrorException("No protocol impl choosen") ;
    }

}

/*
 *  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.
 *
 *  See the NOTICE file distributed with this work for additional
 *  information regarding copyright ownership.
 */

package lizard.comms.thrift;

import org.apache.jena.atlas.lib.InternalErrorException ;
import org.apache.thrift.protocol.* ;
import org.apache.thrift.transport.TTransport ;

public class ThriftLib {

    /** Choose the wire-representation : compact is the normal choice */
    public static TProtocol protocol(TTransport transport) {
        if ( true ) return new TCompactProtocol(transport) ;
        if ( false ) return new TBinaryProtocol(transport) ;
        if ( false ) return new TTupleProtocol(transport) ;
        if ( false ) return new TJSONProtocol(transport) ;
        throw new InternalErrorException("No protocol impl choosen") ;
    }

}

Add record of "binary" protocol (default in some places)


package core.entities.menus;

import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.MessageChannel;

public class MapPickMenuManager extends MenuManager<MapPickMenuController, MapPickMenu> {

	private boolean picking = false;

	public MapPickMenuManager(Member owner, MapPickMenuController controller) {
		super(owner, controller);
	}

	@Override
	protected void createMenu() {
		MessageChannel channel = owner.getUser().openPrivateChannel().complete();

		menu = new MapPickMenu(channel, this, controller.getPickStyle());
	}

	@Override
	protected <T> void menuAction(int pageIndex, T action) {
		if(!picking) {
			return;
		}

		int fieldIndex = (int)action;
		int mapIndex = (pageIndex * getOptions().getPageMaxSize()) + fieldIndex;

		if(mapIndex >= controller.getMapPool().size()) {
			return;
		}

		controller.chooseMap(mapIndex);
		getOptions().removeOption(pageIndex, mapIndex);
		controller.managerActionTaken(this);
	}

	public void nextTurn() {
		picking = !picking;
	}

	public boolean canPick() {
		return picking;
	}
}

package core.entities.menus;

import net.dv8tion.jda.core.entities.Member;
import net.dv8tion.jda.core.entities.MessageChannel;

public class MapPickMenuManager extends MenuManager<MapPickMenuController, MapPickMenu> {

	private boolean picking = false;

	public MapPickMenuManager(Member owner, MapPickMenuController controller) {
		super(owner, controller);
	}

	@Override
	protected void createMenu() {
		MessageChannel channel = owner.getUser().openPrivateChannel().complete();

		menu = new MapPickMenu(channel, this, controller.getPickStyle());
	}

	@Override
	protected <T> void menuAction(int pageIndex, T action) {
		if(!picking) {
			return;
		}

		int fieldIndex = (int)action;
		int mapIndex = (pageIndex * getOptions().getPageMaxSize()) + fieldIndex;

		if(mapIndex >= controller.getMapPool().size()) {
			return;
		}

		controller.chooseMap(mapIndex);
		getOptions().removeOption(pageIndex, fieldIndex);
		controller.managerActionTaken(this);
	}

	public void nextTurn() {
		picking = !picking;
	}

	public boolean canPick() {
		return picking;
	}
}

Fix using wrong index for map selection

Fix using wrong index for map selection


package com.todoist.model;

import java.util.regex.Pattern;

public class Sanitizers {
    public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
    public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:";
    public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";

    public static final Pattern PROJECT_NAME_INVALID_PATTERN =
            Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern LABEL_NAME_INVALID_PATTERN =
            Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern FILTER_NAME_INVALID_PATTERN =
            Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+");

    public static final String REPLACEMENT = "_";
}

package com.todoist.model;

import java.util.regex.Pattern;

public class Sanitizers {
    public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
    public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:@";
    public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";

    public static final Pattern PROJECT_NAME_INVALID_PATTERN =
            Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern LABEL_NAME_INVALID_PATTERN =
            Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern FILTER_NAME_INVALID_PATTERN =
            Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+");

    public static final String REPLACEMENT = "_";
}

Add @ as an invalid label name character


package openmods.utils;

import java.util.Map;

import com.google.common.collect.Maps;

public abstract class CachedFactory<K, V> {

	private final Map<K, V> cache = Maps.newHashMap();

	public V getOrCreate(K key) {
		V value = cache.get(key);

		if (value == null) {
			value = create(key);
			cache.put(key, value);
		}

		return value;
	}

	protected abstract V create(K key);
}

package openmods.utils;

import java.util.Map;

import com.google.common.collect.Maps;

public abstract class CachedFactory<K, V> {

	private final Map<K, V> cache = Maps.newHashMap();

	public V getOrCreate(K key) {
		V value = cache.get(key);

		if (value == null) {
			value = create(key);
			cache.put(key, value);
		}

		return value;
	}

	public V remove(K key) {
		return cache.remove(key);
	}

	protected abstract V create(K key);
}

Add remove method to cached factory

Add remove method to cached factory


package com.legendzero.lzlib.database;

import com.legendzero.lzlib.data.SQLData;

import java.util.Iterator;
import java.util.function.Function;

public class SQLBatch<T> extends SQLStatement {

    private final Function<? super T, Object>[] mappingFunctions;

    public SQLBatch(String update, Function<? super T, Object>... mappingFunctions) {
        super(update);
        this.mappingFunctions = mappingFunctions;
    }

    public SQLBatch(SQLStatement sqlStatement, Function<? super T, Object>... mappingFunctions) {
        super(sqlStatement);
        this.mappingFunctions = mappingFunctions;
    }

    public Function<? super T, Object>[] getMappingFunctions() {
        return this.mappingFunctions;
    }

    public final int[] batch(SQLData<?> data, Iterable<T> iterable) {
        return data.batch(this, iterable);
    }

    public final int[] batch(SQLData<?> data, Iterator<T> iterator) {
        return data.batch(this, iterator);
    }

    public final int[] batch(SQLData<?> data, T... values) {
        return data.batch(this, values);
    }
}

package com.legendzero.lzlib.database;

import com.legendzero.lzlib.data.SQLData;

import java.util.Iterator;
import java.util.List;
import java.util.function.Function;

public class SQLBatch<T> extends SQLStatement {

    private final List<Function<? super T, Object>> mappingFunctions;

    public SQLBatch(String update, List<Function<? super T, Object>> mappingFunctions) {
        super(update);
        this.mappingFunctions = mappingFunctions;
    }

    public SQLBatch(SQLStatement sqlStatement, List<Function<? super T, Object>> mappingFunctions) {
        super(sqlStatement);
        this.mappingFunctions = mappingFunctions;
    }

    public List<Function<? super T, Object>> getMappingFunctions() {
        return this.mappingFunctions;
    }

    public final int[] batch(SQLData<?> data, Iterable<T> iterable) {
        return data.batch(this, iterable);
    }

    public final int[] batch(SQLData<?> data, Iterator<T> iterator) {
        return data.batch(this, iterator);
    }

    public final int[] batch(SQLData<?> data, T... values) {
        return data.batch(this, values);
    }
}

Use list to store functions for type safety.


/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 *
 */
package com.xpn.xwiki.util;

import junit.framework.TestCase;

/**
 * Unit tests for {@link com.xpn.xwiki.util.Util}.
 *
 * @version $Id: $
 */
public class UtilTest extends TestCase
{
    public void testConvertToAlphaNumeric()
    {
        assertEquals("Search", Util.convertToAlphaNumeric("Search"));
        assertEquals("Search", Util.convertToAlphaNumeric("S.earch"));
        assertEquals("e", Util.convertToAlphaNumeric("$%#^^^()"));
    }
}

/*
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 *
 */
package com.xpn.xwiki.util;

import junit.framework.TestCase;

/**
 * Unit tests for {@link com.xpn.xwiki.util.Util}.
 *
 * @version $Id: $
 */
public class UtilTest extends TestCase
{
    public void testConvertToAlphaNumeric()
    {
        assertEquals("Search", Util.convertToAlphaNumeric("Search"));
        assertEquals("Search", Util.convertToAlphaNumeric("S.earch"));
        assertEquals("e", Util.convertToAlphaNumeric("$%#^()"));
    }
}

XWIKI-2054: Add Utility API to remove all non alpha numeric chartacters from some text

* No need to repeat the same chars

git-svn-id: cfa2b40e478804c47c05d0f328c574ec5aa2b82e@7258 f329d543-caf0-0310-9063-dda96c69346f


package org.cryptonit;

import javacard.framework.JCSystem;

public class IOBuffer {
    private FileIndex index = null;
    private byte [] buffer = null;

    private short [] shorts = null;
    private boolean [] bools = null;
    final private byte isLOADED = 0x0;
    final private byte isFILE   = 0x1;

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
        this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
    }
}

package org.cryptonit;

import javacard.framework.JCSystem;

public class IOBuffer {
    private FileIndex index = null;
    private byte [] buffer = null;

    private short [] shorts = null;
    final private byte SIZE = 0x0;
    final private byte PATH = 0x1;
    final private byte OFFSET = 0x2;

    private boolean [] bools = null;
    final private byte isLOADED = 0x0;
    final private byte isFILE   = 0x1;

    public IOBuffer(FileIndex index) {
        this.index = index;
        this.bools = JCSystem.makeTransientBooleanArray((short) 2, JCSystem.CLEAR_ON_DESELECT);
        this.buffer = JCSystem.makeTransientByteArray((short)256, JCSystem.CLEAR_ON_DESELECT);
        this.shorts = JCSystem.makeTransientShortArray((short)3, JCSystem.CLEAR_ON_DESELECT);
    }
}

Define integer metadata array index constants


/*******************************************************************************
 ** Copyright (c) 2010 - 2013 Ushahidi Inc
 ** All rights reserved
 ** Contact: team@ushahidi.com
 ** Website: http://www.ushahidi.com
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser
 ** General Public License version 3 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file. Please review the following information to
 ** ensure the GNU Lesser General Public License version 3 requirements
 ** will be met: http://www.gnu.org/licenses/lgpl.html.
 **
 **
 ** If you have questions regarding the use of this file, please contact
 ** Ushahidi developers at team@ushahidi.com.
 **
 ******************************************************************************/
package com.crowdmap.java.sdk.json;

import com.crowdmap.java.sdk.model.User;

import java.io.Serializable;
import java.util.List;

/**
 * Users resources
 */
public class Users extends Response implements Serializable {

    private List<User> users;

    public List<User> getUsers(){
        return users;
    }

}

/*******************************************************************************
 ** Copyright (c) 2010 - 2013 Ushahidi Inc
 ** All rights reserved
 ** Contact: team@ushahidi.com
 ** Website: http://www.ushahidi.com
 **
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser
 ** General Public License version 3 as published by the Free Software
 ** Foundation and appearing in the file LICENSE.LGPL included in the
 ** packaging of this file. Please review the following information to
 ** ensure the GNU Lesser General Public License version 3 requirements
 ** will be met: http://www.gnu.org/licenses/lgpl.html.
 **
 **
 ** If you have questions regarding the use of this file, please contact
 ** Ushahidi developers at team@ushahidi.com.
 **
 ******************************************************************************/
package com.crowdmap.java.sdk.json;

import com.crowdmap.java.sdk.model.User;

import java.io.Serializable;
import java.util.List;

/**
 * Users resources
 */
public class Users extends Response implements Serializable {

    private static final long serialVersionUID = 8172708394083993131L;

    private List<User> users;

    public List<User> getUsers(){
        return users;
    }

}

Add serial version uid to users class

Add serial version uid to users class


package xyz.nulldev.ts;

import spark.Spark;

/**
 * Project: TachiServer
 * Author: nulldev
 * Creation Date: 22/07/16
 */
public class TachiWebUIServer {
    public void start() {
        Spark.staticFiles.header("Access-Control-Allow-Origin", "*");
        Spark.staticFiles.location("tachiweb-ui");
    }
}

package xyz.nulldev.ts;

import spark.Spark;

/**
 * Project: TachiServer
 * Author: nulldev
 * Creation Date: 22/07/16
 */
public class TachiWebUIServer {
    public void start() {
        Spark.staticFiles.header("Access-Control-Allow-Origin", "*");
        Spark.staticFiles.location("/tachiweb-ui");
    }
}

Fix static files not loading from JAR.

Fix static files not loading from JAR.


package throwing;

@FunctionalInterface
public interface ThrowingRunnable<X extends Throwable> {
    public void run() throws X;

    default public Runnable fallbackTo(Runnable fallback) {
        ThrowingRunnable<Nothing> t = fallback::run;
        return orTry(t)::run;
    }

    default public <Y extends Throwable> ThrowingRunnable<Y> orTry(ThrowingRunnable<? extends Y> r) {
        return () -> {
            try {
                run();
            } catch (Throwable x) {
                try {
                    r.run();
                } catch (Throwable x2) {
                    x2.addSuppressed(x);
                    throw x2;
                }
            }
        };
    }
}

package throwing;

import throwing.function.ThrowingSupplier;

@FunctionalInterface
public interface ThrowingRunnable<X extends Throwable> {
    public void run() throws X;

    default public Runnable fallbackTo(Runnable fallback) {
        ThrowingRunnable<Nothing> t = fallback::run;
        return orTry(t)::run;
    }

    default public <Y extends Throwable> ThrowingRunnable<Y> orTry(ThrowingRunnable<? extends Y> r) {
        ThrowingSupplier<Void, X> s1 = () -> {
            run();
            return null;
        };
        return s1.orTry(() -> {
            r.run();
            return null;
        })::get;
    }
}

Rewrite Runnable's methods to rely on Supplier's


package framework.generators;

/**
 * Abstract class to represent a wave generator.
 */
public abstract class Generator {
    /**
     * Generates the signal with the given frequency and duration.
     * @param  f  the frequency of the sample in hertzs
     * @param  d  the duration of the sample in seconds
     * @param  a  the amplitude of the sample
     * @return    the generated sample as an array of Doubles
     */
    public abstract Double[] generate(Double f, Double d, Double a);

    /**
     * Get the prototypes of the generators.
     * @return an array containing prototypes
     */
    public static Generator[] getPrototypes() {
        Generator[] prototypes = new Generator[1];
        prototypes[0] = new SineGenerator();
        return prototypes;
    }

    public abstract String toString();

    // Constants
    public static final int SAMPLE_RATE   = 44100;    // CD quality audio
}

package framework.generators;

/**
 * Abstract class to represent a wave generator.
 */
public abstract class Generator {
    /**
     * Generates the signal with the given frequency and duration.
     * @param  f  the frequency of the sample in hertzs
     * @param  d  the duration of the sample in seconds
     * @param  a  the amplitude of the sample
     * @return    the generated sample as an array of Doubles
     */
    public abstract Double[] generate(Double f, Double d, Double a);

    /**
     * Get the prototypes of the generators.
     * @return an array containing prototypes
     */
    public static Generator[] getPrototypes() {
        Generator[] prototypes = new Generator[2];
        prototypes[0] = new SineGenerator();
        prototypes[1] = new SquareGenerator();
        return prototypes;
    }

    public abstract String toString();

    // Constants
    public static final int SAMPLE_RATE   = 44100;    // CD quality audio
}

Add square generator to prototypes array.


package guangyin.internal.types;

import clojure.lang.Keyword;
import clojure.lang.ILookup;
import clojure.lang.IPersistentMap;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalAccessor;

public class TemporalAccessorWrapper extends ObjectWrapper implements ILookup {
    protected IPersistentMap keymap;
    private TemporalAccessor wrapped;

    public TemporalAccessorWrapper(IPersistentMap keymap, TemporalAccessor wrapped) {
        super(wrapped);
        this.keymap = keymap;
        this.wrapped = wrapped;
    }

    public Object valAt(Object key) {
        return this.valAt(key, null);
    }

    public Object valAt(Object key, Object notFound) {
        Keyword keyword = (Keyword) key;
        TemporalField field = (TemporalField) keyword.invoke(this.keymap);
        if (field == null || !wrapped.isSupported(field)) {
            return notFound;
        }
        return wrapped.getLong(field);
    }
}

package guangyin.internal.types;

import clojure.lang.Keyword;
import clojure.lang.ILookup;
import clojure.lang.IMapEntry;
import clojure.lang.IPersistentMap;
import clojure.lang.PersistentArrayMap;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalAccessor;

public class TemporalAccessorWrapper extends ObjectWrapper implements ILookup {
    private TemporalAccessor wrapped;
    protected IPersistentMap keymap;
    protected IPersistentMap valmap;

    public TemporalAccessorWrapper(IPersistentMap keymap, TemporalAccessor wrapped) {
        super(wrapped);

        this.wrapped = wrapped;
        this.keymap = keymap;

        IPersistentMap valmap = PersistentArrayMap.EMPTY;
        for (Object val : keymap) {
            IMapEntry entry = (IMapEntry) val;
            TemporalField field = (TemporalField) entry.val();
            if (wrapped.isSupported(field)) {
                valmap = valmap.assoc(entry.key(), wrapped.getLong(field));
            }
        }
        this.valmap = valmap;
    }

    public Object valAt(Object key) {
        return this.valmap.valAt(key);
    }

    public Object valAt(Object key, Object notFound) {
        return this.valmap.valAt(key, notFound);
    }
}

Create an actual map of TemporalAccessor in wrapper.


package com.github.lstephen.ootp.ai.stats;

/** @author lstephen */
public interface BaseRuns {

  double COEFFICIENT_SINGLE = 0.8;
  double COEFFICIENT_DOUBLE = 2.1;
  double COEFFICIENT_TRIPLE = 3.4;
  double COEFFICIENT_HOME_RUN = 1.8;
  double COEFFICIENT_WALK = 0.1;

  Double calculate(PitchingStats stats);
}

package com.github.lstephen.ootp.ai.stats;

/** @author lstephen */
public interface BaseRuns {

  // http://gosu02.tripod.com/id108.html
  double COEFFICIENT_SINGLE = 0.78;
  double COEFFICIENT_DOUBLE = 2.34;
  double COEFFICIENT_TRIPLE = 3.9;
  double COEFFICIENT_HOME_RUN = 2.34;
  double COEFFICIENT_WALK = 0.39;

  Double calculate(PitchingStats stats);
}

Update B coefficients for BsR

Update B coefficients for BsR