text stringlengths 14 410k | label int32 0 9 |
|---|---|
public Player(int pID){
playerID = pID;
//Jeder Spieler bekommt 15 Steine
for(int i=0; i<14; i++){
steine.add(new Steinchen(this.playerID, i));
}
dice = new Dice();
//Startposition fuer die einzelnen Spieler initialisieren
switch(playerID){
case 0:
this.startposition = 0;
case 1:
this.startposition = 12;
}
} | 3 |
public BBLogHandler(File f) {
log.finer("Creating new BBLogHandlerInstance");
try {
if(!f.exists()) {
//noinspection ResultOfMethodCallIgnored
f.getParentFile().mkdirs();
//noinspection ResultOfMethodCallIgnored
f.createNewFile();
}
fw = new FileWriter(f, true);
toFile = true;
} catch(IOException e) {
e.printStackTrace();
}
} | 2 |
public void update(UserBall b){
BPx = b.getPx();
BPy = b.getPy();
BVx = b.getVx();
BVy = b.getVy();
BRad = b.getRadius();
if ((BPy+BRad > Py) && (BPy+BRad < Py+BRad) && (BPx+(0.5)*BRad > Px) && (BPx-(0.5)*BRad < Px+width)){
// ball is on top of platform
BPy = Py-BRad;
BVy = -60;
}
b.setPx(BPx);
b.setPy(BPy);
b.setVx(BVx);
b.setVy(BVy);
} | 4 |
public static String decode(X509Certificate x509) {
List<String> result = new ArrayList<>();
boolean[] usage = x509.getKeyUsage();
if (usage == null) { return "<missing>"; }
for (int i = 0; i < NAMES.length; i++) {
if (i >= usage.length) break;
if (usage[i]) {
result.add(NAMES[i]);
}
}
return result.toString();
} | 4 |
public void applyBackpropagation(double expectedOutput[]) {
int i = 0;
for (Neuron n : outputLayer) { // update weights for output layer
ArrayList<Connection> connections = n.getAllInConnections();
for (Connection con : connections) {
double ak = n.getOutput();
double ai = con.getFromNeuron().getOutput();
double desiredOutput = expectedOutput[i];
double partialDerivative = -ak * (1 - ak) * ai
* (desiredOutput - ak);
double deltaWeight = -learningRate * partialDerivative;
double newWeight = con.getWeight() + deltaWeight;
con.setDeltaWeight(deltaWeight);
con.setWeight(newWeight + momentum * con.getPrevDeltaWeight());
}
i++;
}
for (Neuron n : hiddenLayer) { // update weights for hidden layer
ArrayList<Connection> connections = n.getAllInConnections();
for (Connection con : connections) {
double aj = n.getOutput();
double ai = con.getFromNeuron().getOutput();
double sumKoutputs = 0;
int j = 0;
for (Neuron out_neu : outputLayer) {
double wjk = out_neu.getConnection(n.id).getWeight();
double desiredOutput = expectedOutput[j];
double ak = out_neu.getOutput();
j++;
sumKoutputs = sumKoutputs
+ (-(desiredOutput - ak) * ak * (1 - ak) * wjk);
}
double partialDerivative = aj * (1 - aj) * ai * sumKoutputs;
double deltaWeight = -learningRate * partialDerivative;
double newWeight = con.getWeight() + deltaWeight;
con.setDeltaWeight(deltaWeight);
con.setWeight(newWeight + momentum * con.getPrevDeltaWeight());
}
}
} | 5 |
@RequestMapping(value = "/event-branch/{id}", method = RequestMethod.GET)
public ModelAndView eventBranchPage(
final HttpServletRequest request,
final HttpServletResponse response,
@PathVariable(value = "id") final String idStr
) throws IOException {
ModelAndView modelAndView = new ModelAndView("event-branch-layout");
if (idStr == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
modelAndView = null;
} else {
modelAndView.addObject(idStr);
}
return modelAndView;
} | 1 |
@Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(Encriptador.CifrarMensaje("Ingrese una operacion (SUMAR, RESTAR, MULTIPLICAR, RESTAR): "));
String operacion = in.readLine();
operacion = Encriptador.DescifrarMensaje(operacion);
out.println(Encriptador.CifrarMensaje("Ingrese primer parametro: "));
String parametro1 = in.readLine();
operacion = Encriptador.DescifrarMensaje(parametro1);
out.println(Encriptador.CifrarMensaje("Ingrese segundo parametro: "));
String parametro2 = in.readLine();
operacion = Encriptador.DescifrarMensaje(parametro2);
int resultado = 0;
try {
switch (operacion) {
case "SUMAR":
resultado = OperadorAritmetico.sumar(Integer.parseInt(parametro1), Integer.parseInt(parametro2));
break;
case "RESTAR":
resultado = OperadorAritmetico.restar(Integer.parseInt(parametro1), Integer.parseInt(parametro2));
break;
case "MULTIPLICAR":
resultado = OperadorAritmetico.multiplicar(Integer.parseInt(parametro1), Integer.parseInt(parametro2));
break;
case "DIVIDIR":
resultado = OperadorAritmetico.dividir(Integer.parseInt(parametro1), Integer.parseInt(parametro2));
break;
default:
break;
}
out.println(Encriptador.CifrarMensaje("Resultado: " + resultado));
} catch (Exception e) {
out.println(e.getMessage());
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
} | 6 |
public String read(String player, String element) {
String value = null;
Node players = doc.getFirstChild();
NodeList playerNode = null;
NodeList list = players.getChildNodes();
for(int i = 0; i < list.getLength(); i++) {
Node node = list.item(i);
if(player.equals(node.getNodeName()))
playerNode = node.getChildNodes();
// System.out.println(node.getFirstChild());
}
if(playerNode != null) {
for(int i = 0; i < playerNode.getLength(); i++) {
Node node = playerNode.item(i);
if(element.equals(node.getNodeName()))
value = node.getTextContent();
}
}
return value;
} | 5 |
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String path = file.getAbsolutePath().toLowerCase();
for (int i = 0, n = extensions.length; i < n; i++) {
String extension = extensions[i];
if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == '.')) {
return true;
}
}
}
return false;
} | 4 |
public static <K> void incrementValue(TreeMap<K, Integer> map, K key) {
Integer count = map.get(key);
if (count == null) {
map.put(key, 1);
} else {
map.put(key, count + 1);
}
} | 1 |
public void setYearStored (Year y)
{
yearStored = new Year (y);
} | 0 |
public List<Schedule> getScheduleList()
{
List<Schedule> list = new ArrayList<Schedule>();
try {
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM schedule");
while(rs.next())
{
list.add(getScheduleFromRS(rs));
}
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
} | 2 |
public void setImages() {
if (waitImage == null) {
File imageFile = new File(Structure.baseDir + "ChronoTower.png");
try {
waitImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (attackImage == null) {
File imageFile = new File(Structure.baseDir + "ChronoTowerFire.png");
try {
attackImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (upgradeImage == null) {
File imageFile = new File(Structure.baseDir + "ChronoTower.png");
try {
upgradeImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
if (explodeImage == null) {
File imageFile = new File(Structure.baseDir
+ "explosion-sprite40.png");
try {
explodeImage = ImageIO.read(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
}
} | 8 |
public static void main(String[] args) {
try {
Manifest manifest = new Manifest(FreeCol.class.getResourceAsStream("/META-INF/MANIFEST.MF"));
Attributes attribs = manifest.getMainAttributes();
String revision = attribs.getValue("Revision");
FREECOL_REVISION = FREECOL_VERSION + " (Revision: " + revision + ")";
} catch (Exception e) {
System.out.println("Unable to load Manifest.");
FREECOL_REVISION = FREECOL_VERSION;
}
// parse command line arguments
handleArgs(args);
FreeColDirectories.createAndSetDirectories();
initLogging();
Locale locale = getLocale();
Locale.setDefault(locale);
Messages.setMessageBundle(locale);
if (javaCheck && !checkJavaVersion()) {
System.err.println("Java version " + MIN_JDK_VERSION +
" or better is recommended in order to run FreeCol." +
" Use --no-java-check to skip this check.");
System.exit(1);
}
int minMemory = 128; // million bytes
if (memoryCheck && Runtime.getRuntime().maxMemory() < minMemory * 1000000) {
System.out.println("You need to assign more memory to the JVM. Restart FreeCol with:");
System.out.println("java -Xmx" + minMemory + "M -jar FreeCol.jar");
System.exit(1);
}
if (standAloneServer) {
startServer();
} else {
FreeColClient freeColClient = new FreeColClient(FreeColDirectories.getSavegameFile(), windowSize, sound, splashFilename, introVideo, fontName);
}
} | 6 |
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] split) throws NullPointerException, ArrayIndexOutOfBoundsException {
// get basic info needed
Player player;
Boolean isPlayer;
if (sender instanceof Player) {// If it's a player, we respond differently than if it's the console.
player = (Player) sender;// Cast it when we can
isPlayer = true;
} else {
player = null;
isPlayer = false;
}
// No arguments supplied to command, lets help them out a bit
if (split.length == 0) {
if (isPlayer) {
sendHelp(player);
} else { // not a player (console)
sendHelp(sender);
}// command handled
return true;
}// length was at least 1.
// Lets see what they want to do...
String cmd = TimeShift.command_aliases.get(split[0].toLowerCase());
if (cmd == null) {// no command found!
if (isPlayer) {
sendHelp(player);
} else {
sendHelp(sender);
}
return true;
}
if (cmd == "TS STARTUP") {// Startup Command
setPersist(player, sender, isPlayer, split);
} else if (cmd == "TS STOP") {// is it a stop command?
stopShift(player, sender, isPlayer, split);
} else if (cmd == "TS ERR") {// We got as far as trying to read it... just couldn't quite do it.
sender.sendMessage("There was an error parsing the command '" + split[0] + "' but someone tried to define it. The server's server.log file will have more information at startup.");
} else {// Not a stop command, therefore it's a loop command
startShift(player, sender, isPlayer, split);
}
// escaped the if! All success and error cases handled.
return true;
}// end of onCommand | 8 |
static final void method2267(int i, int i_0_, int i_1_, int i_2_, int i_3_,
int i_4_, int i_5_, int i_6_) {
anInt6324++;
if (i != 10499)
method2267(55, -44, 14, -122, 70, 0, 127, 112);
if ((i_0_ ^ 0xffffffff) == (i_6_ ^ 0xffffffff))
Npc.method2441(i_2_, i_6_, i_4_, -22728,
i_5_, i_3_, i_1_);
else if (Class369.anInt4960 > -i_6_ + i_1_
|| i_6_ + i_1_ > Class113.anInt1745
|| -i_0_ + i_5_ < Class132.anInt1910
|| i_0_ + i_5_ > Class38.anInt513)
Class348_Sub40.method3041(i_6_, i_1_, i_5_, i ^ ~0x2903, i_0_,
i_3_, i_2_, i_4_);
else
AbstractImageFetcher.method3012(i_0_, i_3_, i_6_, i_2_, i_1_,
(byte) -117, i_5_, i_4_);
} | 6 |
private void newSong() {
boolean cont = true;
if (StateMachine.isSongModified())
cont = Dialog
.showYesNoDialog("The current song has been modified!\n"
+ "Create a new song anyway?");
if (cont) {
theStaff.setSequence(new StaffSequence());
theStaff.setSequenceFile(null);
Slider sc = theStaff.getControlPanel().getScrollbar();
sc.setValue(0);
sc.setMax(Values.DEFAULT_LINES_PER_SONG - 10);
ArrowButton.setEndOfFile(false);
theStaff.getNoteMatrix().redraw();
controller.getNameTextField().clear();
StateMachine.setSongModified(false);
}
} | 2 |
public JLabel getPlayer1Name() {
boolean test = false;
if (test || m_test) {
System.out.println("Drawing :: getPlayer1Name() BEGIN");
}
if (test || m_test)
System.out.println("Drawing:: getPlayer1Name() - END");
return m_player1Name;
} | 4 |
public final void init(InjectorClassLoader classLoader, InjectorPluginLoader loader) {
if (this.classLoader != null && this.pluginLoader != null || isEnabled()) {
return;
}
this.classLoader = classLoader;
this.pluginLoader = loader;
if (getDescription().isDatabaseEnabled()) {
ServerConfig db = new ServerConfig();
db.setDefaultServer(false);
db.setRegister(false);
db.setClasses(getDatabaseClasses());
db.setName(getDescription().getName());
getServer().configureDbConfig(db);
DataSourceConfig ds = db.getDataSourceConfig();
ds.setUrl(replaceDatabaseString(ds.getUrl()));
getDataFolder().mkdirs();
ClassLoader previous = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(previous);
this.ebean = EbeanServerFactory.create(db);
Thread.currentThread().setContextClassLoader(previous);
}
} | 4 |
private static int runmemsize(String[] args) {
String rstr = null;
String path = null;
for (int i = 1; i < args.length; i++) {
String arg = args[i];
if (path == null && arg.startsWith("-")) {
usage();
} else if (rstr == null) {
rstr = arg;
} else if (path == null) {
path = arg;
} else {
usage();
}
}
long rnum = rstr != null ? Utility.atoix(rstr) : 1000000;
if (rnum < 1) usage();
int rv = procmemsize(rnum, path);
return rv;
} | 7 |
public ResultSet Select(String query){
//DO NOT USE IN PRODUCTION
//This method will take a query and blindly execute it
// We'll fill this ResultSet from the query and return it. The calling code can then break it down and pop it into the target attributes
ResultSet rs = null;
try{
Class.forName(driver);
Connection cx = DriverManager.getConnection(url, user, password);
Statement st = cx.createStatement();
rs = st.executeQuery(query);
}
catch (Exception x){
System.err.println(x);
}
return rs;
} | 1 |
protected static Ptg calcOdd( Ptg[] operands )
{
if( operands.length != 1 )
{
return PtgCalculator.getNAError();
}
double dd = 0.0;
try
{
dd = operands[0].getDoubleVal();
}
catch( NumberFormatException e )
{
return PtgCalculator.getValueError();
}
if( new Double( dd ).isNaN() ) // Not a Num -- possibly PtgErr
{
return PtgCalculator.getError();
}
long resnum = Math.round( dd );
// always round up!!
if( resnum < dd )
{
resnum++;
}
double remainder = resnum % 2;
if( remainder == 0 )
{
resnum++;
}
PtgInt pint = new PtgInt( (int) resnum );
return pint;
} | 5 |
public static void main(String[] args) {
char again;
int n;
do{
print("Enter the dimension of the matrix: ");
n = scan.nextInt();
double[][] matrix = new double[n][n];
print("\nEnter the matrix data:\n");
input(matrix);
print("The trace of the matrix is: " + trace(matrix));
print("\nContinue?(Y/N): ");
again = scan.next().charAt(0);
}while(again == 'y' || again == 'Y');
return;
} | 2 |
public boolean userNameInList(User user, ArrayList<String> friendNamesList) {
String curName = user.getName();
for (String friendName : friendNamesList) {
if (curName.equals(friendName)) {
return true;
}
}
return false;
} | 2 |
public static void updates(Year year)//update the events in the year and the displayed event
{
myYears.set(0, year);
} | 0 |
public static boolean isFileClass(String file) {
byte[] magicNumber = {(byte) 0xCA, (byte) 0xFE, (byte) 0xBA, (byte) 0xBE};
try (FileInputStream input = new FileInputStream(file)) {
byte[] number = new byte[4];
if (input.read(number) != -1){
if (Arrays.equals(magicNumber, number))
return true;
else
return false;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
} | 4 |
protected ObjectFormatter getObjectFormatter(Field field) {
Class type = field.getType();
if (List.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type)) {
type = String.class;
}
if (field.isAnnotationPresent(Formatter.class)) {
Formatter formatter = field.getAnnotation(Formatter.class);
if (!formatter.formatter().equals(TypeFormatter.class)) {
TypeFormatter typeFormatter = typeFormatterFactory.getByFormatterClass(formatter.formatter());
if (typeFormatter != null) {
return prepareTypeFormatterParam(typeFormatter,formatter.value());
}
typeFormatterFactory.put(formatter.formatter());
return prepareTypeFormatterParam(typeFormatterFactory.getByFormatterClass(formatter.formatter()), formatter.value());
} else if (!formatter.subClazz().equals(String.class)) {
type = formatter.subClazz();
TypeFormatter typeFormatter = typeFormatterFactory.get(type);
if (typeFormatter == null) {
throw new IllegalArgumentException("No typeFormatter for class " + type);
}
return prepareTypeFormatterParam(typeFormatter, formatter.value());
}
}
return getTypeFormatterFactory().get(BasicTypeFormatter.detectBasicClass(type));
} | 7 |
public DuplicateEntryException(Exception e, String name)
{
super(e, name);
} | 0 |
public void openBraceNoIndent() {
if ((Options.outputStyle & Options.BRACE_AT_EOL) != 0) {
print(currentLine.length() > 0 ? " {" : "{");
println();
} else {
if (currentLine.length() > 0)
println();
println("{");
}
} | 3 |
protected void paintComponent(Graphics g) {
g.drawImage(background, 0, 0, this.width,
this.height, null);
switch (pageId) {
case MAINMENU: {
resume.draw(g);
save.draw(g);
load.draw(g);
options.draw(g);
break;
}
case OPTIONSMENU: {
audio.draw(g);
video.draw(g);
controls.draw(g);
break;
}
case AUDIOMENU: {
mute.draw(g);
break;
}
}
if (pageId != MAINMENU) {
back.draw(g);
}
quit.draw(g);
if (isClicked) {
swordOffset += 10;
if (swordOffset > 100) {
swordOffset = 0;
isClicked = false;
doAction();
}
}
} | 6 |
public void readSensors() throws IOException{
try{
com.requestData(Communication.LATITUDE);
com.requestData(Communication.LONGITUDE);
com.requestData(Communication.HEADING);
com.requestData(Communication.ABSOLUTE_WIND);
com.requestData(Communication.OBSTACLES);
com.readMessage();
}catch(NumberFormatException ex){
System.out.println("\nCannot receive sensor data.");
System.out.print("Retry in ");
for(int i = 5; i > 0; i--){
System.out.print(i +", ");
try{
Thread.sleep(1000);
// readSensors();
}catch(InterruptedException ex1){
ex1.printStackTrace();
}
}
}
} | 3 |
@Override
//SimpleEntry: NextHop, Distance
public SimpleEntry<Byte, Byte> getRoute(Byte destination)
throws RouteNotFoundException {
lock.lock();
// TODO Respond whenever a route is requested.
if(destination == this.deviceID) {
lock.unlock();
return new SimpleEntry<Byte,Byte>((byte)1,(byte)0);
} else if(!networkTreeMap.containsKey(destination)) {
lock.unlock();
System.out.println("Looked for host " + destination);
throw new RouteNotFoundException("Destination unknown.");
} else if(networkTreeMap.get(destination).isEmpty()
|| networkTreeMap.get(deviceID).isEmpty()) {
lock.unlock();
System.out.println("Looked for host " + destination);
throw new RouteNotFoundException("Destination unreachable; no route to host.");
}
Byte nextHop = nextHops.get(destination);
Byte routeLen = routeLengths.get(destination);
if(nextHop == -1 || routeLen == -1) {
if(autoUpdate) {
update();
}
lock.unlock();
throw new RouteNotFoundException("Destination unreachable; no route to host.");
}
lock.unlock();
return new SimpleEntry<Byte,Byte>(nextHop,routeLen);
} | 7 |
static public void stop() {
setStopFlag(true);
if (mp3 != null)
mp3.stop();
mp3 = null;
if (music != null)
music.stop();
music = null;
if (musicType.equals("midi")) {
if (sequencer == null)
return;
if (sequencer.isRunning())
sequencer.stop();
if (sequencer.isOpen())
sequencer.close();
}
} | 6 |
public List<ShopDataBean> getarticleList() throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "";
List<ShopDataBean> articleList = null;
ShopDataBean shopBean = null;
try{
conn = getConnection();
sql = "select cou_name,count(*) from coupon";
pstmt = conn.prepareStatement(sql);
rs =pstmt.executeQuery();
if(rs.next()){
articleList = new ArrayList<ShopDataBean>();
do{
shopBean = new ShopDataBean();
shopBean.setCou_name(rs.getString("cou_name"));
shopBean.setCou_quantity(rs.getInt(2));
articleList.add(shopBean);
}
while(rs.next());
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
if(rs!=null)try{rs.close();}catch(SQLException ex){}
if(pstmt!=null)try{pstmt.close();}catch(SQLException ex){}
if(conn!=null)try{conn.close();}catch(SQLException ex){}
}
return articleList;
} | 9 |
public static int getExpressionLocByPtg( Ptg ptg, Stack expression ) throws FormulaNotFoundException
{
for( int i = 0; i < expression.size(); i++ )
{
Object o = expression.elementAt( i );
if( o == null )
{
throw new FormulaNotFoundException( "Couldn't get Ptg at: " + ptg.toString() );
}
if( o instanceof Byte )
{
// do nothing
}
else if( o instanceof Ptg )
{
if( o.equals( ptg ) )
{
return i;
}
}
}
return -1;
} | 5 |
public void control(Agent[] agents, Thing[] things) {
MeView meV = new MeView();
meV.t = t;
meV.vt = vt;
meV.x = x;
meV.y = y;
meV.r = r;
meV.a = a;
meV.AMIN = AMIN;
meV.AMAX = AMAX;
meV.VTMIN = VTMIN;
meV.VTMAX = VTMAX;
meV.CDRAG = CDRAG;
AgentView[] aVs = new AgentView[agents.length];
for (int i = 0; i < aVs.length; i++) {
aVs[i] = new AgentView();
aVs[i].c = agents[i].getClass();
aVs[i].r = agents[i].r;
aVs[i].t = agents[i].t;
aVs[i].v = agents[i].v;
aVs[i].x = agents[i].x;
aVs[i].y = agents[i].y;
}
if (things != null)
throw new Error("internal error: no things yet");
ai.control(meV, aVs, null);
a = clamp (meV.a, AMIN, AMAX);
vt = clamp (meV.vt, VTMIN, VTMAX);
} | 2 |
Precision(String fmt,String regex,int expectedStringLength) {
this.formatter=new SimpleDateFormat(fmt);
this.regex=regex;
this.expectedStringLength=expectedStringLength;
} | 0 |
public static void calculate(int x, int y) {
Queue<Node> cola = new LinkedList<Node>();
cola.add(new Node(x, y, 0));
for (int i = 0; i < v.length; i++) {
for (int j = 0; j < v[0].length; j++) {
v[i][j] = false;
}
}
v[x][y] = true;
dp[x][y][x][y] = 0;
while (!cola.isEmpty()) {
Node actually = cola.poll();
for (int i = 0; i < pX.length; i++) {
if (actually.i + pX[i] >= 0 && actually.i + pX[i] < arr.length
&& actually.j + pY[i] >= 0
&& actually.j + pY[i] < arr[0].length
&& v[actually.i + pX[i]][actually.j + pY[i]] == false) {
v[actually.i + pX[i]][actually.j + pY[i]] = true;
dp[x][y][actually.i + pX[i]][actually.j + pY[i]] = actually.value + 1;
cola.add(new Node(actually.i + pX[i], actually.j + pY[i],
actually.value + 1));
}
}
}
} | 9 |
private void cftfsub(int n, double[] a, int offa, int[] ip, int nw, double[] w) {
if (n > 8) {
if (n > 32) {
cftf1st(n, a, offa, w, nw - (n >> 2));
if ((ConcurrencyUtils.getNumberOfThreads() > 1) && (n > ConcurrencyUtils.getThreadsBeginN_1D_FFT_2Threads())) {
cftrec4_th(n, a, offa, nw, w);
} else if (n > 512) {
cftrec4(n, a, offa, nw, w);
} else if (n > 128) {
cftleaf(n, 1, a, offa, nw, w);
} else {
cftfx41(n, a, offa, nw, w);
}
bitrv2(n, ip, a, offa);
} else if (n == 32) {
cftf161(a, offa, w, nw - 8);
bitrv216(a, offa);
} else {
cftf081(a, offa, w, 0);
bitrv208(a, offa);
}
} else if (n == 8) {
cftf040(a, offa);
} else if (n == 4) {
cftx020(a, offa);
}
} | 9 |
private static void checkUIAvailable() {
String checkUIStr = System.getProperty(CHECK_UI);
//if not in nogui mode check for a visible window
if (Boot.isHeadless() == false && (checkUIStr == null || checkUIStr.equals("true"))) {
//We need to check for a UI. Create a Timer to Check for the UI in 30 seconds
java.util.Timer timer = new java.util.Timer(true);
timer.schedule(new TimerTask() {
public void run() {
try {
BootSecurityManager sm = (BootSecurityManager) System.getSecurityManager();
//no security manager so we don't need to test
if (sm == null) return;
if (sm.getExitClass() == null) sm.setExitClass(Boot.class);
if (!sm.checkWindowVisible()) {
String msg = Resources.bundle.getString("boot.no.user.interface");
msg = MessageFormat.format(msg, Boot.getAppDisplayName());
Boot.shutdownError(msg, null);
} else {
logger.info("Visible User Interface Detected!");
}
} catch (ClassCastException badCast) {
//Not using Our security manager can't check for UI
logger.info("Not using BootSecurityManager. Can't check for User Interface");
}
}
}, 30000); //30 seconds
} else {
logger.info("HEADLESS MODE: Not Checking for Visible User Interface.");
}
} | 7 |
@Override
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
if (status == 0) {
out.write("<option class='" + invalClass + "' value='" + value + "'>");
} else if(status == 1) {
if (date != null) {
Date currDate = new Date();
if (date.after(currDate)) {
out.write("<option class='" + valClass + "' value='" + value + "'>");
} else {
out.write("<option class='" + invalDateClass + "' value='" + value + "'>");
}
} else {
out.write("<option class='" + valClass + "' value='" + value + "'>");
}
}
} catch (IOException e) {
throw new JspTagException(e.getMessage());
}
return EVAL_BODY_INCLUDE;
} | 5 |
private RealDistribution resolveDistribution(DistributionType d){
switch(d){
case BETA: return bettafishd;
case NORMAL: return normald;
case CAUCHY: return cauchyd;
case CHISQUARED: return chid;
case EXPONENTIAL: return exponentiald;
case F: return fd;
case GAMMA: return gammad;
case LOGNORMAL: return lognormald;
default: return null;
}
} | 8 |
private void getUpgrade(RobotController rc) {
if(upgradeTwo){
if (this.upgrade==NUKE) {
this.upgrade = VISION;
} else {
this.upgrade = NUKE;
}
} else {
if(rc.hasUpgrade(PICKAXE)&&rc.hasUpgrade(DEFUSION)&&rc.hasUpgrade(FUSION))
this.upgradeTwo = true;
switch (this.upgrade) {
case PICKAXE:
this.upgrade = DEFUSION;
break;
case DEFUSION:
this.upgrade = FUSION;
break;
case FUSION:
this.upgrade = PICKAXE;
break;
}
}
if(rc.hasUpgrade(this.upgrade)) {
this.getUpgrade(rc);
}
} | 9 |
public void findAllPairsShortestPath() throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(outputFileName)));
PrintWriter log = new PrintWriter(new BufferedWriter(new FileWriter(logFileName)));
for(Map.Entry<Character,Position> s : nodes.entrySet()) {
for(Map.Entry<Character,Position> e : nodes.entrySet()) {
if(s.getKey() < e.getKey()) {
log.println("from '"+s.getKey()+"' to '"+e.getKey()+"'");
log.println("-----------------------------------------------");
findShortestPath(s.getValue(),e.getValue(),out,log);
log.println("-----------------------------------------------");
}
}
}
//System.out.println(graph);
out.close();
log.close();
} | 3 |
public static Role findByName(String name) {
for (Role role : values()) {
if (name.equalsIgnoreCase(role.name())) {
return role;
}
}
return null;
} | 2 |
@Override
public boolean createTable(String query) {
Statement statement = null;
try {
this.connection = this.open();
if (query.equals("") || query == null) {
this.writeError("SQL query empty: createTable(" + query + ")", true);
return false;
}
statement = connection.createStatement();
statement.execute(query);
return true;
} catch (SQLException e) {
this.writeError(e.getMessage(), true);
return false;
} catch (Exception e) {
this.writeError(e.getMessage(), true);
return false;
}
} | 4 |
@Test
public void testConvertToDataNode() throws FileNotFoundException {
try {
InputStream inputStream = new FileInputStream(new File("xml/example.xml"));
NodeList nodes = source.getXMLNodes(inputStream);
Node parent = nodes.item(0);
NodeList realList = parent.getChildNodes();
for (int i = 0; i < realList.getLength(); ++i) {
Node node = realList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
DataNode dataNode = source.convertToDataNode(node);
assertFalse("Data node must exists", dataNode == null);
assertTrue("The node name has to be equal", dataNode
.getName().equals(node.getNodeName()));
// Test the attributes
NamedNodeMap attributes = node.getAttributes();
if (attributes != null) {
for (int a = 0; i < attributes.getLength(); ++a) {
Node attribute = attributes.item(a);
if (attribute.getNodeType() == Node.ATTRIBUTE_NODE) {
String key = attribute.getNodeName();
String value = attribute.getNodeValue();
String dataAttribute = dataNode
.getAttribute(key);
assertTrue("Attribute '" + key
+ "' with value='" + value
+ "' must exist in data node object",
dataAttribute.equals(value));
}
}
}
}
}
} catch (ResourceException e) {
fail(e.getMessage());
}
} | 6 |
@Override
public List<AdminCol> getColSrchList(String tblNm) {
log.debug("get column search list for table = " + tblNm);
Connection conn = null;
PreparedStatement statement = null;
ResultSet rs = null;
ArrayList<AdminCol> list = new ArrayList<AdminCol>();
StringBuilder sql = new StringBuilder();
sql.append(" select tbl_nm, col_nm, dspl_nm, dspl_ord, data_type, sort_ind, sort_ord, sort_dir, srch_ind, key_ind, req_ind, meta_ind, meta_type, render_type, render_params, col_desc, max_len, dspl_tbl_ind");
sql.append(" from admin_col");
sql.append(" where tbl_nm = ?");
sql.append(" and srch_ind = 'Y'");
sql.append(" order by dspl_ord");
try {
conn = DataSource.getInstance().getConnection();
statement = conn.prepareStatement(sql.toString());
statement.setString(1, tblNm);
log.debug(sql.toString());
rs = statement.executeQuery();
while (rs.next()) {
AdminCol col = new AdminCol();
col.setTblNm(rs.getString("tbl_nm"));
col.setColNm(rs.getString("col_nm"));
col.setDsplNm(rs.getString("dspl_nm"));
col.setDsplOrd(rs.getInt("dspl_ord"));
col.setDataType(rs.getString("data_type"));
col.setSortInd(rs.getString("sort_ind"));
col.setSortOrd(rs.getInt("sort_ord"));
col.setSortDir(rs.getString("sort_dir"));
col.setSrchInd(rs.getString("srch_ind"));
col.setKeyInd(rs.getString("key_ind"));
col.setReqInd(rs.getString("req_ind"));
col.setMetaInd(rs.getString("meta_ind"));
col.setMetaType(rs.getString("meta_type"));
col.setRenderType(rs.getString("render_type"));
col.setRenderParams(rs.getString("render_params"));
col.setColDesc(rs.getString("col_desc"));
col.setMaxLen(rs.getInt("max_len"));
col.setDsplTblInd(rs.getString("dspl_tbl_ind"));
list.add(col);
}
} catch (Exception e) {
log.error("failed to get column search list for table = " + tblNm, e);
} finally {
if (rs != null) {
try { rs.close(); } catch (Exception e) {}
}
if (statement != null) {
try { statement.close(); } catch (Exception e) {}
}
if (conn != null) {
try { conn.close(); } catch (Exception e) {}
}
}
return list;
} | 8 |
public boolean goToHunter(List ants) {
Iterator<Ant> antsIterator = ants.iterator();
boolean advanceX, advanceY;
int velocityY = 1, velocityX = 1;
Ant target=null;
while (antsIterator.hasNext()) {
Ant ant = antsIterator.next();
if(target==null &&distance(this.getX_position(), ant.getX(), this.getY_position(), ant.getY()) < 200){
ant=target;
}
}
if(target!=null){
if (target.getX() > this.getX_position()) {
advanceX = true;
velocityX = 1;
} else if (target.getX() < this.getX_position()) {
advanceX = false;
velocityX = 1;
} else {
advanceX = false;
velocityX = 0;
}
if (target.getY() > this.getY_position()) {
advanceY = true;
velocityY = 1;
} else if (target.getY() < this.getY_position()) {
advanceY = false;
velocityY = 1;
} else {
advanceY = false;
velocityY = 0;
}
this.moveAntPredator(advanceX, advanceY, velocityX, velocityY);
} else {
this.moveAntPredator();
}
return false;
} | 8 |
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req, String ip) {
String uri = req.getUri();
FullHttpResponse resp = null;
if (uri.equalsIgnoreCase(STATUS)) {
ManagerDB.addOrUpdateRequestAmount(ip, dateFormat.format(new Date()));
ServerStatus.addRequest();
PageStatus page = new PageStatus();
String send = page.getPage();
ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(send, CharsetUtil.US_ASCII));
resp = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);
resp.headers().set(CONTENT_TYPE, "text/HTML");
resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
sendHttpResponse(ctx, req, resp);
trafficLog();
ManagerDB.insertConnection(ip, uri, dateFormat.format(new Date()), sentBytes, receivedBytes, speed);
} else if (uri.equalsIgnoreCase(HELLO)) {
try {
Thread.sleep(TIMESLEEP * 1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
Page page = new PageHello();
ManagerDB.addOrUpdateRequestAmount(ip, dateFormat.format(new Date()));
ServerStatus.addRequest();
String send = page.getPage();
ByteBuf buf = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(send, CharsetUtil.US_ASCII));
resp = new DefaultFullHttpResponse(HTTP_1_1, OK, buf);
resp.headers().set(CONTENT_TYPE, "text/HTML");
resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
sendHttpResponse(ctx, req, resp);
trafficLog();
ManagerDB.insertConnection(ip, uri, dateFormat.format(new Date()), sentBytes, receivedBytes, speed);
} else if (uri.toLowerCase().contains(REDIRECT) && uri.toLowerCase().contains("url")) {
ManagerDB.addOrUpdateRequestAmount(ip, dateFormat.format(new Date()));
ServerStatus.addRequest();
String redirect;
if (uri.toLowerCase().contains("http://")) {
redirect = uri.substring(14);
} else {
redirect = "http://" + uri.substring(14);
}
ByteBuf buf23 = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("", CharsetUtil.US_ASCII));
resp = new DefaultFullHttpResponse(HTTP_1_1, TEMPORARY_REDIRECT, buf23);
resp.headers().set(LOCATION, redirect);
sendHttpResponse(ctx, req, resp);
trafficLog();
ManagerDB.insertConnection(ip, uri, dateFormat.format(new Date()), sentBytes, receivedBytes, speed);
} else {
ByteBuf buf2 = Unpooled.unreleasableBuffer(Unpooled.copiedBuffer("404 page not found", CharsetUtil.US_ASCII));
resp = new DefaultFullHttpResponse(HTTP_1_1, OK, buf2);
resp.headers().set(CONTENT_TYPE, "text/plain");
resp.headers().set(CONTENT_LENGTH, resp.content().readableBytes());
sendHttpResponse(ctx, req, resp);
}
} | 6 |
protected void print() {
for (int i = 0; i < mLocalMem.size(); i++) {
System.out.println("i: " + i);
if (mLocalMem.get(i).getDescription() != null) {
System.out.println(mLocalMem.get(i).getDescription());
}
if (mLocalMem.get(i).getFromDateTime() != null) {
System.out.println(mLocalMem.get(i).getFromDateTime()
.toString());
}
if (mLocalMem.get(i).getToDateTime() != null) {
System.out.println(mLocalMem.get(i).getToDateTime().toString());
}
if (mLocalMem.get(i).getLabels() != null) {
if (!mLocalMem.get(i).getLabels().isEmpty()) {
for (int k = 0; k < mLocalMem.get(i).getLabels().size(); k++) {
System.out.println("label: "
+ mLocalMem.get(i).getLabels().get(k));
}
}
}
}
} | 7 |
public int eventOnNoExplore(int noExploreCounter, int idealLeashLength, int randomNumber) throws ExploringControlException {
double noExploreCounterD = (double) noExploreCounter;
double minLeashLenght = 4;
if (noExploreCounter < 0 || noExploreCounter > 10) { // test for good leashlenght
throw new ExploringControlException("*** Our appologies, something went wrong. ***"
+ "\n*** ERROR in GameMenuView.java ***"
+ "\nin public int eventOnNoExplore(int noExploreCounter, int idealLeashLength, int randomNumber)"
+ "\n if (noExploreCounter < 0 || noExploreCounter > 10)");
}
if (idealLeashLength < 4 || idealLeashLength > 15) {
throw new ExploringControlException("*** Our appologies, something went wrong. ***"
+ "\n*** ERROR in GameMenuView.java ***"
+ "\nin public int eventOnNoExplore(int noExploreCounter, int idealLeashLength, int randomNumber)"
+ "\n if (idealLeashLength < 4 || idealLeashLength > 15)");
}
if (randomNumber < 4 || randomNumber > 19) {
throw new ExploringControlException("*** Our appologies, something went wrong. ***"
+ "\n*** ERROR in GameMenuView.java ***"
+ "\nin public int eventOnNoExplore(int noExploreCounter, int idealLeashLength, int randomNumber)"
+ "\n if (randomNumber < 4 || randomNumber > 19)");
}
if (noExploreCounter == 0) { // test noExploreCounter not zero if zero add 1
noExploreCounterD = 1.0;
}
double randomNumberD = randomNumber; // cast int to double
double fidoLeashOverlap = minLeashLenght + .1 * noExploreCounterD * randomNumberD;
if (fidoLeashOverlap < idealLeashLength) { // test for overlap
return 0;
}
return 1; // return 1 for yes overlap
} | 8 |
public AnimationField(Color bg, Animation init, String fieldTitle) {
if (fieldTitle == null) {
fieldTitle = "";
}
if (init == null) {
init = Animation.ORIGINAL;
}
if (bg == null) {
bg = Color.WHITE;
}
create(bg, init, fieldTitle);
} | 3 |
public void draw(Graphics g) {
int i;
for (i = 0; i != 5; i++) {
setVoltageColor(g, volts[i]);
drawThickLine(g, ptEnds[i], ptCoil[i]);
}
for (i = 0; i != 4; i++) {
if (i == 1) {
continue;
}
setPowerColor(g, current[i] * (volts[i] - volts[i + 1]));
drawCoil(g, i > 1 ? -6 : 6,
ptCoil[i], ptCoil[i + 1], volts[i], volts[i + 1]);
}
g.setColor(needsHighlight() ? selectColor : lightGrayColor);
for (i = 0; i != 4; i += 2) {
drawThickLine(g, ptCore[i], ptCore[i + 1]);
}
// calc current of tap wire
current[3] = current[1] - current[2];
for (i = 0; i != 4; i++) {
curcount[i] = updateDotCount(current[i], curcount[i]);
}
// primary dots
drawDots(g, ptEnds[0], ptCoil[0], curcount[0]);
drawDots(g, ptCoil[0], ptCoil[1], curcount[0]);
drawDots(g, ptCoil[1], ptEnds[1], curcount[0]);
// secondary dots
drawDots(g, ptEnds[2], ptCoil[2], curcount[1]);
drawDots(g, ptCoil[2], ptCoil[3], curcount[1]);
drawDots(g, ptCoil[3], ptEnds[3], curcount[3]);
drawDots(g, ptCoil[3], ptCoil[4], curcount[2]);
drawDots(g, ptCoil[4], ptEnds[4], curcount[2]);
drawPosts(g);
setBbox(ptEnds[0], ptEnds[4], 0);
} | 7 |
public static String getAppropriateCode(Environmental E, Environmental RorM, List classes, List list)
{
if(CMLib.flags().isCataloged(E))
return "CATALOG-"+E.Name();
else
if(list.contains(E))
return ""+E;
else
if(((RorM instanceof Room)&&(((Room)RorM).isHere(E)))
||((RorM instanceof MOB)&&(((MOB)RorM).isMine(E))))
return (E instanceof Item)?getItemCode(classes,(Item)E):getMOBCode(classes,(MOB)E);
return E.ID();
} | 7 |
private boolean r_shortv() {
int v_1;
// (, line 49
// or, line 51
lab0: do {
v_1 = limit - cursor;
lab1: do {
// (, line 50
if (!(out_grouping_b(g_v_WXY, 89, 121)))
{
break lab1;
}
if (!(in_grouping_b(g_v, 97, 121)))
{
break lab1;
}
if (!(out_grouping_b(g_v, 97, 121)))
{
break lab1;
}
break lab0;
} while (false);
cursor = limit - v_1;
// (, line 52
if (!(out_grouping_b(g_v, 97, 121)))
{
return false;
}
if (!(in_grouping_b(g_v, 97, 121)))
{
return false;
}
// atlimit, line 52
if (cursor > limit_backward)
{
return false;
}
} while (false);
return true;
} | 8 |
public void setBirth(String birth) {
Birth = birth;
} | 0 |
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
MOB target=mob;
if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
target=(MOB)givenTarget;
if(target.fetchEffect(ID())!=null)
{
mob.tell(target,null,null,L("<S-NAME> <S-IS-ARE> already rooted."));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
invoker=mob;
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<S-NAME> become(s) rooted to the ground!"):L("^S<S-NAME> chant(s) as <S-HIS-HER> feet become rooted in the ground!^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s), but nothing more happens."));
// return whether it worked
return success;
} | 8 |
protected void prepareCanvas(int[] bits){
for(int i = 0; i < bits.length; i++){
bits[i] = GUIStandarts.backgroundColor;
}
} | 1 |
private String _smsc_read_url(String url) {
String line = "", real_url = url;
String[] param = {};
boolean is_post = (SMSC_POST || url.length() > 2000);
if (is_post) {
param = url.split("\\?",2);
real_url = param[0];
}
try {
URL u = new URL(real_url);
InputStream is;
if (is_post){
URLConnection conn = u.openConnection();
conn.setDoOutput(true);
OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), SMSC_CHARSET);
os.write(param[1]);
os.flush();
os.close();
//System.out.println("post");
is = conn.getInputStream();
}
else {
is = u.openStream();
}
InputStreamReader reader = new InputStreamReader(is, SMSC_CHARSET);
int ch;
while ((ch = reader.read()) != -1) {
line += (char)ch;
}
reader.close();
}
catch (MalformedURLException e) { // Неверно урл, протокол...
}
catch (IOException e) {
}
return line;
} | 6 |
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Settings)) {
return false;
}
Settings other = (Settings) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
} | 5 |
private void seriesTableKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_seriesTableKeyPressed
Logger.getLogger(MainInterface.class.getName()).entering(MainInterface.class.getName(), "seriesTableKeyPressed");
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
evt.consume();
albumsTable.requestFocusInWindow();
} else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
evt.consume();
startReading();
} else if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
evt.consume();
((TableRowSorter<?>)seriesTable.getRowSorter()).setRowFilter(null);
seriesTable.scrollRectToVisible(seriesTable.getCellRect(seriesTable.getSelectedRow(), 0, false));
}
Logger.getLogger(MainInterface.class.getName()).exiting(MainInterface.class.getName(), "seriesTableKeyPressed");
}//GEN-LAST:event_seriesTableKeyPressed | 4 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Vendedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Vendedor().setVisible(true);
}
});
} | 6 |
@Override
public void deserialize(Buffer buf) {
presetId = buf.readByte();
if (presetId < 0)
throw new RuntimeException("Forbidden value on presetId = " + presetId + ", it doesn't respect the following condition : presetId < 0");
position = buf.readUByte();
if (position < 0 || position > 255)
throw new RuntimeException("Forbidden value on position = " + position + ", it doesn't respect the following condition : position < 0 || position > 255");
objUid = buf.readInt();
if (objUid < 0)
throw new RuntimeException("Forbidden value on objUid = " + objUid + ", it doesn't respect the following condition : objUid < 0");
} | 4 |
@Override
public synchronized void finalize() {
try {
try {
closeDocument();
} catch (RemoteException ex) {
/* Nothing */
} catch (FileNotFoundException ex) {
/* Nothing */
} catch (MalformedURLException e) {
/* Nothing */
} catch (NotBoundException e) {
/* Nothing */
}
if (hasDocument()) {
try {
unlockDocument();
} catch (RemoteException ex) {
Logger.getLogger(AbstractClientController.class.getName()).log(Level.SEVERE, null, ex);
} catch (MalformedURLException ex) {
Logger.getLogger(AbstractClientController.class.getName()).log(Level.SEVERE, null, ex);
} catch (NotBoundException ex) {
Logger.getLogger(AbstractClientController.class.getName()).log(Level.SEVERE, null, ex);
}
}
} finally {
try {
super.finalize();
} catch (Throwable ex) {
Logger.getLogger(AbstractClientController.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 9 |
public void setInsets(Insets insets) {
if (insets != null) {
mInsets.set(insets.top, insets.left, insets.bottom, insets.right);
} else {
mInsets.set(0, 0, 0, 0);
}
} | 1 |
public String eqMember(String membername, String desc, int index) {
MemberrefInfo minfo = (MemberrefInfo)getItem(index);
NameAndTypeInfo ntinfo
= (NameAndTypeInfo)getItem(minfo.nameAndTypeIndex);
if (getUtf8Info(ntinfo.memberName).equals(membername)
&& getUtf8Info(ntinfo.typeDescriptor).equals(desc))
return getClassInfo(minfo.classIndex);
else
return null; // false
} | 2 |
public boolean move(double newBearing) {
// if the newBearing is -1, then leave it on the ground
if ((bearing == -1 && newBearing == -1))
return true;
// see if it's a legal move
if (!isLegalMove(newBearing)) {
return false;
}
// this allows bearing to be equal to 360, in which case we treat it as 0
double radialBearing = newBearing % 360;
radialBearing = (radialBearing-90) * Math.PI/180;
double newx = this.x + (Math.cos(radialBearing)*VELOCITY);
double newy = this.y + (Math.sin(radialBearing)*VELOCITY);
// make sure they're still in bounds
if (newx < 0 || newx > 100) {
System.err.println("Error! new x-coordinate position " + newx + " is out of bounds!");
return false;
}
if (newy < 0 || newy > 100) {
System.err.println("Error! new y-coordinate position " + newy + " is out of bounds!");
return false;
}
this.x = newx; //this.x + (Math.cos(bearing)*DISTANCE);
this.y = newy; //this.y + (Math.sin(bearing)*DISTANCE);
//this.bearing = bearing * 180/Math.PI;
this.bearing = newBearing;
return true;
} | 7 |
private void readLuminance() {
int type = sourceImage.getType();
if (type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB) {
int[] pixels = (int[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
int p = pixels[i];
int r = (p & 0xff0000) >> 16;
int g = (p & 0xff00) >> 8;
int b = p & 0xff;
data[i] = luminance(r, g, b);
}
} else if (type == BufferedImage.TYPE_BYTE_GRAY) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xff);
}
} else if (type == BufferedImage.TYPE_USHORT_GRAY) {
short[] pixels = (short[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xffff) / 256;
}
} else if (type == BufferedImage.TYPE_3BYTE_BGR) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
int offset = 0;
for (int i = 0; i < picsize; i++) {
int b = pixels[offset++] & 0xff;
int g = pixels[offset++] & 0xff;
int r = pixels[offset++] & 0xff;
data[i] = luminance(r, g, b);
}
} else {
throw new IllegalArgumentException("Unsupported image type: " + type);
}
} | 9 |
public static boolean isPowerProviderOrWire(IBlockAccess par0IBlockAccess, int par1, int par2, int par3, int par4)
{
int var5 = par0IBlockAccess.getBlockId(par1, par2, par3);
if (var5 == Block.redstoneWire.blockID)
{
return true;
}
else if (var5 == 0)
{
return false;
}
else if (var5 != Block.redstoneRepeaterIdle.blockID && var5 != Block.redstoneRepeaterActive.blockID)
{
if (Block.blocksList[var5] instanceof IConnectRedstone)
{
return ((IConnectRedstone)Block.blocksList[var5]).canConnectRedstone(par0IBlockAccess, par1, par2, par3, par4);
}
return Block.blocksList[var5].canProvidePower() && par4 != -1;
}
else
{
int var6 = par0IBlockAccess.getBlockMetadata(par1, par2, par3);
return par4 == (var6 & 3) || par4 == Direction.footInvisibleFaceRemap[var6 & 3];
}
} | 7 |
public int IndexOfByKMP(String q, String D) {
int m = q.length();
int n = D.length();
// get special cases out of the way
if (m == 0) { return 0; }
if (m > n) { return -1; }
LongestEquifix equiSolver = new LongestEquifix();
// E[i] holds the length of the longest equifix of q[0..i].
int[] E = equiSolver.getEquifixLength(q);
// q[0] will be aligned with D[k]
int k = 0;
// the first comparison after realignment will be q[start] vs.
// D[k+start].
int start = 0;
boolean matched = false;
while (k <= n - m && !matched) {
int i = start;
// find first mismatch
while (i < m && q.charAt(i) == D.charAt(k + i)) { ++i; }
// done if q matches D[k..k+m)
if (i == m) { return k; }
if (i == 0) {
// special case: mismatch happens at q[0] != D[k]. Shift q by 1.
k += 1;
start = 0;
} else {
// normal case: we look at the longest equifix of q[0..i).
int L = i == 0 ? 0 : E[i - 1];
// see the slides for explanation
k += i - L;
start = L;
}
}
return -1;
} | 9 |
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = new String();
int i;
i = sc.nextInt();
while (i > 0) {
str = sc.next();
String rnp = new String();
int len = str.length();
Stack<Character> stk = new Stack<Character>();
char c;
for (int k = 0; k < len; k++) {
c = str.charAt(k);
switch (c) {
case '(':
break;
case '+':
stk.push(c);
break;
case '-':
stk.push(c);
break;
case '*':
stk.push(c);
break;
case '/':
stk.push(c);
break;
case '^':
stk.push(c);
break;
case ')':
rnp = rnp + stk.pop();
break;
default:
rnp = rnp + c;
break;
}
}
System.out.println(rnp);
i--;
}
sc.close();
} | 9 |
public final void currVote() {
Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 1);
List<VoteData> votes = database.find(VoteData.class).where().ge("time", cal.getTime()).findList();
synchronized (plugin.getCurrVotes()) {
plugin.getCurrVotes().clear();
if (votes != null && votes.size() > 0) {
for (VoteData voteData : votes) {
plugin.addVote(voteData.getMinecraftUser());
}
}
}
log.info(String.format(plugin.getMessages().getString("votes.per.day"), plugin.getCurrVotes().size()));
} | 3 |
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Punto_de_Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Punto_de_Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Punto_de_Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Punto_de_Ventas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new Punto_de_Ventas().setVisible(true);
}
});
} | 6 |
public boolean addRecord(Record record){
for(Record r:table){
if(r.getUsername().compareToIgnoreCase(record.getUsername())==0){
return false;
}
}
return table.add(record);
} | 2 |
@Override
public void execute(CommandSender sender, String[] arg1) {
if (!CommandUtil.hasPermission(sender, PERMISSION_NODES)) {
sender.sendMessage(plugin.NO_PERMISSION);
return;
}
String[] list = null;
try {
list = plugin.getUtilities().getWarpList(sender);
} catch (SQLException e) {
e.printStackTrace();
}
sender.sendMessage(list[0]);
if (CommandUtil.hasPermission(sender, PERMISSION_NODES_OVERRIDE)) {
sender.sendMessage(list[1]);
}
} | 3 |
public void splash(GraphicsEngine g) throws JavaLayerException{
StdDraw.setXscale(0.0, 610); //Set scale to 500
StdDraw.setYscale(0.0, 610); //Set scale to 500
while(true){
String file = "splash/splashscreen.jpg";
//String shoot = "Portal2_sfx_portal_gun_fire_blue.mp3";
FileInputStream welcome = null;
try {
welcome = new FileInputStream("splash/welcome.mp3");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StdDraw.picture(305.0, 305.0, file, 650.0, 650.0);
final AtomicBoolean pause = new AtomicBoolean(false);
final Player player = new Player(welcome);
Thread playerThread = new Thread() {
@Override
public void run() {
try {
if(player.isComplete()){
player.play(1);
}
while (player.play(1)) {
if(pause.get()) {
LockSupport.park();
}
}
}
catch (Exception e) {
System.err.printf("%s\n", e.getMessage());
}
}
};
playerThread.start();
while(true){
pause.set(!pause.get());
if (!pause.get()) {
LockSupport.unpark(playerThread);
}
if(StdDraw.hasNextKeyTyped()){
return;
}
}
}
} | 9 |
@Override
protected void loopImpl(ServerSocket listener) throws Exception {
Socket socket = null;
try {
socket = listener.accept();
} catch(SocketTimeoutException e) {
// No-Op
}
try {
if(socket != null) {
logger.info("Socket recieved.");
InputStream iStream = socket.getInputStream();
String input = Utilities.stringify(iStream);
String output = process(input);
OutputStream oStream = socket.getOutputStream();
Utilities.push(output, oStream);
if(iStream != null) {
socket.shutdownInput();
iStream.close();
}
if(oStream != null) {
socket.shutdownOutput();
oStream.close();
}
}
} finally {
if(socket != null) {
socket.close();
}
}
} | 5 |
public SubProcess getNextSubProcess(State state) {
if (state == null) return null;
reSortSubProcesses();
SubProcess sp = state.getSubProcess();
if (sp == null
|| !this.subProcesses.contains(sp)
|| this.subProcesses.indexOf(sp) >= this.subProcesses.size() - 1) return null;
return this.subProcesses.get(this.subProcesses.indexOf(sp) + 1);
} | 4 |
public ProfileEntry checkAvailability(int reqPE, double startTime,
long duration) {
Iterator<ProfileEntry> it = avail.itValuesFromPrec(startTime);
if (!it.hasNext()) {
return null;
}
PERangeList intersec = it.next().getAvailRanges().clone();
double finishTime = startTime + duration;
// Scans the availability profile until the expected termination
// of the job to check whether enough PEs will be available for it.
while(it.hasNext()) {
ProfileEntry entry = it.next();
if(entry.getTime() >= finishTime || intersec.getNumPE() < reqPE) {
break;
}
intersec = intersec.intersection(entry.getAvailRanges());
}
return (intersec.getNumPE() >= reqPE) ?
new Entry(startTime, intersec) : null;
} | 5 |
private static String myCrypt(String password, String seed) throws RuntimeException {
String out = null;
int count = 8;
MessageDigest digester;
// Check for correct Seed
if (!seed.substring(0, 3).equals("$H$")) {
// Oh noes! Generate a seed and continue.
byte[] randomBytes = new byte[6];
java.util.Random randomGenerator = new java.util.Random();
randomGenerator.nextBytes(randomBytes);
seed = genSalt(randomBytes);
}
String salt = seed.substring(4, 12);
if (salt.length() != 8) {
throw new RuntimeException("Error hashing password - Invalid seed.");
}
byte[] sha1Hash = new byte[40];
try {
digester = MessageDigest.getInstance("SHA-1");
digester.update((salt + password).getBytes("iso-8859-1"), 0, (salt + password).length());
sha1Hash = digester.digest();
do {
byte[] CombinedBytes = new byte[sha1Hash.length + password.length()];
System.arraycopy(sha1Hash, 0, CombinedBytes, 0, sha1Hash.length);
System.arraycopy(password.getBytes("iso-8859-1"), 0, CombinedBytes, sha1Hash.length, password.getBytes("iso-8859-1").length);
digester.update(CombinedBytes, 0, CombinedBytes.length);
sha1Hash = digester.digest();
} while (--count > 0);
out = seed.substring(0, 12);
out += encode64(sha1Hash);
} catch (NoSuchAlgorithmException Ex) {
System.err.println("Error hashing password." + Ex);
} catch (UnsupportedEncodingException Ex) {
System.err.println("Error hashing password." + Ex);
}
if (out == null) {
throw new RuntimeException("Error hashing password - out = null");
}
return out;
} | 6 |
@Override
public boolean equals(Object o) {
if (o == null) { // fast fail
return false;
}
if ((o == this) || (o == payload)) { // fast success
return true;
}
if (!(o instanceof CachedValue)) { // cope with non-cached values
return o.equals(payload);
}
return ((CachedValue) o).payload.equals(payload); // cope with cached values
} | 4 |
private void checkForPrompt()
{
// Text has been entered, remove the prompt
if (document.getLength() > 0)
{
setVisible( false );
return;
}
// Prompt has already been shown once, remove it
if (showPromptOnce && focusLost > 0)
{
setVisible(false);
return;
}
// Check the Show property and component focus to determine if the
// prompt should be displayed.
if (component.hasFocus())
{
if (show == Show.ALWAYS
|| show == Show.FOCUS_GAINED)
setVisible( true );
else
setVisible( false );
}
else
{
if (show == Show.ALWAYS
|| show == Show.FOCUS_LOST)
setVisible( true );
else
setVisible( false );
}
} | 8 |
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Ball other = (Ball) obj;
if (this.color != other.color) {
return false;
}
if (this.coords != other.coords && (this.coords == null || !this.coords.equals(other.coords))) {
return false;
}
return true;
} | 6 |
public static void testValidity(Object o) throws JSONException {
if (o != null) {
if (o instanceof Double) {
if (((Double)o).isInfinite() || ((Double)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
} else if (o instanceof Float) {
if (((Float)o).isInfinite() || ((Float)o).isNaN()) {
throw new JSONException(
"JSON does not allow non-finite numbers.");
}
}
}
} | 7 |
public final List<Answer> getAnswers()
{
final Random rand = new Random();
final Answer[] ans = new Answer[this.answers.length];
boolean hasBottom = false;
for (final Answer a : this.answers)
{
if (a.dispStr.equals(Card_Question.BOTTOM_ANSWER))
{
hasBottom = true;
}
}
for (final Answer a : this.answers)
{
if (a.dispStr.equals(Card_Question.BOTTOM_ANSWER))
{
ans[ans.length - 1] = a;
continue;
}
int pos = rand.nextInt(ans.length);
while (ans[pos] != null && (!hasBottom || hasBottom && pos != ans.length - 1))
{
pos = rand.nextInt(ans.length);
}
ans[pos] = a;
}
final List<Answer> ret = new ArrayList<Answer>();
for (final Answer a : ans)
{
ret.add(a);
}
return ret;
} | 9 |
public void provideCapacity(final int capacity) {
if (c.length >= capacity) {
return;
}
int newcapacity = ((capacity * 3) >> 1) + 1;
char[] newc = new char[newcapacity];
System.arraycopy(c, 0, newc, 0, length);
c = newc;
} | 1 |
public void init()
{
boolean debug = CommandLine.booleanVariable("debug");
if (debug)
{
// Enable debug logging
Logger logger = Logger.getLogger("com.reuters.rfa");
logger.setLevel(Level.FINE);
Handler[] handlers = logger.getHandlers();
if (handlers.length == 0)
{
Handler handler = new ConsoleHandler();
handler.setLevel(Level.FINE);
logger.addHandler(handler);
}
for (int index = 0; index < handlers.length; index++)
handlers[index].setLevel(Level.FINE);
}
Context.initialize();
// Create a Session
String sessionName = CommandLine.variable("session");
_session = Session.acquire(sessionName);
if (_session == null)
{
System.out.println("Could not acquire session.");
Context.uninitialize();
System.exit(1);
}
System.out.println("RFA Version: " + Context.getRFAVersionInfo().getProductVersion());
// Create an Event Queue
_eventQueue = EventQueue.create("myEventQueue");
// Create a OMMPool.
_pool = OMMPool.create();
// Create an OMMEncoder
_encoder = _pool.acquireEncoder();
_encoder.initialize(OMMTypes.MSG, 5000);
// Initialize client for login domain.
_loginClient = new BatchViewLoginClient(this);
// Initialize item manager for item domains
_itemManager = new BatchViewItemManager(this);
// Initialize directory client for directory domain.
_directoryClient = new BatchViewDirectoryClient(this);
// Create an OMMConsumer event source
_ommConsumer = (OMMConsumer)_session.createEventSource(EventSource.OMM_CONSUMER,
"myOMMConsumer", true);
// Application may choose to down-load the enumtype.def and
// RWFFldDictionary
// This example program loads the dictionaries from file only.
String fieldDictionaryFilename = CommandLine.variable("rdmFieldDictionary");
String enumDictionaryFilename = CommandLine.variable("enumType");
try
{
GenericOMMParser.initializeDictionary(fieldDictionaryFilename, enumDictionaryFilename);
}
catch (DictionaryException ex)
{
System.out.println("ERROR: Unable to initialize dictionaries.");
System.out.println(ex.getMessage());
if (ex.getCause() != null)
System.err.println(": " + ex.getCause().getMessage());
cleanup(-1);
return;
}
// Send login request
// Application must send login request first
_loginClient.sendRequest();
} | 6 |
protected String unFilterString(String str)
{
final StringBuffer buf=new StringBuffer(str);
for(int i=0;i<buf.length()-1;i++)
if(buf.charAt(i)=='\\')
switch(buf.charAt(i+1))
{
case '\\':
buf.deleteCharAt(i);
break;
case 't':
buf.deleteCharAt(i);
buf.setCharAt(i,'\t');
break;
case 'r':
buf.deleteCharAt(i);
buf.setCharAt(i,'\r');
break;
case 'n':
buf.deleteCharAt(i);
buf.setCharAt(i,'\n');
break;
case '\"':
buf.deleteCharAt(i);
break;
}
return buf.toString();
} | 7 |
public boolean jsFunction_waitStartProgress(int timeout) {
deprecated();
int curr = 0; if(timeout == 0) timeout = 10000;
while(!JSBotUtils.hourGlass)
{
if(curr > timeout)
return false;
Sleep(25);
curr += 25;
}
return true;
} | 3 |
public List<User> getInitialUserForSecondActivityCluster(List<FirstActivityCluster> facList,
List<SleepingCluster> scList, List<User> allUserList) {
List<User> returnUserList = new ArrayList<>();
for (SleepingCluster sc : scList) {
for (User user : allUserList) {
if (sc.getUserID() == user.getId()) {
returnUserList.add(user);
break;
}
}
}
ClusterCommons cc = new ClusterCommons();
for (User user : returnUserList) {
List<Posts> postList = user.getUserPost();
System.out.println("Before Deleting " + user.getId() + "-->" + user.getUserPost().size());
for (FirstActivityCluster facObj : facList) {
if (facObj.getUserID() == user.getId()) {
int[] facTimeVector = facObj.getUserCluster();
List<Posts> toSetList = new ArrayList<>();
for (Posts post : postList) {
Timestamp ts = Timestamp.valueOf(new SimpleDateFormat("yyyy-MM-dd ").format(new Date()).concat(post.getTime()));
int timeCategory = cc.getTimeCategory(ts.getHours());
if (facTimeVector[timeCategory] == 0) {
toSetList.add(post);
}
}
user.setUserPost(toSetList);
System.out.println("After Deleting " + user.getId() + "-->" + user.getUserPost().size());
System.out.println("---------------");
break;
}
}
}
return returnUserList;
} | 8 |
public SudokuGame(){
File f = new File("Sudoku.sudoku");
Scanner sc = null;
try{
sc = new Scanner(f);
}
catch (FileNotFoundException e){
e.printStackTrace();
System.out.println("File doesn't exist");
System.exit(1);
}
Color c = Color.BLACK;
for (int i=0;i<9;i++){
for (int j=0;j<9;j++){
String temp=sc.next();
if (temp.equals("_")) temp="";
gameGrid[i][j]=new GenericButton(c, "sudoku", temp);
}
}
for (int i=0;i<9;i++){
this.setConstraint(0,i,9,1);
}
for (int i=0; i<9;i++){
this.setConstraint(i,0,1,9);
}
for (int i=0; i<9;i+=3){
for (int j=0; j<9;j+=3){
this.setConstraint(i,j,3,3);
}
}
} | 8 |
private void generateSongStructure(File songsDirectory) {
songList.getItems().clear();
for(File songFolder : songsDirectory.listFiles()) {
//Check that only directories are processed
if(songFolder.isDirectory() || songFolder.listFiles() == null) {
if(!songFolder.canRead()) {
InfoDialog errorDiag = new InfoDialog("Could not read from chosen folder");
errorDiag.show();
return;
}
//Find .osu files in folder and process them
try {
for(File osuFile : songFolder.listFiles()) {
int indexOfExtension = osuFile.getName().lastIndexOf('.');
if(indexOfExtension == -1)
continue;
String extension = osuFile.getName().substring(indexOfExtension);
if(extension.equals(".osu")) {
songList.getItems().add(new OsuFile(osuFile));
break; //We only need one .osu file per song folder
}
}
}
catch(Exception e) {
InfoDialog errorDiag = new InfoDialog("Could not read from chosen folder");
errorDiag.show();
return;
}
}
}
//Check that there was any songs found at all
if(songList.getItems().isEmpty()) {
InfoDialog errorDiag = new InfoDialog("Could not locate any songs, are you sure you chose the osu/songs folder?");
errorDiag.show();
}
else {
//Entries on the list should be compared alphabetically by title
Comparator<OsuFile> compare = new Comparator<OsuFile>() {
@Override
public int compare(OsuFile o1, OsuFile o2) {
return o1.meta.getSongname().compareTo(o2.meta.getSongname());
}
};
FXCollections.sort(songList.getItems(), compare);
}
} | 9 |
private void computeNext() {
int i = k - 1;
int j = k;
// find smallest j > k - 1 where a[j] > a[k - 1]
while (j < n && a[i] >= a[j]) {
++j;
}
if (j < n) {
swap(i, j);
} else {
reverseRightOf(i);
// i = (k - 1) - 1
--i;
while (i >= 0 && a[i] >= a[i + 1]) {
--i;
}
if (i < 0) {
hasNext = false;
return;
}
// j = n - 1
--j;
while (j > i && a[i] >= a[j]) {
--j;
}
swap(i, j);
reverseRightOf(i);
}
} | 8 |
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
if (axis == Axis.X_AXIS)
{
int height = getIconHeight();
for (Icon icon : icons)
{
int iconY = getOffset(height, icon.getIconHeight(), alignmentY);
icon.paintIcon(c, g, x, y + iconY);
x += icon.getIconWidth() + gap;
}
}
else if (axis == Axis.Y_AXIS)
{
int width = getIconWidth();
for (Icon icon : icons)
{
int iconX = getOffset(width, icon.getIconWidth(), alignmentX);
icon.paintIcon(c, g, x + iconX, y);
y += icon.getIconHeight() + gap;
}
}
else // must be Z_AXIS
{
int width = getIconWidth();
int height = getIconHeight();
for (Icon icon : icons)
{
int iconX = getOffset(width, icon.getIconWidth(), alignmentX);
int iconY = getOffset(height, icon.getIconHeight(), alignmentY);
icon.paintIcon(c, g, x + iconX, y + iconY);
}
}
} | 5 |
public GnuNeutron (String computer_algorithme)
{
autodisplay = true;
display = 1;
computerColour = NeutronBoard.BLACK;
playerName = "";
ponder = true;
nb = new NeutronBoard ();
if (computer_algorithme.equals("random"))
{
cp = new ComputerPlayerRandom ();
}
else if (computer_algorithme.equals ("simple"))
{
cp = new ComputerPlayerSimple ();
}
else if (computer_algorithme.equals ("minimax"))
{
cp = new ComputerPlayerMinimax ();
}
else if (computer_algorithme.equals ("uct"))
{
cp = new ComputerPlayerUct ();
}
else if (computer_algorithme.equals("alphabeta"))
{
cp=new ComputerPlayerAlphaBeta();
}
else {
cp=new ComputerPlayerAlphaBeta();
}
moveHistory=new ArrayList<String>();
} | 5 |
private void doPrint(String aInText, Throwable aInT)
{
switch (this)
{
case WARN:
case ERROR:
case DEATH:
if (null == stream)
{
System.err.println(aInText);
if (null != aInT)
{
aInT.printStackTrace();
}
}
else
{
stream.report(aInText);
origErr.println(aInText);
if (null != aInT)
{
aInT.printStackTrace();
aInT.printStackTrace(origErr);
}
}
break;
default:
if (null == stream)
{
System.err.println(aInText);
if (null != aInT)
{
aInT.printStackTrace();
}
}
else
{
stream.report(aInText);
if (null != aInT)
{
aInT.printStackTrace();
}
}
break;
}
} | 9 |
public void resetPlplayer()
{
start = false;
if (P1character.equals("White"))
{
whiteKnight.reset(100,450,true);
}
else if (P1character.equals("Bond"))
{
jamesBond.reset(100,450,true);
}
else if (P1character.equals("Ninja"))
{
redNinja.reset(100,450,true);
}
else if (P1character.equals("Mage"))
{
purpleMage.reset(100,450,true);
}
markGreen.reset(100,450,true);
} | 4 |
public Song(String filePath) {
measures = new ArrayList<Measure>();
titleCards = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = in.readLine()) != null) {
if (line.length() > 0) {
switch(line.charAt(0)) {
case 'm':
case 'r':
case 's':
measures.add(new Measure(line));
break;
case 't':
parseTitleCard(line);
break;
}
}
}
in.close();
} catch (FileNotFoundException e) {
System.err.println("Song file not found: " + filePath);
e.printStackTrace();
} catch (IOException e) {
System.err.println("Problem loading song: " + filePath);
e.printStackTrace();
}
} | 8 |
public int getMove(int place1,int place2) {
if (System.currentTimeMillis() - c.lastSpear < 4000)
return 0;
if ((place1 - place2) == 0) {
return 0;
} else if ((place1 - place2) < 0) {
return 1;
} else if ((place1 - place2) > 0) {
return -1;
}
return 0;
} | 4 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.