blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
417ee1b2fcf4d17c389c4f8a3d547a935e18c652
|
Java
|
RichardRoda/2017-CodePaLOUsa-Lambda
|
/sample/examples/src/main/java/com/richard/roda/lambda/stream/StreamCollect.java
|
UTF-8
| 1,117
| 3.3125
| 3
|
[
"Apache-2.0"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.richard.roda.lambda.stream;
import java.util.Comparator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
*
* @author Richard
*/
public class StreamCollect {
public static void main(String[] args) throws Exception {
List<Integer> ints = IntStream.of(1,2,2,3,4,5).boxed()
.collect(Collectors.toList());
System.out.println(ints);
Set<Integer> intSet = IntStream.of(1,2,2,3,4,5).boxed()
.collect(Collectors.toSet());
System.out.println(intSet);
// Custom collection type with a sort applied to it.
LinkedHashSet<Integer> sortedSet = IntStream.of(1,2,2,3,4,5).boxed()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toCollection(LinkedHashSet::new));
System.out.println(sortedSet);
}
}
| true
|
c340b4185a36a6db8ef3d191409c62f276d1f59e
|
Java
|
arthurschneider/csv-print
|
/src/main/java/de/aschneider/csvprint/formatter/Formatter.java
|
UTF-8
| 107
| 1.914063
| 2
|
[] |
no_license
|
package de.aschneider.csvprint.formatter;
public interface Formatter {
String format(Object object);
}
| true
|
29edc6a00a16176a76c7530960a6ca50f40a889e
|
Java
|
ryanvarick/jEAC
|
/edu/indiana/cs/eac/driver/USBDriver.java
|
UTF-8
| 29,697
| 2.203125
| 2
|
[] |
no_license
|
/**
* USBDriver.java - Driver for USB-based uEACs.
*
* @version 1.0.0
*
* @author Adam Miller
* @author Ryan R. Varick
*
* Copyright (C) 2006. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
*/
package edu.indiana.cs.eac.driver;
import java.io.*;
import java.util.*;
import javax.swing.*;
import gnu.io.*;
import edu.indiana.cs.eac.*;
import edu.indiana.cs.eac.exceptions.*;
import javax.swing.*;
public class USBDriver implements HAL, Serializable
{
// print useful debugging information when enabled
private static boolean DEBUG = false;
// driver configuration
private String portName;
private int baudRate;
// communication channels
private transient SerialPort serialPort;
private transient InputStream inputStream;
private transient OutputStream outputStream;
private transient String dataString; // raw, ready-to-process reply
public static boolean okFound; // flow control
// known-bad port strings -- as we test the uEAC on new architectures,
// we learn more about what valid USB ports look like. Right now, we
// do not know enough to support known good ports; rather, we are enumerating
// ports that cause problems here.
//
// NOTE: these entries are case-insenstive
private static final String[] IGNORED_PORTS = new String[]
{
"lpt", // Windows: printer ports
"modem", // OSX/Linux: modem devices can cause problems
"bluetooth", // OSX: bluetooth devices cause all kinds of problems
"cu", // OSX: duplicates tty entries
};
// driver parameters
private static final int NUM_ROWS = 5;
private static final int NUM_COLS = 5;
private static final int NUM_CONNECTION_TYPES = 4; // TODO: (DEF) support for LLA_SRC/LLA_SNK starts here
private static final String CURRENT_UNIT = "uA";
private static final int MIN_CURRENT = 0;
private static final int MAX_CURRENT = 200;
private static final int MAX_LLAS = 10;
private static final int LLA_ARGS = 8;
private static final int NUM_OF_LLA_FUNCTIONS = 27; // TODO: (DEF) support for user-defined LLAs starts here
private static final int TIMEOUT_MILLIS = 1000;
// LLA bookkeeping
private static final int INSUFFICIENT_LLAS = -1;
private static final int INVALID_INDEX = -1;
private static final int NULL_VALUE = -1;
private int[][] llaArray; // stores what the driver knows about the LLAs
private static final int X_IN = 0;
private static final int Y_IN = 1;
private static final int X_OUT = 2;
private static final int Y_OUT = 3;
private static final int FUNCTION = 4;
private static final int REFRESH_RATE = 5;
private static final int INPUT_VALUE = 6;
private static final int OUTPUT_VALUE = 7;
// node allocation
private JEACNode nodes[];
private NodeMap nodemap;
// LED state
private boolean ledsEnabled;
// cached copy of the gradient
private double[][] lastGradient;
/**
* Constructor - instantiates a new USBDriver.
*
* @param String port - name of the port to connect to
*
*/
public USBDriver(String portName)
{
this.portName = portName;
this.baudRate = 19200;
// initialize the gradient cache
lastGradient = getBlankVoltageGradient();
// allocate JEACNodes
nodes = new JEACNode[NUM_ROWS * NUM_COLS];
for(int i = 0; i < NUM_ROWS * NUM_COLS; i++)
{
nodes[i] = new JEACNode();
}
// instantiate a NodeMap
nodemap = new NodeMap(this);
// LLA bookkeeping
this.llaArray = new int[MAX_LLAS][LLA_ARGS];
initLLAs();
// according to the uEAC specs, LEDs are enabled by default
this.ledsEnabled = true;
}
/**
* INTERNAL - Constructor - for internal use only.
*
*/
public USBDriver() { /* Do nothing */ }
/**
* Debugging method.
*
* @param String[] args - command line arguemnts are ignored
*
*/
public static void main(String args[])
{
String[] drivers = USBDriver.getDeviceList();
System.out.println("Connecting to: " + drivers[0]);
USBDriver driver = new USBDriver(drivers[0]);
try
{
driver.connect();
driver.reset();
driver.disconnect();
}
catch(Exception e)
{
System.out.println("Connection failed: " + e.getMessage());
e.printStackTrace();
}
}
/* ===============[ LAYER 0: LOW-LEVEL (internal) COMMUNICATION ]=============== */
/**
* Writes a command to the uEAC.
*
* @param String message - sentence to write
* @return boolean - status
*
*/
private synchronized boolean writeSentence(String message)
{
return writeSentence(message, false);
}
/**
* (unsafe) Writes a command to the uEAC, bypassing normal timeout checking.
*
* @param String message - sentence to write
* @param boolean waitForever - whether to bypass timeout checking or not
* @return boolean - status
*
*/
private synchronized boolean writeSentence(String message, boolean waitForever)
{
// these two print statements are good for debugging
if(DEBUG) { System.out.println("Writing: " + message); }
message = message + "\n";
char[] bytes = message.toCharArray();
try
{
for(int i = 0; i < bytes.length; i++)
{
this.writeChar(bytes[i]);
}
outputStream.flush();
}
catch (IOException e)
{
System.err.println("Error sending sentence.");
}
/*
* Here's our complicated little spinlock -- Normally, the event listener is
* assumed to prepare data for us in a certain time window (TIMEOUT_MILLIS).
* When waitForever is specified, however, we will wait an indefinte period of time
* for the command to complete. Further, we DO NOT assume that the response is
* going to be well-formed, hence the conditional based on the content of dataString.
*
*/
long start = System.currentTimeMillis();
while((!okFound && System.currentTimeMillis() - start < TIMEOUT_MILLIS) || (waitForever && dataString == null))
{
// spin baby spin
}
// okFound should be true by now, or the command timed out
if(!okFound)
{
if(DEBUG) { System.out.println("Command timed out."); }
return false;
}
else
{
if(DEBUG) { System.out.println("Response: " + dataString); }
okFound = false;
return true;
}
}
/**
* (internal only) Write an individual character to the uEAC.
* Adam tells me that this is the reason life sucks... I believe him.
*
* @param outputByte - character to write
*
*/
private synchronized void writeChar(char outputByte)
{
try
{
outputStream.write(outputByte);
outputStream.flush();
}
catch (IOException e)
{
System.err.println("Error sending byte.");
}
}
/* ===============[ LAYER 1: CONNECT/DISCONNECT ]===============*/
// API-mapped
public void connect() throws ConnectionException
{
try
{
CommPortIdentifier portID = CommPortIdentifier.getPortIdentifier(portName);
serialPort = (SerialPort) portID.open("Serial Port" + portName, 2000);
// set up communication parameters
try
{
serialPort.setSerialPortParams(baudRate, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
}
catch (UnsupportedCommOperationException e)
{
System.err.println("Error setting serial port parameters.");
throw new IOException();
}
// create communication channels
try
{
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
}
catch (IOException e)
{
throw new ConnectionException("Error setting up I/O streams.");
}
// add communication listeners
try
{
serialPort.addEventListener(new USBEventListener());
serialPort.notifyOnDataAvailable(true);
}
catch (TooManyListenersException e)
{
throw new ConnectionException("Error adding event listeners.");
}
}
catch (Exception e)
{
throw new ConnectionException("Error connecting; serial port in use.");
}
}
// API-mapped
public void disconnect()
{
if(serialPort != null)
{
try
{
inputStream.close();
outputStream.close();
}
catch (IOException e)
{
System.err.println("Error closing I/O streams.");
}
serialPort.close();
serialPort = null;
}
else
{
System.err.println("Tried to disconnect a null serial port.");
}
}
// API-mapped
public void reload() throws ConnectionException
{
// de-allocate nodes
for(int i = 0; i < nodes.length; i++)
{
try
{
nodes[i].setType(JEACNode.OFF);
nodes[i].setValue(0.0);
}
catch(Exception e)
{
System.err.println("Could not reset node.");
}
}
reset();
}
// API-mapped
public void reset()
{
// use the unsafe write method since RST takes a while
writeSentence("RST", true);
// BUGFIX: (1473311) reset LLA bookkeeping
initLLAs();
}
/* ===============[ LAYER 2: BASIC uEAC INTERACTION ]=============== */
/**
* Returns a blank voltage gradient (all values = 0.0). Useful when
* a driver call is not necessary or desired.
*
* @return double[][] - blank voltage gradient
*
*/
private double[][] getBlankVoltageGradient()
{
double[][] numbers = new double[NUM_ROWS][NUM_COLS];
for (int i = 0; i < numbers.length; i++)
{
for (int j = 0; j < numbers[i].length; j++)
{
numbers[i][j] = 0.0;
}
}
return numbers;
}
// API-mapped
public double[][] getVoltageGradient() throws IOException
{
double[][] numbers = new double[NUM_ROWS][NUM_COLS];
if(writeSentence("p,v"))
{
try
{
StringTokenizer tokenizer = new StringTokenizer(dataString, ",");
for (int i = 0; i < numbers.length; i++)
{
for (int j = 0; j < numbers[i].length; j++)
{
String s = tokenizer.nextToken();
numbers[j][i] = Double.parseDouble(s); // BUGFIX: (1477024) reversed gradient representation
}
}
}
// if something happens, and we can't process the gradient, return the cached copy
catch(Exception e)
{
System.err.println("Processing gradient failed, returning previous gradient.");
numbers = lastGradient;
}
}
else
{
System.err.println("Could not retrieve voltage gradient.");
}
// cache the gradient and return
lastGradient = numbers;
return numbers;
}
/**
* Write current to the EAC.
*
* @param int y - x-coordinate of the channel to write
* @param int x - y-coordinate of the channel to write
* @param int amount - amount of current to write
* (postive for sources, negative for sinks)
*
*/
public void setCurrent(int xLocation, int yLocation, int amount)
{
writeSentence("w,i," + xLocation + "," + yLocation + "," + amount);
}
/**
* Read current from the EAC.
*
* @param int x - x-coordinate of the point to read
* @param int y - y-coordinate of the point to read
*
* @return double - current at the point
*
*/
public double readCurrent(int xLocation, int yLocation)
{
writeSentence("r,i," + xLocation + "," + yLocation + ",100");
StringTokenizer tokenizer = new StringTokenizer(dataString, ",");
double value = Double.parseDouble(tokenizer.nextToken());
return value;
}
/**
* Read voltage from the EAC.
*
* @param int x - x-coordinate of the point to read
* @param int y - y-coordiante of the point to read
*
* @return double - voltage at the point
*
*/
public double readVoltage(int xLocation, int yLocation)
{
writeSentence("r,v," + xLocation + "," + yLocation + ",100");
StringTokenizer tokenizer = new StringTokenizer(dataString, ",");
double value = Double.parseDouble(tokenizer.nextToken());
return value;
}
/**
* Toggle the LED display. If the LEDs are off, they will be turned on;
* otherwise, they will be disabled.
*
* TODO: This should probably be setLEDStatus(boolean), or something...
*
*/
public void toggleLEDs()
{
String sentence = "";
if(ledsEnabled) sentence = "LOF";
else sentence = "LON";
boolean success = writeSentence(sentence);
if(success) ledsEnabled = !ledsEnabled;
else
{
JOptionPane.showMessageDialog(null, "Could not toggle uEAC LEDs; command \"" + sentence + "\"failed.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Returns the status of the LED display.
*
* @return boolean status - true = on, false = off
*
*/
public boolean getLEDStatus()
{
return ledsEnabled;
}
/**
* Toggle debug state. When enabled, driver debug information (mainly the I/O command trace)
* will be sent to stdout.
*
* @param boolean - debug status
*
*/
public static void setDebug(boolean status)
{
DEBUG = status;
}
/**
* Returns whether debugging is enabled or disabled
*
* @return boolean - debug status
*
*/
public static boolean getDebug()
{
return DEBUG;
}
/* --------------------[ LLA HARDWARE CONTROL (API) ]-------------------- */
//
// NOTE: These methods manage LLAs in hardware.
//
/**
* Adds an LLA to the uEAC.
*
* @param int x_in - input coordinates
* @param int y_in
* @param int x_out - output coordinates (0,0 for none)
* @param int y_out
* @param int function - LLA function (1-27)
* @param int refresh - refresh rate (1-255)
*
* @return boolean - status
*
*/
public boolean addLLA(int x_in, int y_in, int x_out, int y_out, int function, int refresh)
{
// try to allocate an LLA
int id = allocateLLA();
if(id == INSUFFICIENT_LLAS)
{
// BUGFIX: (1476439) No feedback when allocation fails
JOptionPane.showMessageDialog(null, "Insufficient LLAs: the uEAC supports a maximum of 10 LLAs.", "Insufficient LLAs", JOptionPane.ERROR_MESSAGE);
return false;
}
// map to hardware, convert the 0-based function to 1-based
mapLLA(id, x_in, y_in, x_out, y_out, function + 1, refresh);
return writeLLACommand(id, 'A');
}
/**
* Enables an existing LLA on the uEAC.
*
* @param int id - LLA to enable
*
* @return boolean - status
*
*/
public boolean enableLLA(int id)
{
return writeLLACommand(id, 'E');
}
/**
* Disables an existing LLA on the uEAC.
*
* @param int id - LLA to disable
*
* @return boolean - status
*
*/
public boolean disableLLA(int id)
{
// first remove from hardware, then de-allocate
boolean status = writeLLACommand(id, 'D');
freeLLA(id);
return status;
}
/**
* Reads the values of an existing LLA on the uEAC.
*
* @param int id - LLA to report
*
* @return int[] values - LLA values
*
*/
public int[] reportLLA(int id)
{
boolean status = writeLLACommand(id, 'R');
// the results are stored in the dataString, split on commas
// and convert the first two values (third is OK)
String[] pieces = dataString.split(",");
int values[] = new int[2];
values[0] = Integer.parseInt(pieces[0]);
values[1] = Integer.parseInt(pieces[1]);
return values;
}
/**
* (internal) Reads each active LLA and stores the results in <code>llaArray</code>.
*
*/
private void readAllLLAs()
{
for(int i = 0; i < llaArray.length; i++)
{
if(llaArray[i][X_IN] != NULL_VALUE)
{
int lla_values[] = reportLLA(i);
llaArray[i][INPUT_VALUE] = lla_values[0];
llaArray[i][OUTPUT_VALUE] = lla_values[1];
}
}
}
/**
* (internal) Writes an LLA command to the uEAC. This method reads
* the (assumed to be set) parameters from <code>llaArray</code>.
*
* @param int id - LLA to write
* @param char instruction - command to issue (one of: A,D,E,R)
*
* @return boolean - status
*
* @see http://www.cs.indiana.edu/~bhimebau/ueac/uEACos/doc/interpreter_doc/index.html
*
*/
private boolean writeLLACommand(int id, char instruction)
{
int params[] = getLLAParams(id);
String command = "L," + instruction + "," +
params[0] + "," + params[1] + "," +
params[2] + "," + params[3] + "," +
(id + 1) + "," + // correct 0-based ID to 1-based
params[4] + "," + params[4];
return writeSentence(command);
}
/* --------------------[ LLA HARDWARE CONTROL (Internal) ]------------------- */
//
// NOTE: These methods are responsible for keeping track of LLAs on the driver side.
//
/**
* Allocates a new LLA.
*
* @return int id - new, 0-based LLA identifier;
* or <code>INSUFFICIENT_LLAS</code> if allocation fails
*
*/
private int allocateLLA()
{
// look for the first open slot
for(int i = 0; i < llaArray.length; i++)
{
if(llaArray[i][X_IN] == NULL_VALUE && llaArray[i][Y_IN] == NULL_VALUE) return i;
}
return INSUFFICIENT_LLAS;
}
/**
* Un-maps and frees (de-allocates) an existing LLA.
*
* @param int id - LLA to de-allocate
*
*/
private void freeLLA(int id)
{
llaArray[id][X_IN] = NULL_VALUE;
llaArray[id][Y_IN] = NULL_VALUE;
llaArray[id][X_OUT] = NULL_VALUE;
llaArray[id][Y_OUT] = NULL_VALUE;
llaArray[id][FUNCTION] = NULL_VALUE;
llaArray[id][REFRESH_RATE] = NULL_VALUE;
llaArray[id][INPUT_VALUE] = NULL_VALUE;
llaArray[id][OUTPUT_VALUE] = NULL_VALUE;
}
/**
* Returns the identifier for the LLA at the given index.
*
* @param int x - coordinates of the LLA
* @param int y
*
* @return int id - LLA identifier;
* or <code>INVALID_INDEX</code> if the index was not found
*
*/
private int getLLAIndex(int x, int y)
{
for(int i = 0; i < llaArray.length; i++)
{
if(llaArray[i][X_IN] == x && llaArray[i][Y_IN] == y) return i;
}
return INVALID_INDEX;
}
/**
* Returns the driver-stored paramaters of an existing LLA.
*
* @param int id - LLA to lookup
*
* @return int[] params - current LLA parameters:
* x_in, y_in, x_out, y_out, function, refresh rate, input, output
*
*/
private int[] getLLAParams(int id)
{
return llaArray[id];
}
/**
* Frees (de-allocates) all LLAs.
*
*/
private void initLLAs()
{
for(int i = 0; i < llaArray.length; i++)
{
freeLLA(i);
}
}
/**
* Records an LLA as in use.
*
* @param int id - LLA to map to hardware
* @param int x_in - input coordinates
* @param int y_in
* @param int x_out - output coordinates (0,0 for none)
* @param int y_out
* @param int function - LLA function (1-27)
* @param int refresh - refresh rate (1-255)
*
*/
private void mapLLA(int id, int x_in, int y_in, int x_out, int y_out, int function, int refresh)
{
llaArray[id][X_IN] = x_in;
llaArray[id][Y_IN] = y_in;
llaArray[id][X_OUT] = x_out;
llaArray[id][Y_OUT] = y_out;
llaArray[id][FUNCTION] = function;
llaArray[id][REFRESH_RATE] = refresh;
}
/* ====================[ LAYER 3: GET METHODS ]==================== */
// API-mapped
public String getDeviceName()
{
// serialPort.getName();
return this.portName;
}
// API-mapped
public int getNumRows()
{
return NUM_ROWS;
}
// API-mapped
public int getNumReportingRows()
{
return this.getNumRows();
}
// API-mapped
public int getNumCols()
{
return NUM_COLS;
}
// API-mapped
public int getNumReportingCols()
{
return this.getNumCols();
}
// API-mapped
public String getCurrentUnit()
{
return CURRENT_UNIT;
}
// API-mapped
public int getMaxCurrent()
{
return MAX_CURRENT;
}
// API-mapped
public int getMinCurrent()
{
return MIN_CURRENT;
}
// API-mapped
public int getNumLLAFunctions()
{
return NUM_OF_LLA_FUNCTIONS;
}
// API-mapped
public int getNumConnectionTypes()
{
return NUM_CONNECTION_TYPES;
}
// API-mapped
public int getNumLLAs()
{
// int count = 0;
// for(int i = 0; i < llaArray.length; i++)
// {
// if(llaArray[i][X_IN] != NULL_VALUE && llaArray[i][Y_IN] != NULL_VALUE) count++;
// }
// return count;
return MAX_LLAS;
}
// API-mapped
public String[] getAllLLAInputValues()
{
String values[] = new String[getNumLLAs()];
//
// HACK: LLA reporting is one command. We don't want to duplicate
// effort, and we know that getAllInput/getAllOutput methods are
// called sequentially, so we'll go ahead and read here.
// getAllOutput will read cached values.
//
readAllLLAs();
int count = 0;
for(int i = 0; i < llaArray.length; i++)
{
if(llaArray[i][INPUT_VALUE] != NULL_VALUE)
{
int in = Math.abs(llaArray[i][INPUT_VALUE]);
values[count++] = Integer.toString(in);
}
}
return values;
}
// API-mapped
public String[] getAllLLAOutputValues()
{
String values[] = new String[getNumLLAs()];
int count = 0;
for(int i = 0; i < llaArray.length; i++)
{
if(llaArray[i][OUTPUT_VALUE] != NULL_VALUE)
{
int out = Math.abs(llaArray[i][OUTPUT_VALUE]);
values[count++] = Integer.toString(out);
}
}
return values;
}
/* ----------------[ JEAC-specifc Interaction ]--------------- */
// API-mapped
public JEACNode[] getJEACNodes()
{
return this.nodes;
}
// API-mapped
public NodeMap getNodeMap()
{
return this.nodemap;
}
// API-mapped
public boolean changeNode(String newType, double newValue, JEACNode node)
{
int index = getNodeIndex(node);
int coords[] = getNodeCoordinates(index);
// reset the node off when (1) OFF is request or (2) the type changes
if(newType.equals(JEACNode.OFF) || !node.getType().equals(newType))
{
resetNode(node);
}
// set or update a source
if(newType.equals(JEACNode.SOURCE))
{
setCurrent(coords[0], coords[1], (int)newValue);
}
// set or update a sink
else if(newType.equals(JEACNode.SINK))
{
setCurrent(coords[0], coords[1], -1 * (int)newValue);
}
// set or update an LLA (also BUGFIX for 1473313)
else if(newType.equals(JEACNode.LLA))
{
// BUGFIX: (1473306) look for an existing LLA at this point; if it exists, disable it
int id = getLLAIndex(coords[0], coords[1]);
if(id != USBDriver.INVALID_INDEX)
{
disableLLA(id);
}
addLLA(coords[0], coords[1], 0, 0, (int)newValue, 1);
enableLLA(getLLAIndex(coords[0], coords[1]));
}
// now let's save things locally
try
{
nodes[index].setType(newType);
nodes[index].setValue(newValue);
}
catch(Exception e)
{
System.err.println("Driver error: could not update node[" + index + "].");
}
return true;
}
/**
* Resets a node to the OFF state.
*
* @param node - node to reset
*
*/
private void resetNode(JEACNode node)
{
int index = getNodeIndex(node);
int coords[] = getNodeCoordinates(index);
if(node.isType(JEACNode.OFF))
{
/* Do nothing, already off. */
}
// reset sources and sinks to 0 uA
else if(node.isType(JEACNode.SOURCE) || node.isType(JEACNode.SINK))
{
setCurrent(coords[0], coords[1], 0);
}
else if(node.isType(JEACNode.LLA))
{
disableLLA(getLLAIndex(coords[0], coords[1]));
}
else
{
System.err.println("Illegal node type: " + node.getType());
}
// HACK: We need to set the node's value to 0 here to erase the value
// (I call this a HACK because we should only be reading from nodes
// here, not setting their values)
node.setValue(0);
}
/**
* Given a node, returns its index in the node array.
*
* @param node - node to find
* @return int - index of the node (-1 if the node does not exist)
*/
private int getNodeIndex(JEACNode node)
{
for(int i = 0; i < nodes.length; i++)
{
if(node == nodes[i])
{
return i;
}
}
return -1;
}
/**
* Given an index into the node array, returns its X-Y mapping.
*
* @param index - array index (0-based)
* @return int[] - X-Y coordinates (1-based)
*
*/
private int[] getNodeCoordinates(int index)
{
// BUGFIX: (1477024) reversed the coordinates
return new int[]
{
index % getNumCols() + 1,
(int)Math.floor(index / getNumCols()) + 1,
};
}
/* ====================[ UTILITY METHODS ]==================== */
/**
* Return the list of valid devices for this driver class.
*
* @return String[] - list of devices
*
*/
public static String[] getDeviceList()
{
Object[] ports = USBDriver.getPortList();
String[] portList = new String[ports.length];
for(int i = 0; i < ports.length; i++)
{
portList[i] = ((CommPortIdentifier)ports[i]).getName();
}
// OSX on Mills' iBook *only*
// String[] portList = new String[]
// {
// "/dev/tty.usbserial-191A"
// };
return portList;
}
/**
* Lists available ports that RXTX knows about.
*
* @return Object[] - list of know ports
*
*/
public static Object[] getPortList()
{
// retrive the list of known COMM ports
Enumeration ports = CommPortIdentifier.getPortIdentifiers();
// now look for at each port
Vector validPorts = new Vector();
while(ports.hasMoreElements())
{
CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
// check for ignored ports
boolean try_port = true;
for(int i = 0; i < IGNORED_PORTS.length; i++)
{
if(port.getName().toLowerCase().contains(IGNORED_PORTS[i].toLowerCase()))
{
if(DEBUG) System.out.println("\n" + port.getName() + " known bad, ignoring...");
try_port = false;
}
}
// now probe the port
if(try_port)
{
if(DEBUG) System.out.println("\nProbing " + port.getName() + "...");
// try to connect, then probe the driver
boolean isValid = false;
try
{
USBDriver driver = new USBDriver(port.getName());
driver.connect();
if(driver.writeSentence("NOK_TEST")) { isValid = true; }
driver.disconnect();
}
catch(Exception e) { /* Do nothing. */ }
if(isValid)
{
validPorts.add(port);
if(DEBUG) System.out.println(port.getName() + " is valid.");
}
else
{
if(DEBUG) System.out.println(port.getName() + " is not valid.");
}
}
}
return validPorts.toArray();
}
/**
* Sleep for the given amount number of milliseconds. I noticed a lot
* of sleep statements, so I packaged them into their own static method.
*
* @param int - time to sleep, in milliseconds
*
*/
private static void sleep(int time)
{
try
{
Thread.sleep(time);
}
catch (InterruptedException e)
{
System.err.println("Someone interrupted sleep.");
}
}
/* ====================[ LISTENERS ]==================== */
/**
* Listens for communication from the serial port.
*
*/
private class USBEventListener implements SerialPortEventListener
{
public void serialEvent(SerialPortEvent event)
{
dataString = null;
okFound = false;
String readString = "";
byte[] buffer = new byte[10000000];
int bufferSize = 0;
// only respond when data-available events
if(event.getEventType() != SerialPortEvent.DATA_AVAILABLE)
{
return;
}
try
{
while(inputStream.available() > 0)
{
int amountToBeRead = inputStream.available();
if(amountToBeRead > buffer.length)
{
amountToBeRead = buffer.length;
}
bufferSize = inputStream.read(buffer, 0, amountToBeRead);
USBDriver.sleep(20);
}
if(readString == null)
{
readString = new String(buffer, 0, bufferSize);
}
else
{
readString = readString.concat(new String(buffer, 0, bufferSize));
}
}
catch (IOException e)
{
System.err.println("Error in USB event, closing down shop.");
System.err.println(e);
serialPort.close();
}
if(readString.lastIndexOf('>') == (bufferSize - 2))
{
okFound = true;
dataString = readString.substring(0, (bufferSize - 7));
}
}
}
}
| true
|
af19be1e93301ed679fe50c6195b4e413901fef0
|
Java
|
GustGimenez/TP02_IA
|
/TP02_IA/src/codigos/main.java
|
UTF-8
| 1,325
| 2.375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package codigos;
import IU.IUprincipal;
/**
*
* @author fabio
*/
public class main {
public static void main(String[] args) {
// Resolve tab = new Resolve(3, 3);
// int[][] tabOriginal = new int[3][3];
// tab.exibe();
// System.out.println("------------------");
// tab.embaralha(500);
// tab.copyArray(tab.getTab(), tabOriginal);
// tab.exibe();
// System.out.println("--------EXECUÇÃO H1----------");
// tab.buscaH1();
// tab.exibe();
// tab.copyArray(tabOriginal, tab.getTab());
// System.out.println("--------EXECUÇÃO H2----------");
// tab.buscaH2();
// tab.exibe();
// tab.copyArray(tabOriginal, tab.getTab());
// System.out.println("------------------");
// System.out.println("--------EXECUÇÃO HP----------");
// tab.buscaHPessoal();
// tab.exibe();
// System.out.println("------------------");
// System.out.println(tab.getNumJogadas());
IUprincipal janela = new IUprincipal();
janela.setVisible(true);
}
}
| true
|
bb5196304e27d8cf30c696246eaebe8a7498e643
|
Java
|
KevinBaffo/ChessGame
|
/boardGames/src/com/squares/SquareColor.java
|
UTF-8
| 63
| 1.648438
| 2
|
[] |
no_license
|
package com.squares;
public enum SquareColor {
LIGHT, DARK
}
| true
|
2a14b9b8c004b490a33583f13b17488f086155cb
|
Java
|
jaxbriggs/projeto_inteligencia_artificial
|
/src/main/java/br/edu/fatec/projeto_ia/GeradorServlet.java
|
UTF-8
| 18,970
| 2.21875
| 2
|
[] |
no_license
|
package br.edu.fatec.projeto_ia;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import weka.core.Instances;
import static java.lang.System.out;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import weka.classifiers.lazy.IB1;
import weka.classifiers.lazy.IBk;
import weka.classifiers.trees.Id3;
import weka.core.Instance;
/**
*
* @author Carlos Henrique
*/
@MultipartConfig
public class GeradorServlet extends HttpServlet {
XSSFWorkbook workbook;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Pega o arquivo arff do cliente
Part filePart = request.getPart("file");
if(filePart.getSubmittedFileName().equals("statec-nominal.arff")){
InputStream fileContent = filePart.getInputStream();
File f = StreamUtil.stream2file(fileContent);
FileReader leitor = new FileReader(f);
Instances baseArff = new Instances(leitor);
baseArff.setClassIndex(7);
Id3 arvore = new Id3();
Map<Integer, String> realResults = new TreeMap<>();
Map<Integer, String> id3Results = new TreeMap<>();
String[][] comparacoesId3 = new String[134][2];
try{
arvore.buildClassifier(baseArff);
for(int i = 0; i < baseArff.numInstances(); i++){
Instance teste = baseArff.instance(i);
realResults.put(i, baseArff.classAttribute().value((int)teste.classValue()));
comparacoesId3[i][0] = baseArff.classAttribute().value((int)teste.classValue());
teste.setClassMissing();
//Id3
double classeId3 = arvore.classifyInstance(teste);
id3Results.put(i, baseArff.classAttribute().value((int)classeId3));
comparacoesId3[i][1] = baseArff.classAttribute().value((int)classeId3);
}
//System.out.println(arvore);
} catch (Exception ex) {
out.println("Erro ao classificar instancias!");
ex.printStackTrace();
}
try
{
FileInputStream file = new FileInputStream(new File(getServletContext().getRealPath("/") + "matriz_ia.xlsx"));
workbook = new XSSFWorkbook (file);
XSSFSheet avaliador = workbook.getSheetAt(0);
XSSFSheet matriz = workbook.getSheetAt(1);
int rowCount = 0, cellCount = 0;
//Preenche os reais
rowCount = 1; cellCount = 0;
Iterator it3 = realResults.entrySet().iterator();
while (it3.hasNext()) {
Map.Entry pair = (Map.Entry)it3.next();
XSSFRow row;
row = avaliador.getRow(rowCount);
Cell cell = row.getCell(cellCount);
cell.setCellValue(pair.getValue().toString());
rowCount++;
it3.remove();
}
//Preenche os resultados ID3
rowCount = 1; cellCount = 3;
Iterator it = id3Results.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
XSSFRow row;
row = avaliador.getRow(rowCount);
Cell cell = row.getCell(cellCount);
cell.setCellValue(pair.getValue().toString());
rowCount++;
it.remove();
}
String[] classes = {"aneuploid", "diploid", "tetraploid"};
//Comeca a preencher a matriz de confusao
//ID3
int[][] id3Confusao = new int[3][3];
int aa = 0, ad = 0, at = 0,
da = 0, dd = 0, dt = 0,
ta = 0, td = 0, tt = 0;
for(int j = 0; j < 134; j++){
//Aneuploide/X
if(classes[0].equals(comparacoesId3[j][0]) && classes[0].equals(comparacoesId3[j][1])){
aa++;
} else if(classes[0].equals(comparacoesId3[j][0]) && classes[1].equals(comparacoesId3[j][1])) {
ad++;
} else if(classes[0].equals(comparacoesId3[j][0]) && classes[2].equals(comparacoesId3[j][1])) {
at++;
}
//Diploide/X
if(classes[1].equals(comparacoesId3[j][0]) && classes[0].equals(comparacoesId3[j][1])){
da++;
} else if(classes[1].equals(comparacoesId3[j][0]) && classes[1].equals(comparacoesId3[j][1])) {
dd++;
} else if(classes[1].equals(comparacoesId3[j][0]) && classes[2].equals(comparacoesId3[j][1])) {
dt++;
}
//Tetraploide/X
if(classes[2].equals(comparacoesId3[j][0]) && classes[0].equals(comparacoesId3[j][1])){
ta++;
} else if(classes[2].equals(comparacoesId3[j][0]) && classes[1].equals(comparacoesId3[j][1])) {
td++;
} else if(classes[2].equals(comparacoesId3[j][0]) && classes[2].equals(comparacoesId3[j][1])) {
tt++;
}
}
id3Confusao[0][0] = aa;
id3Confusao[0][1] = ad;
id3Confusao[0][2] = at;
id3Confusao[1][0] = da;
id3Confusao[1][1] = dd;
id3Confusao[1][2] = dt;
id3Confusao[2][0] = ta;
id3Confusao[2][1] = td;
id3Confusao[2][2] = tt;
//Popula a matriz na planilha
//ID3
XSSFRow row;
cellCount = 16;
for(int i = 0; i < 3; i++){
row = matriz.getRow(2+i);
for(int j = 0; j < 3; j++){
Cell cell = row.getCell(cellCount);
cell.setCellValue(id3Confusao[i][j]);
cellCount++;
}
cellCount = 16;
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=matriz_confusao.xlsx");
workbook.write(response.getOutputStream());
response.getOutputStream().close();
} else if(filePart.getSubmittedFileName().equals("statec.arff")) {
InputStream fileContent = filePart.getInputStream();
File f = StreamUtil.stream2file(fileContent);
FileReader leitor = new FileReader(f);
Instances baseArff = new Instances(leitor);
baseArff.setClassIndex(7);
//baseArff.resample(new Random());
Map<Integer, String> realResults = new TreeMap<>();
Map<Integer, String> ib1Results = new TreeMap<>();
String[][] comparacoesIb1 = new String[146][2];
String[][] comparacoesIbk = new String[146][2];
Map<Integer, String> knnResults = new TreeMap<>();
IB1 classificador = new IB1();
IBk classificadorIbk = new IBk(Integer.parseInt(request.getParameter("kval")));
try {
for(int i = 0; i < baseArff.numInstances(); i++){
Instances exemplosTeste = baseArff.testCV(baseArff.numInstances(), i);
Instances exemplosTreino = baseArff.trainCV(baseArff.numInstances(), i);
classificador.buildClassifier(exemplosTreino);
classificadorIbk.buildClassifier(exemplosTreino);
Instance teste = exemplosTeste.instance(0);
realResults.put(i, baseArff.classAttribute().value((int)teste.classValue()));
comparacoesIb1[i][0] = baseArff.classAttribute().value((int)teste.classValue());
comparacoesIbk[i][0] = baseArff.classAttribute().value((int)teste.classValue());
teste.setClassMissing();
//Ib1
double classeIb1 = classificador.classifyInstance(teste);
ib1Results.put(i, baseArff.classAttribute().value((int)classeIb1));
comparacoesIb1[i][1] = baseArff.classAttribute().value((int)classeIb1);
//Knn
double classeIbk = classificadorIbk.classifyInstance(teste);
knnResults.put(i, baseArff.classAttribute().value((int)classeIbk));
comparacoesIbk[i][1] = baseArff.classAttribute().value((int)classeIbk);
}
} catch (Exception ex) {
out.println("Erro ao classificar instancias!");
ex.printStackTrace();
}
try
{
FileInputStream file = new FileInputStream(new File(getServletContext().getRealPath("/") + "matriz_ia.xlsx"));
workbook = new XSSFWorkbook (file);
XSSFSheet avaliador = workbook.getSheetAt(0);
XSSFSheet matriz = workbook.getSheetAt(1);
int rowCount = 0, cellCount = 0;
//Preenche os reais
rowCount = 1; cellCount = 0;
Iterator it3 = realResults.entrySet().iterator();
while (it3.hasNext()) {
Map.Entry pair = (Map.Entry)it3.next();
XSSFRow row;
row = avaliador.getRow(rowCount);
Cell cell = row.getCell(cellCount);
cell.setCellValue(pair.getValue().toString());
rowCount++;
it3.remove();
}
//Preenche os resultados knn
rowCount = 1; cellCount = 1;
Iterator it = knnResults.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
XSSFRow row;
row = avaliador.getRow(rowCount);
Cell cell = row.getCell(cellCount);
cell.setCellValue(pair.getValue().toString());
rowCount++;
it.remove();
}
//Preenche os resultados vizinho mais proximo
rowCount = 1; cellCount = 2;
Iterator it2 = ib1Results.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry pair = (Map.Entry)it2.next();
XSSFRow row;
row = avaliador.getRow(rowCount);
Cell cell = row.getCell(cellCount);
cell.setCellValue(pair.getValue().toString());
rowCount++;
it2.remove();
}
String[] classes = {"aneuploid", "diploid", "tetraploid"};
//Comeca a preencher a matriz de confusao
//KNN
int[][] ibkConfusao = new int[3][3];
int aa = 0, ad = 0, at = 0,
da = 0, dd = 0, dt = 0,
ta = 0, td = 0, tt = 0;
for(int j = 0; j < 146; j++){
//Aneuploide/X
if(classes[0].equals(comparacoesIbk[j][0]) && classes[0].equals(comparacoesIbk[j][1])){
aa++;
} else if(classes[0].equals(comparacoesIbk[j][0]) && classes[1].equals(comparacoesIbk[j][1])) {
ad++;
} else if(classes[0].equals(comparacoesIbk[j][0]) && classes[2].equals(comparacoesIbk[j][1])) {
at++;
}
//Diploide/X
if(classes[1].equals(comparacoesIbk[j][0]) && classes[0].equals(comparacoesIbk[j][1])){
da++;
} else if(classes[1].equals(comparacoesIbk[j][0]) && classes[1].equals(comparacoesIbk[j][1])) {
dd++;
} else if(classes[1].equals(comparacoesIbk[j][0]) && classes[2].equals(comparacoesIbk[j][1])) {
dt++;
}
//Tetraploide/X
if(classes[2].equals(comparacoesIbk[j][0]) && classes[0].equals(comparacoesIbk[j][1])){
ta++;
} else if(classes[2].equals(comparacoesIbk[j][0]) && classes[1].equals(comparacoesIbk[j][1])) {
td++;
} else if(classes[2].equals(comparacoesIbk[j][0]) && classes[2].equals(comparacoesIbk[j][1])) {
tt++;
}
}
ibkConfusao[0][0] = aa;
ibkConfusao[0][1] = ad;
ibkConfusao[0][2] = at;
ibkConfusao[1][0] = da;
ibkConfusao[1][1] = dd;
ibkConfusao[1][2] = dt;
ibkConfusao[2][0] = ta;
ibkConfusao[2][1] = td;
ibkConfusao[2][2] = tt;
//KNN
int[][] ib1Confusao = new int[3][3];
aa = 0; ad = 0; at = 0;
da = 0; dd = 0; dt = 0;
ta = 0; td = 0; tt = 0;
for(int j = 0; j < 146; j++){
//Aneuploide/X
if(classes[0].equals(comparacoesIb1[j][0]) && classes[0].equals(comparacoesIb1[j][1])){
aa++;
} else if(classes[0].equals(comparacoesIb1[j][0]) && classes[1].equals(comparacoesIb1[j][1])) {
ad++;
} else if(classes[0].equals(comparacoesIb1[j][0]) && classes[2].equals(comparacoesIb1[j][1])) {
at++;
}
//Diploide/X
if(classes[1].equals(comparacoesIb1[j][0]) && classes[0].equals(comparacoesIb1[j][1])){
da++;
} else if(classes[1].equals(comparacoesIb1[j][0]) && classes[1].equals(comparacoesIb1[j][1])) {
dd++;
} else if(classes[1].equals(comparacoesIb1[j][0]) && classes[2].equals(comparacoesIb1[j][1])) {
dt++;
}
//Tetraploide/X
if(classes[2].equals(comparacoesIb1[j][0]) && classes[0].equals(comparacoesIb1[j][1])){
ta++;
} else if(classes[2].equals(comparacoesIb1[j][0]) && classes[1].equals(comparacoesIb1[j][1])) {
td++;
} else if(classes[2].equals(comparacoesIb1[j][0]) && classes[2].equals(comparacoesIb1[j][1])) {
tt++;
}
}
ib1Confusao[0][0] = aa;
ib1Confusao[0][1] = ad;
ib1Confusao[0][2] = at;
ib1Confusao[1][0] = da;
ib1Confusao[1][1] = dd;
ib1Confusao[1][2] = dt;
ib1Confusao[2][0] = ta;
ib1Confusao[2][1] = td;
ib1Confusao[2][2] = tt;
//Popula a matriz na planilha
//Knn
XSSFRow row;
cellCount = 2;
for(int i = 0; i < 3; i++){
row = matriz.getRow(2+i);
for(int j = 0; j < 3; j++){
Cell cell = row.getCell(cellCount);
cell.setCellValue(ibkConfusao[i][j]);
cellCount++;
}
cellCount = 2;
}
//Vizinho mais proximo
cellCount = 9;
for(int i = 0; i < 3; i++){
row = matriz.getRow(2+i);
for(int j = 0; j < 3; j++){
Cell cell = row.getCell(cellCount);
cell.setCellValue(ib1Confusao[i][j]);
cellCount++;
}
cellCount = 9;
}
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
XSSFFormulaEvaluator.evaluateAllFormulaCells(workbook);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=matriz_confusao.xlsx");
workbook.write(response.getOutputStream());
response.getOutputStream().close();
}
}
@Override
public String getServletInfo() {
return "Servlet que cria a matriz de confusão dinâmicamente.";
}
}
| true
|
b8dfc1f66a1a953d596f29c31ed5b9fd618828f1
|
Java
|
zhaozhiqiang8090/spring-boot
|
/spring-boot-basic/src/main/java/com/zzq/basic/java/generic/Identifier.java
|
UTF-8
| 358
| 2.5625
| 3
|
[] |
no_license
|
package com.zzq.basic.java.generic;
import java.util.Collection;
public class Identifier<T extends Collection<T>> {
private T field;
public T getField() {
return field;
}
public void setField(T field) {
//可以使用限定类型List的方法
System.out.println(field.size());
this.field = field;
}
}
| true
|
909bfc845da5f2f6e348d76b09b322f5a45e8d7e
|
Java
|
hjc851/SourceCodePlagiarismDetectionDataset
|
/Entire Dataset/4-35/Programming/Grr/GrrProcedure.java
|
UTF-8
| 643
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
package Programming.Grr;
import Debugging.Multitasking;
import Debugging.Phase;
public class GrrProcedure extends Phase {
public static final double total = 0.29404132872535604;
private int sentenceTeleportation = 0;
public GrrProcedure(Phase p) {
super(p);
this.sentenceTeleportation = Debugging.JunctureTremendous;
}
public synchronized int sustainThingLibido() {
double constrain = 0.6755380572399858;
return sentenceTeleportation;
}
public synchronized void settledPeriodsGigantic(int periodQualitative) {
double symbol = 0.8018450915621291;
this.sentenceTeleportation = periodQualitative;
}
}
| true
|
c771c41d6b99d8dace5a18aab3c95e0d41e548c1
|
Java
|
dcbenas/CS2340
|
/CS2340Project/CS2340Project/src/com/CeramicKoala/cs2340/activities/AccountHomeActivity.java
|
UTF-8
| 3,499
| 2.453125
| 2
|
[] |
no_license
|
package com.CeramicKoala.cs2340.activities;
import java.text.NumberFormat;
import com.CeramicKoala.cs2340.R;
import com.CeramicKoala.cs2340.model.Account;
import com.CeramicKoala.cs2340.model.AlertDialogManager;
import com.CeramicKoala.cs2340.model.SessionManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class AccountHomeActivity extends Activity {
private NumberFormat currencyFormatter;
private AlertDialogManager alertManager;
private SessionManager sessionManager;
//passed into report activity, then used to determine which type of report to create & display
private int followUp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_home);
// instantiate all helper objects
sessionManager = new SessionManager(this);
//DEPRECATED intent = getIntent();
alertManager = new AlertDialogManager(this);
currencyFormatter = NumberFormat.getCurrencyInstance();
// update view if user is logged in
if (sessionManager.hasCurrentAccount()) {
// get formatted account balance
Account currentAccount = sessionManager.getAccount();
String balanceString = currencyFormatter.format(currentAccount.getBalance());
// update login message textview
TextView loginMessageTextView = (TextView) findViewById(R.id.login_message);
String loginMessage = currentAccount.getName();
loginMessageTextView.setText(loginMessage);
// update balance textview
TextView balanceMessageTextView = (TextView) findViewById(R.id.current_balance);
String balanceMessage = getString(R.string.balance_message) + " "+ balanceString;
balanceMessageTextView.setText(balanceMessage);
} else {
// there is no current account set
alertManager.generateAlertDialog(
AlertDialogManager.AlertType.ACCOUNT_DOES_NOT_EXIST)
.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logged_in, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.log_out:
sessionManager.logOut();
startActivity(new Intent(this, MainActivity.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// DEPRECATED
// protected Intent getIntent(Class<?> activityClass) {
//
// Intent intent = new Intent(this, activityClass);
// return intent;
// }
public void startTransaction(View view) {
startActivity(new Intent(this, TransactionActivity.class));
}
//DEPRECATED - MOVED TO USER MENU
/*public void generateReport(View view) {
followUp = 0;
Intent intent = new Intent(this, ReportActivity.class);
intent.putExtra("followUpDecision", followUp);
startActivity(intent);
}*/
public void getTransactionHistory(View view) {
followUp = 1;
Intent intent = new Intent(this, ReportActivity.class);
intent.putExtra("followUpDecision", followUp);
startActivity(intent);
}
}
| true
|
91c5dde42dc31aef9182f43d7180e02b77281d7e
|
Java
|
sanguolingzi/yhtz
|
/productservice/src/main/java/com/yinhetianze/business/product/service/impl/ProductDetailInfoServiceImpl.java
|
UTF-8
| 1,217
| 1.945313
| 2
|
[] |
no_license
|
package com.yinhetianze.business.product.service.impl;
import com.yinhetianze.business.product.service.ProductDetailInfoService;
import com.yinhetianze.pojo.product.ProductDetailPojo;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.yinhetianze.business.product.mapper.ProductDetailInfoMapper;
import java.util.List;
import java.util.Map;
@Service
public class ProductDetailInfoServiceImpl implements ProductDetailInfoService
{
@Autowired
private ProductDetailInfoMapper mapper;
@Override
public List<Map<String, Object>> getProductDetail(Map<String, Object> params)
{
return mapper.getProductDetailList(params);
}
@Override
public ProductDetailPojo selectProductDetailPojo(ProductDetailPojo productDetailPojo){
return mapper.selectOne(productDetailPojo);
}
@Override
public List<ProductDetailPojo> productDetailList(ProductDetailPojo productDetailPojo){
return mapper.select(productDetailPojo);
}
@Override
public List<Map<String,Object>> getShopProductDetail(Map<String,Object> detailParam){
return mapper.getShopProductDetail(detailParam);
}
}
| true
|
3fc0aab86303e9200936da4495b68b0b6508b25b
|
Java
|
humq1992/mylearningroad
|
/idea_workplace/basiccode/itheimaDay09/src/test03/worker.java
|
UTF-8
| 219
| 2.4375
| 2
|
[] |
no_license
|
package test03;
public class worker extends works{
public worker(String name, String num) {
super(name, num);
}
@Override
public void work(){
System.out.println("服务顾客");
}
}
| true
|
17f249eac1704e33c2f6945f8835b8e670a00330
|
Java
|
classtest/sonartest
|
/password/test/com/luv2code/password/util/PasswordUtilsTest.java
|
UTF-8
| 2,440
| 2.734375
| 3
|
[] |
no_license
|
package com.luv2code.password.util;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Chad Darby, darby@luv2code.com
*/
public class PasswordUtilsTest {
public PasswordUtilsTest() {
}
@Test
public void validatePassword_Null() {
// setup
String password = null;
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_EmptyString() {
// setup
String password = "";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneNumber() {
// setup
String password = "Abcdefg#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneUpperCaseLetter() {
// setup
String password = "abcdefg5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneLowerCaseLetter() {
// setup
String password = "ABCDEFG5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_Missing_OneSymbol() {
// setup
String password = "Abcdefg5";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
@Test
public void validatePassword_AllRulesMet() {
// setup
String password = "Abcdefg5#";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertTrue(actual);
}
@Test
public void validatePassword_LengthTooLong() {
// setup
String password = "Abcdefg5#abcdefgabcd";
// execute
boolean actual = PasswordUtils.validatePassword(password);
// assert
assertFalse(actual);
}
}
| true
|
32d09f61a223ed926c453036afc3f202a8e599fc
|
Java
|
Serya32/pruebaAsd
|
/activosFijosBackEnd/src/main/java/co/com/activoFijo/controller/PersonaController.java
|
UTF-8
| 1,155
| 2.09375
| 2
|
[] |
no_license
|
package co.com.activoFijo.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import co.com.activoFijo.dto.PersonaDTO;
import co.com.activoFijo.entity.Ciudad;
import co.com.activoFijo.services.IPersonaService;
@RestController("persona")
@CrossOrigin(origins = "*")
public class PersonaController {
private static final Logger logger = LoggerFactory.getLogger(Ciudad.class);
@Autowired
IPersonaService personaService;
@GetMapping(value = {"/api/getPersona"}, produces = "application/json")
public ResponseEntity<List<PersonaDTO>> getPersona() {
logger.info("getPersona");
try {
return new ResponseEntity<>(personaService.getPersona(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
| true
|
634cf33a8922bfa81122fc27a01fa07ac25978dc
|
Java
|
695137400/apic_src
|
/src/com/uzmap/pkg/openapi/Html5EventListener.java
|
UTF-8
| 570
| 1.945313
| 2
|
[] |
no_license
|
package com.uzmap.pkg.openapi;
import android.text.TextUtils;
import com.uzmap.pkg.uzcore.e;
public abstract class Html5EventListener {
private final int a;
public Html5EventListener(String eventName) {
if (TextUtils.isEmpty(eventName)) {
throw new IllegalArgumentException("eventName can not be empty");
} else {
this.a = e.a(eventName);
}
}
public final boolean matching(int h5event) {
return this.a == h5event;
}
public abstract void onReceive(WebViewProvider var1, Object var2);
}
| true
|
03cf9071ef13e32458a0886f09257387f336d7e5
|
Java
|
tbressler/waterrower-core
|
/src/test/java/de/tbressler/waterrower/io/msg/interpreter/TestErrorMessageInterpreter.java
|
UTF-8
| 1,524
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package de.tbressler.waterrower.io.msg.interpreter;
import de.tbressler.waterrower.io.msg.AbstractMessage;
import de.tbressler.waterrower.io.msg.in.ErrorMessage;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;
/**
* Tests for class ErrorMessageInterpreter.
*
* @author Tobias Bressler
* @version 1.0
*/
public class TestErrorMessageInterpreter {
/* Class under test. */
private ErrorMessageInterpreter interpreter;
// Mocks:
private ErrorMessage errorMessage = mock(ErrorMessage.class, "errorMessage");
@Before
public void setUp() {
interpreter = new ErrorMessageInterpreter();
}
@Test
public void getMessageTypeChar_returnsERROR() {
assertEquals("ERROR", interpreter.getMessageIdentifier());
}
@Test
public void isSupported_withSupportedMessage_returnsTrue() {
ErrorMessage msg = mock(ErrorMessage.class, "message");
assertTrue(interpreter.isSupported(msg));
}
@Test
public void isSupported_withUnsupportedMessage_returnsTrue() {
AbstractMessage msg = mock(AbstractMessage.class, "message");
assertFalse(interpreter.isSupported(msg));
}
@Test
public void decode_withValidMessage_returnsErrorMessage() {
assertNotNull(interpreter.decode("ERROR"));
}
@Test(expected = IllegalStateException.class)
public void encode_throwsIllegalStateException() {
interpreter.encode(errorMessage);
}
}
| true
|
7d47cdd98fa45b10ec93e045904c8efd0c741ac2
|
Java
|
stevelorddremio/nessie
|
/tools/apprunner-gradle-plugin/src/main/java/org/projectnessie/quarkus/gradle/QuarkusAppPlugin.java
|
UTF-8
| 3,889
| 1.9375
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) 2020 Dremio
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.projectnessie.quarkus.gradle;
import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.tasks.testing.Test;
@SuppressWarnings("Convert2Lambda") // Gradle complains when using lambdas (build-cache won't wonk)
public class QuarkusAppPlugin implements Plugin<Project> {
static final String START_TASK_NAME = "nessie-quarkus-start";
static final String STOP_TASK_NAME = "nessie-quarkus-stop";
static final String EXTENSION_NAME = "nessieQuarkusApp";
/**
* The configuration that contains the Quarkus server application as the only dependency.
*/
static final String APP_CONFIG_NAME = "nessieQuarkusServer";
/**
* The configuration that contains optional runtime dependencies, if required.
*/
static final String RUNTIME_CONFIG_NAME = "nessieQuarkusRuntime";
/**
* INTERNAL configuration that extends {@link #APP_CONFIG_NAME} + {@link #RUNTIME_CONFIG_NAME}.
*/
static final String LAUNCH_CONFIG_NAME = "nessieQuarkusLaunch";
@Override
public void apply(Project target) {
QuarkusAppExtension extension = target.getExtensions().create(EXTENSION_NAME, QuarkusAppExtension.class, target);
Configuration appConfig = target.getConfigurations().create(APP_CONFIG_NAME)
.setDescription("References the Nessie-Quarkus server dependency, only a single dependency allowed.");
Configuration runtimeConfig = target.getConfigurations().create(RUNTIME_CONFIG_NAME)
.setDescription("Optional/additional runtime dependencies.");
Configuration launchConfig = target.getConfigurations().create(LAUNCH_CONFIG_NAME)
.setDescription(String.format("Extends %s and %s - plugin internal use only.", APP_CONFIG_NAME, RUNTIME_CONFIG_NAME))
.setVisible(false)
.extendsFrom(runtimeConfig, appConfig);
// Cannot use the task name "test" here, because the "test" task might not have been registered yet.
// This `withType(Test.class...)` construct will configure any current and future task of type `Test`.
target.getTasks().withType(Test.class, new Action<Test>() {
@SuppressWarnings("UnstableApiUsage") // omit warning about `Property`+`MapProperty`
@Override
public void execute(Test test) {
test.dependsOn(START_TASK_NAME);
test.finalizedBy(STOP_TASK_NAME);
// Add the StartTask's properties as "inputs" to the Test task, so the Test task is
// executed, when those properties change.
test.getInputs().property("nessie.quarkus.props", extension.getPropsProperty());
test.getInputs().property("quarkus.native.builderImage", extension.getNativeBuilderImageProperty());
test.getInputs().files(launchConfig);
// Start the Nessie-Quarkus-App only when the Test task actually runs
test.doFirst(new Action<Task>() {
@Override
public void execute(Task ignore) {
StartTask startTask = (StartTask) target.getTasks().getByName(START_TASK_NAME);
startTask.quarkusStart();
}
});
}
});
target.getTasks().register(START_TASK_NAME, StartTask.class);
target.getTasks().register(STOP_TASK_NAME, StopTask.class);
}
}
| true
|
78ad18de948deebca87e0b49ac32dcfbdf42b3b5
|
Java
|
lanns-skynns/2Domi-Nations2
|
/Java In/Domi-Nations/src/dominations/model/CartesEnJeu.java
|
UTF-8
| 419
| 2.484375
| 2
|
[] |
no_license
|
package dominations.model;
public class CartesEnJeu {
private Carte[] carteEnJeu;
private String[] roi; // tu ne crois pas qu'on devrait prendre un tableau de roi de préférence, comme ça, on associe roi et cartes en jeu
private int nbrCartes;
public CartesEnJeu(){}
public void setRoi(String[] roi){
this.roi=roi;
}
public String[] getRoi(){
return this.roi;
}
}
| true
|
740f90bc5c2797298b9067bd275267c709afafa3
|
Java
|
RadhikaKalaiselvan/Gift-Registry---Web-Programming
|
/GiftRegistryWebServices1/src/org/BlueLeaf/Servlet/LoginServlet.java
|
UTF-8
| 3,240
| 2.203125
| 2
|
[] |
no_license
|
package org.BlueLeaf.Servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.BlueLeaf.Service.LoginService;
import blueleaf.giftregistry.model.AllUserinfo;
import blueleaf.giftregistry.model.Status;
import blueleaf.giftregistry.model.UserInfo;
import javax.ws.rs.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String password;
//long userID;
String username;
String email;
int userType;
long phoneNum;
email= request.getParameter("email");
password= request.getParameter("password");
phoneNum = 0;
userType=0;
username="";
UserInfo u=new UserInfo(username,password,email,userType,phoneNum);
HttpSession session = request.getSession();
LoginService loginService = new LoginService();
Status s= loginService.authenticate(u);
if(s.getCode()==100) {
//Admin
session.setAttribute("Semail", email);
session.setAttribute("Spassword", password);
response.sendRedirect("adminHomePage.jsp");
return;
}else
if(s.getCode()==110) {
//Customer
session.setAttribute("Semail", email);
session.setAttribute("Spassword", password);
Client client=ClientBuilder.newClient();
Response r= client.target("http://localhost:9080/GiftRegistryWebServices_AppServ2/rest/usermanagementservice/getUserInfo/"+email).request().get();
UserInfo userinfo=r.readEntity(UserInfo.class);
request.setAttribute("userinfo", userinfo);
session.setAttribute("SuserID", userinfo.getUserID());
session.setAttribute("SUname", userinfo.getUsername());
session.setAttribute("Sphonenum", userinfo.getPhoneNum());
RequestDispatcher dispacter = request.getRequestDispatcher("success.jsp");
dispacter.forward(request, response);
// RequestDispatcher dispacter1 = request.getRequestDispatcher("EditProfile.jsp");
// dispacter.forward(request, response);
//response.sendRedirect("success.jsp");
return;
}else
if(s.getCode()==103) {
//User Doesn't Exist
//response.sendRedirect("login.jsp");
request.setAttribute("message", "User Doesn't exist");
request.getRequestDispatcher("login.jsp").forward(request, response);
return;
}else
if(s.getCode()==104) {
//Invalid Password
//response.sendRedirect("login.jsp");
request.setAttribute("message", "Invalid Password");
request.getRequestDispatcher("login.jsp").forward(request, response);
return;
}
}
}
| true
|
2ba834f6556556b4188e8290d7366b3fdef6067b
|
Java
|
kskim-wisethan/MyBleTest
|
/app/src/main/java/com/example/mybletest/util/BleManager.java
|
UTF-8
| 4,241
| 1.984375
| 2
|
[] |
no_license
|
package com.example.mybletest.util;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.example.mybletest.R;
import com.example.mybletest.model.BleModel;
import com.example.mybletest.service.BluetoothLeService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static android.content.Context.BIND_AUTO_CREATE;
public class BleManager {
private static final String TAG = BleManager.class.getSimpleName();
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_FINE_LOCATION = 2;
private static final long SCAN_PERIOD = 10000;
private final String LIST_NAME = "NAME";
private final String LIST_UUID = "UUID";
private boolean mScanning = false;
private boolean mConnected = false;
private String mDeviceAddress = "";
private Handler mHandler = new Handler();
private Activity mParent;
private BluetoothAdapter mBluetoothAdapter;
private BleDeviceCallback mDeviceCallback;
private static BleManager mInstance;
public static BleManager getInstance(Activity parent) {
if (mInstance == null) {
mInstance = new BleManager(parent);
}
return mInstance;
}
public interface BleDeviceCallback {
public void onResponse(BleModel model);
}
private BleManager(Activity parent) {
mParent = parent;
checkBleEnable();
}
public void checkBleEnable() {
if (!mParent.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(mParent, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
} else {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(mParent, R.string.bluetooth_not_supported, Toast.LENGTH_SHORT).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
mParent.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
}
private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, final byte[] scanRecord) {
mParent.runOnUiThread(new Runnable() {
@Override
public void run() {
Map<String, Object> data = new HashMap<>();
data.put("uuid", device.getAddress());
data.put("rssi", String.valueOf(rssi));
data.put("name", (device.getName() == null) ? mParent.getString(R.string.unknown_device) : device.getName());
data.put("description", "");
data.put("scan_record", StringUtils.byteArrayInHexFormat(scanRecord));
BleModel ble = new BleModel(data);
mDeviceCallback.onResponse(ble);
}
});
}
};
public void scanBleDevice(final BleDeviceCallback callback) {
mDeviceCallback = callback;
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (mScanning) {
mScanning = false;
mBluetoothAdapter.stopLeScan(leScanCallback);
}
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(leScanCallback);
}
public void stopScan() {
mScanning = false;
mBluetoothAdapter.stopLeScan(leScanCallback);
}
}
| true
|
18d4baab9c7860eee913ed4e10cec834c0f1bf41
|
Java
|
sachin073/challenges
|
/src/dell/EqualArray.java
|
UTF-8
| 2,279
| 3.453125
| 3
|
[] |
no_license
|
package dell;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by sachin on 12/5/18.
*
You are given an array A of size N
Find the minimum non negative number X such that there exist an index j and when you can replace Aj by Aj+X, the sum of elements of array from index 1 to j and j+1 to N becomes equal, where 1≤j≤N−1. Assume array to be 1-indexed.
If there is no possible X print −1 in separate line.
Input Format
The first line contains T, the number of test cases.
For each Test case :
The first line contains an integer N, size of the array.
The second line contains N space-separated integers, the ith of which is Ai.
*
*
*/
public class EqualArray {
static String inp="";
static BufferedReader inpReader= new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) {
try {
int test= Integer.parseInt(inpReader.readLine());
while (test>0){
int size = Integer.parseInt(inpReader.readLine());
int[] arr = new int[size];
inp =inpReader.readLine();
int i=0;
int sum =0;
for (String str :inp.split(" ")) {
arr[i] = Integer.parseInt(str);
sum += arr[i];
i++;
}
int balancingLoad=0;
int rightLoad = sum;
int leftSum = 0;
int j = 0;
for ( j = 0; j < i ; j++) {
leftSum = leftSum +arr[j]; //1
rightLoad = rightLoad - arr[j]; // 8
if ( (rightLoad > leftSum) && (balancingLoad > rightLoad -leftSum || balancingLoad ==0) && (leftSum +(rightLoad -leftSum ) == rightLoad ) ) {
balancingLoad = rightLoad - leftSum;
}
}
if (balancingLoad !=0) {
System.out.println(balancingLoad);
} else {
System.out.println(-1);
}
test--;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
| true
|
2405c4e35cbe751cc2cb362bd282f2fe5b317c68
|
Java
|
Red1144/peatioj
|
/sample/worker-web/src/main/java/com/epitome/peatioj/app/PeatiojApplication.java
|
UTF-8
| 587
| 1.796875
| 2
|
[] |
no_license
|
package com.epitome.peatioj.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {
"com.epitome.peatioj.controller.ui",
"com.epitome.peatioj.config"
})
public class PeatiojApplication {
public static void main(String[] args) {
SpringApplication.run(PeatiojApplication.class, args);
}
}
| true
|
682031b854f364ad04770b01724db415deee6ba4
|
Java
|
BhawanaRani/TrainingMaterial
|
/com.spark.works/src/main/java/SparkSQlWork.java
|
UTF-8
| 5,095
| 2.328125
| 2
|
[] |
no_license
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.map.HashedMap;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.COL;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.RowFactory;
import org.apache.spark.sql.SparkSession;
import org.apache.spark.sql.functions.*;
import org.apache.spark.sql.types.DataType;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import com.training.commons.SparkConnections;
public class SparkSQlWork {
public static void main(String[] args) {
Logger.getLogger("org").setLevel(Level.ERROR);
//optional
Logger.getLogger("akka").setLevel(Level.ERROR);
JavaSparkContext sparkContext=SparkConnections.getContext();
SparkSession spSession=SparkConnections.getSession();
Dataset<Row> empDataFile=spSession.read().json("./data/customerData.json");
empDataFile.show();
empDataFile.printSchema();
//data queries
System.out.println("select Demo");
empDataFile.select(org.apache.spark.sql.functions.col("name"),org.apache.spark.sql.functions.col("salary")).show();
//data queries on selection (condition)
System.out.println("select Demo with condition");
//empDataFile.filter(col("gender")).equalTo("male")).show();
//System.out.println();
//group by dept id ,average salry ,max age
Dataset<Row> summaryData=empDataFile.groupBy(org.apache.spark.sql.functions.col("deptid"))
.agg(org.apache.spark.sql.functions.avg((empDataFile.col("salary"))),org.apache.spark.sql.functions.max(empDataFile.col("age")));
summaryData.show();
////try with bean classes/////
Department dept1=new Department(100,"Development");
Department dept2=new Department(200,"Testing");
List<Department> deptList=new ArrayList<Department>();
deptList.add(dept1);
deptList.add(dept2);
Dataset<Row> deptDataField=spSession.createDataFrame(deptList, Department.class);
System.out.println("Department contents are.......");
deptDataField.show();
Dataset<Row> empDeptJoin=empDataFile.join(deptDataField,org.apache.spark.sql.functions.col("deptid").equalTo(org.apache.spark.sql.functions.col("departmentId")));
empDeptJoin.show();
empDataFile.filter(org.apache.spark.sql.functions.col("age").gt(30)).join(deptDataField,org.apache.spark.sql.functions.col("deptid")
.equalTo(org.apache.spark.sql.functions.col("departmentId"))).groupBy(org.apache.spark.sql.functions.col("deptid"))
.agg(org.apache.spark.sql.functions.avg(empDataFile.col("salary")),
org.apache.spark.sql.functions.max(empDataFile.col("age"))).show();
Dataset<Row> autoData=spSession.read().option("header", "true").csv("./data/auto-dataNew");
autoData.show(5);
//creating object with row//
Row row1=RowFactory.create(1,"India","Bangaluru");
Row row2=RowFactory.create(2,"USA","Restron");
Row row3=RowFactory.create(3,"UK","SteevenScreek");
List<Row> rList=new ArrayList<Row>();
rList.add(row1);
rList.add(row2);
rList.add(row3);
JavaRDD<Row> rowRDD=sparkContext.parallelize(rList);
StructType schema=DataTypes.createStructType(new StructField[]
{DataTypes.createStructField("id",DataTypes.IntegerType,false),
DataTypes.createStructField("country",DataTypes.StringType,false),
DataTypes.createStructField("city",DataTypes.StringType,false)
});
Dataset<Row> tempDataField=spSession.createDataFrame(rowRDD, schema);
tempDataField.show();
//working with csv data,with sql statements
//provide the data is kept in table like format
//presistence will b only till end of prgrm
autoData.createOrReplaceTempView("autos");//csv file auto data ......creating temp view autos
System.out.println("Temp Table content");
System.out.println("showing all the fields with hp greater than 200");
//spSession.sql("select * from autos where HP>200").show();
//to find make ,maximum RPM from autos group by make
System.out.println("===========to find make,maximum from autos=========");
//spSession.sql("select make,max(rpm) from autos group by make order by 2").show();
//convert dataframe to JavaRDD
JavaRDD autoRdd=autoData.rdd().toJavaRDD();
//reading the data from mysql db
//db (db) table(employee
Map<String,String> jdbcConnection=new HashMap<String,String>();
jdbcConnection.put("url", "jdbc:mysql://localhost:3306/myDatabase");
jdbcConnection.put("driver", "com.mysql.jdbc.Driver");
jdbcConnection.put("dbtable", "Employee");
jdbcConnection.put("user", "root");
jdbcConnection.put("password", "Root@123");
System.out.println("create a db from db table (Employee)");
Dataset<Row> sqlDataFields=spSession.read().format("jdbc").options(jdbcConnection).load();
sqlDataFields.show();
}
}
| true
|
6329a20c5abb0efda3d65fd51c4c376c11a55535
|
Java
|
LLLHgo/Garden
|
/HomeWork4/原型代码/HRMSClient/src/businesslogicservice/sitemanagerblservice/SitemanagerBLService_Driver.java
|
UTF-8
| 4,831
| 2.140625
| 2
|
[] |
no_license
|
package businesslogicservice.sitemanagerblservice;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import Enum.ResultMessage;
import Enum.Star;
import Enum.VIPType;
import vo.clientVO.ClientVO;
import vo.hotelinfoVO.HotelinfoVO;
import vo.hotelinfoVO.RoominfoVO;
import vo.hotelstaffVO.HotelstaffVO;
import vo.marketingVO.MarketingVO;
import vo.sitemanager.SitemanagerVO;
public class SitemanagerBLService_Driver {
public void drive(SitemanagerBLService sitemanagerBLService){
ResultMessage result;
//Date date;
ClientVO clientAccountVO = null;
MarketingVO marketingAccountVO=null;
HotelinfoVO hotelInfoVO=null;
HotelstaffVO hotelstaffVO=null;
SitemanagerVO sitemanagerVO=null;
// 修改客户账户
System.out.println("修改客户账户:");
result=sitemanagerBLService.clientAccountUpdate(new ClientVO("C00000009","000","Kerry","17999982876",VIPType.ENTERPRISEVIP,2,null,"SAP",new File("C00000009")));
if(result==ResultMessage.SUCCESS){
System.out.println("修改成功");
}
else if(result==ResultMessage.FAIL){
System.out.println("修改失败");
}
//System.out.println(clientAccountVO.getClient_name()+" "+clientAccountVO.getClient_tel()+clientAccountVO.getClient_birth());
// 删除账户
System.out.println("删除客户账户:");
result=sitemanagerBLService.accountDelete("H00000090");
if(result==ResultMessage.SUCCESS){
System.out.println("删除成功");
}
else if(result==ResultMessage.FAIL){
System.out.println("删除失败");
}
// 管理界面得到客户账户信息
System.out.println("得到客户账户信息:");
clientAccountVO=sitemanagerBLService.clientAccountFind("C00000009");
System.out.print("显示客户账户信息:");
//System.out.println(clientAccountVO.getClient_name()+clientAccountVO.getVip_type());
System.out.println("这里是账户的详细信息");
// 修改网站营销人员账户
System.out.println("修改网站营销人员账户:");
result=sitemanagerBLService.MarketingAccountUpdate(new MarketingVO("Liu","liu123","M00000008","13777879889"));
if(result==ResultMessage.SUCCESS){
System.out.println("修改成功");
}
else if(result==ResultMessage.FAIL){
System.out.println("修改失败");
}
//System.out.println(marketingAccountVO.getName()+" "+marketingAccountVO.getTelephone());
// 添加网站营销人员
System.out.println("添加网站营销人员:");
result=sitemanagerBLService.MarketingAccountUpdate(new MarketingVO("Tony","tony1234","M00000009","17889987656"));
if(result==ResultMessage.SUCCESS){
System.out.println("添加成功");
}
else if(result==ResultMessage.FAIL){
System.out.println("添加失败");
}
// 管理界面得到网站营销人员账户信息
System.out.println("得到网站营销人员账户信息:");
marketingAccountVO=sitemanagerBLService.MarketingAccountFind("M00000008");
System.out.print("显示网站营销人员账户信息:");
//System.out.println(marketingAccountVO.getMarketingID()+marketingAccountVO.getName());
System.out.println("这里是账户的详细信息");
// 添加酒店
System.out.println("添加酒店:");
result=sitemanagerBLService.MarketingAccountAdd(new HotelinfoVO("caesar","Charls road No.1","LVegas","010-00233",
new ArrayList<RoominfoVO>(),Star.FIVE,new ArrayList<String>(),"Best in LV","H00000105" ));
if(result==ResultMessage.SUCCESS){
System.out.println("添加酒店成功");
}
else if(result==ResultMessage.FAIL){
System.out.println("添加酒店失败");
}
// 管理界面得到酒店工作人员账户信息
System.out.println("得到酒店工作人员账户信息:");
hotelstaffVO=sitemanagerBLService.HotelStaffAccountFind("H00000008");
System.out.print("显示酒店工作人员账户信息:");
System.out.println(hotelstaffVO.getClass()+hotelstaffVO.getTel());
System.out.println("这里是账户的详细信息");
// 修改酒店工作人员账户
System.out.println("修改酒店工作人员账户:");
result=sitemanagerBLService.HotelStaffAccountUpdate(new HotelstaffVO("H00000006","h123","17889967883"));
if(result==ResultMessage.SUCCESS){
System.out.println("修改成功");
}
else if(result==ResultMessage.FAIL){
System.out.println("修改失败");
}
System.out.println(hotelstaffVO.getHotelID()+" "+hotelstaffVO.getTel());
// 检查登录的网站管理人员账户密码是否正确
System.out.println("检查登录的网站管理人员账户密码是否正确:");
result=sitemanagerBLService.checkAccount(new SitemanagerVO("S00000001","010-08923","IAMSITEMANAGER"));
if(result==ResultMessage.SUCCESS){
System.out.println("登录帐号密码正确");
}
else if(result==ResultMessage.FAIL){
System.out.println("登录帐号密码错误");
}
}
}
| true
|
18df602701d46ec1805d13d2b6eee66acfa306cb
|
Java
|
dnd2/CQZTDMS
|
/src/com/infodms/dms/actions/report/partReport/partOderGoodsDetailReport/PartOderGoodsDetailAction.java
|
UTF-8
| 8,126
| 1.882813
| 2
|
[] |
no_license
|
package com.infodms.dms.actions.report.partReport.partOderGoodsDetailReport;
import com.infodms.dms.actions.report.partReport.partBuySaleStoreReport.PartBuySaleStoreAction;
import com.infodms.dms.actions.sales.planmanage.PlanUtil.BaseImport;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.dao.parts.salesManager.PartOderGoodsDetailDao;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.util.CheckUtil;
import com.infodms.dms.util.CommonUtils;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.mvc.context.ResponseWrapper;
import com.infoservice.po3.bean.PageResult;
import jxl.Workbook;
import jxl.write.Label;
import org.apache.log4j.Logger;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
public class PartOderGoodsDetailAction extends BaseImport {
public Logger logger = Logger.getLogger(PartBuySaleStoreAction.class);
ActionContext act = ActionContext.getContext();
AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
public static final String INIT_URL = "/jsp/parts/salesManager/carFactorySalesManager/partOderGoodsDetailQuery.jsp";
private PartOderGoodsDetailDao dao = PartOderGoodsDetailDao.getInstance();
public void init() {
ActionContext act = ActionContext.getContext();
AclUserBean loginUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
try {
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 1);//把日期设置为当月第一天
c.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
act.setOutData("start", c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + "1");
act.setOutData("end", c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DATE));
act.setForword(INIT_URL);
} catch (Exception e) {//异常方法
BizException e1 = new BizException(act, e, ErrorCodeConstant.SPECIAL_MEG, "服务站订货明细页面初始化失败!");
logger.error(loginUser, e1);
act.setException(e1);
}
}
/**
* 销售明细报表
*/
public void query() {
ActionContext act = ActionContext.getContext();
AclUserBean loginUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
RequestWrapper request = act.getRequest();
try {
Integer curPage = request.getParamValue("curPage") != null ? Integer
.parseInt(request.getParamValue("curPage"))
: 1; // 处理当前页
PageResult<Map<String, Object>> sumps = dao.query(request, curPage, Constant.PAGE_SIZE, "2");
PageResult<Map<String, Object>> ps = dao.query(request, curPage, Constant.PAGE_SIZE, "1");
act.setOutData("outQty", sumps.getRecords().get(0).get("OUTQTY") == null ? 0 : sumps.getRecords().get(0).get("OUTQTY"));
act.setOutData("outAmount", sumps.getRecords().get(0).get("OUTAMOUNT") == null ? 0 : sumps.getRecords().get(0).get("OUTAMOUNT"));
act.setOutData("ps", ps);
} catch (Exception e) {//异常方法
BizException e1 = new BizException(act, e, ErrorCodeConstant.SPECIAL_MEG, "销售明细页面查询失败!");
logger.error(loginUser, e1);
act.setException(e1);
}
}
/**
* 销售明细报表导出
*/
public void exportExcel() {
ActionContext act = ActionContext.getContext();
AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
try {
RequestWrapper request = act.getRequest();
String[] head = new String[11];
head[0] = "序号";
head[1] = "出库日期";
head[2] = "服务站号";
head[3] = "服务站名称";
head[4] = "订单号";
head[5] = "流水号";
head[6] = "配件编码";
head[7] = "配件名称";
head[8] = "出库数量";
head[9] = "销售单价";
head[10] = "销售金额";
PageResult<Map<String, Object>> ps = dao.query(request, 1, Constant.PAGE_SIZE_MAX, "1");
List list1 = new ArrayList();
for (int i = 0; i < ps.getRecords().size(); i++) {
Map map = (Map) ps.getRecords().get(i);
if (map != null && map.size() != 0) {
String[] detail = new String[11];
detail[0] = CommonUtils.checkNull((i + 1));
detail[1] = CommonUtils.checkNull(map.get("SUBMIT_DATE"));
detail[2] = CommonUtils.checkNull(map.get("DEALER_CODE"));
detail[3] = CommonUtils.checkNull(map.get("DEALER_NAME"));
detail[4] = CommonUtils.checkNull(map.get("ORDER_CODE"));
detail[5] = CommonUtils.checkNull(map.get("SO_CODE"));
detail[6] = CommonUtils.checkNull(map.get("PART_OLDCODE"));
detail[7] = CommonUtils.checkNull(map.get("PART_CNAME"));
detail[8] = CommonUtils.checkNull(map.get("OUTSTOCK_QTY"));
detail[9] = CommonUtils.checkNull(map.get("SALE_PRICE"));
detail[10] = CommonUtils.checkNull(map.get("SALE_AMOUNT"));
list1.add(detail);
}
}
this.exportEx(ActionContext.getContext().getResponse(), request, head, list1);
} catch (Exception e) {
BizException e1 = new BizException(act, e, ErrorCodeConstant.SPECIAL_MEG, "");
logger.error(logonUser, e1);
act.setException(e1);
}
}
/**
* @param : @param orgAmt
* @param : @return
* @return :
* @throws : LastDate : 2013-4-3
* @Title :
* @Description:导出
*/
public static Object exportEx(ResponseWrapper response,
RequestWrapper request, String[] head, List<String[]> list)
throws Exception {
String name = "销售明细.xls";
jxl.write.WritableWorkbook wwb = null;
OutputStream out = null;
try {
response.setContentType("application/octet-stream");
response.addHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
out = response.getOutputStream();
wwb = Workbook.createWorkbook(out);
jxl.write.WritableSheet ws = wwb.createSheet("sheettest", 0);
if (head != null && head.length > 0) {
for (int i = 0; i < head.length; i++) {
ws.addCell(new Label(i, 0, head[i]));
}
}
for (int z = 1; z < list.size() + 1; z++) {
String[] str = list.get(z - 1);
for (int i = 0; i < str.length; i++) {
/*ws.addCell(new Label(i, z, str[i]));*/ //modify by yuan
if (CheckUtil.checkFormatNumber1(str[i] == null ? "" : str[i])) {
ws.addCell(new jxl.write.Number(i, z, Double.parseDouble(str[i])));
} else {
ws.addCell(new Label(i, z, str[i]));
}
}
}
wwb.write();
out.flush();
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (null != wwb) {
wwb.close();
}
if (null != out) {
out.close();
}
}
return null;
}
}
| true
|
34ac6818fb404a7c0cc6fb9fdd266d7e286e6c1a
|
Java
|
xiaohangqiao/DesignPattern
|
/src/main/java/com/TestBase/TestOverload.java
|
UTF-8
| 643
| 3.109375
| 3
|
[] |
no_license
|
package TestBase;
/**
* 测试方法重载
* 1)方法相同,但是参数不同也可以是重载
* 2)方法相同,参数也个数以及参数的类型也相同,但是参数的顺序不同,也构成重载
*/
public class TestOverload {
public static void main(String[] args) {
System.out.println("测试重载");
TestOverload.Test(10, "aaaaaaaaa");
TestOverload.Test("bbbbbbbbbbb", 10);
}
public static void Test(int a, String b) {
System.out.println("aaa");
}
public static void Test(String b, int a) {
System.out.println(a);
System.out.println(b);
}
}
| true
|
f82d5fdf95c6b5577434011e588ced6200fce29d
|
Java
|
getgauge/gauge-java
|
/src/main/java/com/thoughtworks/gauge/processor/StepNamesRequestProcessor.java
|
UTF-8
| 1,133
| 1.828125
| 2
|
[
"WTFPL",
"BSD-3-Clause",
"MPL-1.1",
"GPL-3.0-only",
"LGPL-2.1-only",
"Apache-2.0",
"BSD-2-Clause",
"EPL-1.0"
] |
permissive
|
/*----------------------------------------------------------------
* Copyright (c) ThoughtWorks, Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE.txt in the project root for license information.
*----------------------------------------------------------------*/
package com.thoughtworks.gauge.processor;
import com.thoughtworks.gauge.registry.StepRegistry;
import gauge.messages.Messages;
import java.util.List;
public class StepNamesRequestProcessor implements IMessageProcessor {
private final StepRegistry registry;
public StepNamesRequestProcessor(StepRegistry registry) {
this.registry = registry;
}
public Messages.Message process(Messages.Message receivedMessage) {
List<String> stepTexts = registry.getAllStepAnnotationTexts();
return Messages.Message.newBuilder()
.setMessageId(receivedMessage.getMessageId())
.setMessageType(Messages.Message.MessageType.StepNamesResponse)
.setStepNamesResponse(Messages.StepNamesResponse.newBuilder().addAllSteps(stepTexts).build())
.build();
}
}
| true
|
454fc3b020841f130bb9f8d13a24cae771ab1f47
|
Java
|
gpalabral/ErpContabilidad
|
/ERP_APP/src/main/java/com/bap/erp/vista/cnt/backing/CntParametrosServidorBacking.java
|
UTF-8
| 2,233
| 1.960938
| 2
|
[] |
no_license
|
package com.bap.erp.vista.cnt.backing;
import com.bap.erp.modelo.entidades.cnf.ParParametrosGestion;
import com.bap.erp.modelo.entidades.cnf.ParParametrosServidor;
import com.bap.erp.modelo.servicios.cnf.ParParametricasService;
import com.bap.erp.vista.common.AbstractManagedBean;
import com.bap.erp.vista.utils.MessageUtils;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
@ManagedBean(name = "cntParametrosServidorBacking")
@ViewScoped
public class CntParametrosServidorBacking extends AbstractManagedBean implements Serializable {
@ManagedProperty(value = "#{parParametricasService}")
private ParParametricasService parParametricasService;
private String urlAutenticacion = "" ;
public CntParametrosServidorBacking() {
}
@PostConstruct
public void initCntParametrosServidorBacking() {
try {
urlAutenticacion = parParametricasService.findParametrosServidor("HOST").getValor();
} catch (Exception e) {
e.printStackTrace();
}
}
public String modificaParametrosServidor(){
try {
if (urlAutenticacion.equals("")) {
MessageUtils.addErrorMessage("La Url de Autentificacion es obligatoria");
} else{
parParametricasService.modificaParametrosServidor(urlAutenticacion);
return "paginaEnBlanco";
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String cancelar() {
return "paginaEnBlanco";
}
public ParParametricasService getParParametricasService() {
return parParametricasService;
}
public void setParParametricasService(ParParametricasService parParametricasService) {
this.parParametricasService = parParametricasService;
}
public String getUrlAutenticacion() {
return urlAutenticacion;
}
public void setUrlAutenticacion(String urlAutenticacion) {
this.urlAutenticacion = urlAutenticacion;
}
}
| true
|
58eb90765ab931b74e6cc5e76a504a40b90f3e59
|
Java
|
andersonjope/psicologia
|
/psicologia-web/src/main/java/br/com/jope/psicologia/view/message/MessageDecoder.java
|
UTF-8
| 644
| 2.21875
| 2
|
[] |
no_license
|
package br.com.jope.psicologia.view.message;
import javax.websocket.DecodeException;
import javax.websocket.Decoder.Text;
import javax.websocket.EndpointConfig;
import com.google.gson.Gson;
public class MessageDecoder implements Text<MessageWebSocket> {
private static Gson gson = new Gson();
@Override
public void init(EndpointConfig config) {
}
@Override
public void destroy() {
}
@Override
public MessageWebSocket decode(String s) throws DecodeException {
return gson.fromJson(s, MessageWebSocket.class);
}
@Override
public boolean willDecode(String s) {
return (s != null);
}
}
| true
|
bc95b5fab5de2ba42e5f5219c6898cc9ff311b22
|
Java
|
ZhangShufan15/attribute-explain
|
/ae-core/src/main/java/com/dangdang/ae/base/AttributeExplainPrinter.java
|
UTF-8
| 13,443
| 2.671875
| 3
|
[] |
no_license
|
package com.dangdang.ae.base;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* 对象信息解析器。
* 解析采用递归方式,直到对象中属性值得数据类型为:原始类型、原始类型封装类型、Enum、String、Date、Object时停止迭代。
*
* @author zhangxiansheng
*
*/
public class AttributeExplainPrinter {
public static final String QUADRI_SPACE = "_Q_0_S_";
public static final String NEW_LINE = "_N_0_L_";
public static final String KEY_START_KEY = "_K_S_K_";
public static final String KEY_END_KEY = "_K_E_K_";
public static final String VALUE_START_KEY = "_V_S_K_";
public static final String VALUE_END_KEY = "_V_E_K_";
public static final String COMMENT_START_KEY = "_C_S_K_";
public static final String COMMENT_END_KEY = "_C_E_K_";
public static final String EMBRACE_START_KEY = "_E_S_K_";
public static final String EMBRACE_END_KEY = "_E_E_K_";
/**
* 最终展现形式的转换器,默认提供了html的转换器,其他形式的转换器可能还可以是markdown?
*/
private IMarkConvertor markConvertor;
public AttributeExplainPrinter(IMarkConvertor convertor){
this.markConvertor = convertor;
}
public AttributeExplainPrinter setConvertor(IMarkConvertor convertor){
markConvertor = convertor;
return this;
}
public String getExplainInfo(Object target){
List<StringBuilder> infoArray = explain(target);
return markConvertor.convert(infoArray);
}
public static List<StringBuilder> explain(Object target){
List<StringBuilder> infoList = new ArrayList<>();
List<Field> fieldArray = getAllFields(target.getClass());
for(Field field : fieldArray){
if(field.getName().equals("serialVersionUID")){
continue;
}
if(isSubclassOf(field.getType(), Collection.class) || field.getType().isArray()){
processArray(field, target, infoList);
}else if(isSubclassOf(field.getType(), Map.class)){
processMap(field, target, infoList);
}else if(!isPrimitiveType(field.getType())){
processSelfDefinedClass(field, target, infoList);
}else{
processBasics(field, target, infoList);
}
}
return infoList;
}
private static void processArray(Field field, Object target, List<StringBuilder> infoList){
Object o = getValueByField(field, target);
if(field.getAnnotation(AttributeExplain.class) != null){
infoList.add(createAnnotationInfo(field));
}
StringBuilder aInfo = new StringBuilder();
aInfo.append(QUADRI_SPACE);
aInfo.append(createKeyInfo(field));
aInfo.append(" => ");
aInfo.append(EMBRACE_START_KEY);
aInfo.append("array (");
aInfo.append(EMBRACE_END_KEY);
infoList.add(aInfo);
if(o != null){
Object[] array = null;
if(isSubclassOf(field.getType(), Collection.class)){
array = ((Collection<?>)o).toArray();
}else{
array = (Object[]) o;
}
for(Object obj : array){
List<StringBuilder> childInfoList = explain(obj);
StringBuilder aInfo1 = new StringBuilder();
//集合内为普通数据类型时,直接按照数组样式输出
if(isPrimitiveType(obj.getClass()) || obj.getClass().equals(Object.class)){
aInfo1.append(QUADRI_SPACE).append(QUADRI_SPACE);
aInfo1.append(VALUE_START_KEY);
aInfo1.append(array2String(array));
aInfo1.append(VALUE_END_KEY);
infoList.add(aInfo1);
break;
}
aInfo1.append(QUADRI_SPACE).append(QUADRI_SPACE);
aInfo1.append("child => ");
aInfo1.append(createStartBraceInfo());
infoList.add(aInfo1);
for(StringBuilder childInfo : childInfoList){
childInfo.insert(0, QUADRI_SPACE).insert(0, QUADRI_SPACE);
}
infoList.addAll(childInfoList);
infoList.add(createEndBraceDoubleSpaceInfo());
}
}
infoList.add(createEndBraceInfo());
}
@SuppressWarnings("rawtypes")
private static void processMap(Field field, Object target, List<StringBuilder> infoList){
Object o = getValueByField(field, target);
if(field.getAnnotation(AttributeExplain.class) != null){
infoList.add(createAnnotationInfo(field));
}
StringBuilder aInfo = new StringBuilder();
aInfo.append(QUADRI_SPACE);
aInfo.append(createKeyInfo(field));
aInfo.append(" => ");
aInfo.append(EMBRACE_START_KEY);
aInfo.append("map (");
aInfo.append(EMBRACE_END_KEY);
infoList.add(aInfo);
if(o != null){
Map array = (Map)o;
@SuppressWarnings("unchecked")
Iterator<Entry> it = array.entrySet().iterator();
while(it.hasNext()){
Entry obj = it.next();
StringBuilder aInfo1 = new StringBuilder();
//集合内为普通数据类型时,直接按照数组样式输出
if(isPrimitiveType(obj.getValue().getClass()) || obj.getValue().getClass().equals(Object.class)){
aInfo1.append(QUADRI_SPACE).append(QUADRI_SPACE);
aInfo1.append(VALUE_START_KEY);
aInfo1.append(array.toString());
aInfo1.append(VALUE_END_KEY);
infoList.add(aInfo1);
break;
}
List<StringBuilder> childInfoList = explain(obj.getValue());
aInfo1.append(QUADRI_SPACE).append(QUADRI_SPACE);
aInfo1.append(KEY_START_KEY);
aInfo1.append(obj.getKey());
aInfo1.append(KEY_END_KEY);
aInfo1.append(" => ");
aInfo1.append(createStartBraceInfo());
infoList.add(aInfo1);
for(StringBuilder childInfo : childInfoList){
childInfo.insert(0, QUADRI_SPACE).insert(0, QUADRI_SPACE);
}
infoList.addAll(childInfoList);
infoList.add(createEndBraceDoubleSpaceInfo());
}
}
infoList.add(createEndBraceInfo());
}
private static void processSelfDefinedClass(Field field, Object target, List<StringBuilder> infoList){
if(field.getAnnotation(AttributeExplain.class) != null){
infoList.add(createAnnotationInfo(field));
}
Object o = getValueByField(field, target);
StringBuilder aInfo = new StringBuilder();
aInfo.append(QUADRI_SPACE);
aInfo.append(createKeyInfo(field));
aInfo.append(" => ");
aInfo.append(createStartBraceInfo());
infoList.add(aInfo);
if(o != null){
List<StringBuilder> childInfoList = explain(o);
for(StringBuilder childInfo : childInfoList){
childInfo.insert(0, QUADRI_SPACE);
}
infoList.addAll(childInfoList);
}
infoList.add(createEndBraceInfo());
}
private static void processBasics(Field field, Object target, List<StringBuilder> infoList){
if(field.getAnnotation(AttributeExplain.class) != null){
infoList.add(createAnnotationInfo(field));
}
StringBuilder aInfo = new StringBuilder();
aInfo.append(QUADRI_SPACE);
aInfo.append(createKeyInfo(field));
aInfo.append(" => ");
Object o = getValueByField(field, target);
aInfo.append(createValueInfo(o));
infoList.add(aInfo);
}
private static Object getValueByField(Field field, Object target){
Object o = null;
try{
if(field.getName().startsWith("is")){
Method getMethod = target.getClass().getMethod(field.getName());
if(getMethod != null){
o = getMethod.invoke(target);
}
}else{
PropertyDescriptor pd = new PropertyDescriptor(field.getName(), target.getClass());
Method getMethod = pd.getReadMethod();
if(getMethod != null){
o = getMethod.invoke(target);
}
}
}catch(IntrospectionException e){
//
}catch(IllegalAccessException e){
//
}catch(IllegalArgumentException e){
//
}catch(InvocationTargetException e){
//
}catch(NoSuchMethodException e){
//
}catch(SecurityException e){
//
}
return o;
}
private static StringBuilder createAnnotationInfo(Field field){
StringBuilder sbuffer = new StringBuilder();
sbuffer.append(QUADRI_SPACE);
sbuffer.append(COMMENT_START_KEY);
sbuffer.append("//");
sbuffer.append(field.getAnnotation(AttributeExplain.class).explaintInfo());
sbuffer.append(COMMENT_END_KEY);
return sbuffer;
}
private static StringBuilder createStartBraceInfo(){
StringBuilder sbuffer = new StringBuilder();
sbuffer.append(EMBRACE_START_KEY);
sbuffer.append("(");
sbuffer.append(EMBRACE_END_KEY);
return sbuffer;
}
private static StringBuilder createEndBraceInfo(){
StringBuilder sbuffer = new StringBuilder();
sbuffer.append(QUADRI_SPACE);
sbuffer.append(EMBRACE_START_KEY);
sbuffer.append(")");
sbuffer.append(EMBRACE_END_KEY);
return sbuffer;
}
private static StringBuilder createEndBraceDoubleSpaceInfo(){
StringBuilder sbuffer = new StringBuilder();
sbuffer.append(QUADRI_SPACE).append(QUADRI_SPACE);
sbuffer.append(EMBRACE_START_KEY);
sbuffer.append(")");
sbuffer.append(EMBRACE_END_KEY);
return sbuffer;
}
private static StringBuilder createKeyInfo(Field field){
StringBuilder sbuffer = new StringBuilder();
sbuffer.append(KEY_START_KEY);
sbuffer.append(field.getName());
sbuffer.append(KEY_END_KEY);
return sbuffer;
}
private static StringBuilder createValueInfo(Object o){
StringBuilder sbuffer = new StringBuilder();
sbuffer.append(VALUE_START_KEY);
if(o != null){
sbuffer.append(o);
}else{
sbuffer.append("NULL");
}
sbuffer.append(VALUE_END_KEY);
return sbuffer;
}
private static StringBuilder array2String(Object[] array){
StringBuilder sbuffer = new StringBuilder();
sbuffer.append("[");
if(array != null){
for(Object obj : array){
if(obj != null){
sbuffer.append(obj.toString());
sbuffer.append(",");
}
}
}
sbuffer.append("]");
return sbuffer;
}
/**
* 指定类型是否为基本类型:Number、Boolean、Character、Enum、String
* boolean、char、byte、short、int、long、float、double
* @param clazz
* @return
*/
private static boolean isPrimitiveType(Class<?> clazz){
if(clazz == null){
return false;
}
List<Class<?>> interfaces = getAllSuperclass(clazz);
interfaces.add(clazz);//添加当前类型
for(Class<?> interClass : interfaces){
if(interClass.equals(Number.class) || interClass.equals(Boolean.class) || interClass.equals(Character.class)
||interClass.isPrimitive() || interClass.isEnum() || interClass.equals(String.class) || interClass.equals(Date.class)){
return true;
}
}
return false;
}
/**
* 判断是不是继承了某一个指定的接口或者类
* @param clazz1 当前类型
* @param clazz2 父类或者接口类型
* @return
*/
private static boolean isSubclassOf(Class<?> clazz1, Class<?> clazz2){
if(clazz1 == null || clazz2 == null){
return false;
}
List<Class<?>> allClazzArray = null;
//获取父类型
if(clazz2.isInterface()){
allClazzArray = getAllInterfaces(clazz1);
}else{
allClazzArray = getAllSuperclass(clazz1);
}
//添加当前类型
allClazzArray.add(clazz1);
for(Class<?> interClass : allClazzArray){
if(interClass.equals(clazz2)){
return true;
}
}
return false;
}
/**
* 获取一个类继承链上所有的接口
* @param clazz
* @return
*/
private static List<Class<?>> getAllInterfaces(Class<?> clazz){
List<Class<?>> interfaceArray = new ArrayList<>();
if(clazz == null){
return interfaceArray;
}
interfaceArray.addAll(Arrays.asList(clazz.getInterfaces()));
//获取父类实现的接口
if(clazz.getSuperclass() != null){
interfaceArray.addAll(getAllInterfaces(clazz.getSuperclass()));
}
//获取父接口实现的接口
if(clazz.getInterfaces() != null){
for(Class<?> c : clazz.getInterfaces()){
interfaceArray.addAll(getAllInterfaces(c));
}
}
return interfaceArray;
}
/**
* 获取一个类型继承链上所有的父类,不包含自身。
* @param clazz
* @return
*/
private static List<Class<?>> getAllSuperclass(Class<?> clazz){
List<Class<?>> superClassArray = new ArrayList<>();
if(clazz == null){
return superClassArray;
}
Class<?> superClass = clazz.getSuperclass();
while(superClass != null){
superClassArray.add(superClass);
superClass = superClass.getSuperclass();
}
return superClassArray;
}
/**
* 获取某一个类所有的域,包含父类的域。
* 采用递归方式获取,先输出的是自Object以下的顶级父类的域,即自顶向下输出。
* @param clazz
* @return
*/
private static List<Field> getAllFields(Class<?> clazz){
List<Field> fieldArray = new ArrayList<>();
if(clazz == null || clazz == Object.class){
return fieldArray;
}
if(clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Object.class)){
fieldArray.addAll(getAllFields(clazz.getSuperclass()));
}
fieldArray.addAll(Arrays.asList(clazz.getDeclaredFields()));
return fieldArray;
}
}
| true
|
65dc91bcde20a4b537f40d6e739cccccc3c6e8cd
|
Java
|
Anzhelika-Trockaya/epam-introduction-to-java-module05-task5004
|
/task5004/src/by/epam/task5004/bean/Gem.java
|
UTF-8
| 1,641
| 3.09375
| 3
|
[] |
no_license
|
package by.epam.task5004.bean;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Objects;
public class Gem extends Treasure implements Serializable {
private GemType type;
private double carat;
public Gem() {
super();
this.type = GemType.OTHER;
this.carat = 0.0;
}
public Gem(GemType type, double carat, BigDecimal cost) {
super(cost);
this.type = type;
this.carat = carat;
}
public Gem(int id, GemType type, double carat, BigDecimal cost) {
super(id, cost);
this.type = type;
this.carat = carat;
}
public GemType getType() {
return type;
}
public void setType(GemType type) {
this.type = type;
}
public double getCarat() {
return carat;
}
public void setCarat(double carat) {
this.carat = carat;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Gem)) return false;
Gem gem = (Gem) o;
return getId() == gem.getId() &&
Double.compare(gem.carat, carat) == 0 &&
type == gem.type &&
getCost().equals(gem.getCost());
}
@Override
public int hashCode() {
return Objects.hash(getId(), type, carat, getCost());
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"id=" + getId() +
", type=" + type +
", carat=" + carat +
", cost=" + this.getCost() +
'}';
}
}
| true
|
4601c38036e5ff812dfb9466f994086df21f82f4
|
Java
|
jelena-stojanovic/jelenadjole
|
/PS_MSSP_Server/src/view/panels/importDSpanel/PanelAllAdmins.java
|
UTF-8
| 7,442
| 2.09375
| 2
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package view.panels.importDSpanel;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import model.Administrator;
import model.OpstiDomenskiObjekat;
import view.controllers.ControllerUI_Administrator;
import view.forms.FrmAdministrator;
import view.forms.OpstaEkranskaForma;
import view.panels.importDSpanel.model.TableModelAdministrator;
/**
*
* @author Jelena
*/
public class PanelAllAdmins extends javax.swing.JPanel implements OpstaEkranskaForma{
/**
* Creates new form PanelAllAdmins
*/
public PanelAllAdmins() {
initComponents();
tblAllAdmins.setComponentPopupMenu(postaviPopupmenu());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
tblAllAdmins = new javax.swing.JTable();
btnAddNewAdmin = new javax.swing.JButton();
tblAllAdmins.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
}
));
jScrollPane1.setViewportView(tblAllAdmins);
btnAddNewAdmin.setText("Add new administrator");
btnAddNewAdmin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddNewAdminActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(layout.createSequentialGroup()
.addGap(0, 342, Short.MAX_VALUE)
.addComponent(btnAddNewAdmin))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnAddNewAdmin)
.addGap(0, 11, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnAddNewAdminActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddNewAdminActionPerformed
FrmAdministrator frmAdministrator= new FrmAdministrator();
frmAdministrator.setCtrlAdmin(controllerUI_Administrator);
controllerUI_Administrator.setOdo(new Administrator());
controllerUI_Administrator.setOef(frmAdministrator);
frmAdministrator.getBtnRegisterAdmin().setVisible(true);
frmAdministrator.getBtnUpdateAdmin().setVisible(false);
frmAdministrator.setVisible(true);
}//GEN-LAST:event_btnAddNewAdminActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnAddNewAdmin;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tblAllAdmins;
// End of variables declaration//GEN-END:variables
@Override
public TableModel vratiModel() {
return tblAllAdmins.getModel();
}
@Override
public Object[] vratiPocetneVrednosti() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int vratiSelektovaniRed() {
return tblAllAdmins.getSelectedRow();
}
@Override
public OpstiDomenskiObjekat kreirajObjekat() {
throw new UnsupportedOperationException("Not supported yet.");
}
public JTable getTblAllAdmins() {
return tblAllAdmins;
}
private JPopupMenu postaviPopupmenu() {
JPopupMenu jpm = new JPopupMenu("Administrator");
JMenuItem jmiDetalji = new JMenuItem();
jmiDetalji.setText("View details about administrator");
jmiDetalji.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
jmiDetaljiActionPerformed(evt);
}
private void jmiDetaljiActionPerformed(ActionEvent evt) {
int red = tblAllAdmins.getSelectedRow();
Administrator administrator=((TableModelAdministrator)vratiModel()).getAdmin(red);
FrmAdministrator frmAdministrator= new FrmAdministrator();
frmAdministrator.setCtrlAdmin(controllerUI_Administrator);
controllerUI_Administrator.setOdo(administrator);
controllerUI_Administrator.setOef(frmAdministrator);
frmAdministrator.getBtnRegisterAdmin().setVisible(false);
frmAdministrator.getBtnUpdateAdmin().setVisible(false);
frmAdministrator.setVisible(true);
}
});
jpm.add(jmiDetalji);
JMenuItem jmiIzmeni = new JMenuItem();
jmiIzmeni.setText("Edit administrator");
jmiIzmeni.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jmiIzmeniActionPerformed(evt);
}
private void jmiIzmeniActionPerformed(ActionEvent evt) {
int red = tblAllAdmins.getSelectedRow();
Administrator administrator=((TableModelAdministrator)vratiModel()).getAdmin(red);
FrmAdministrator frmAdministrator= new FrmAdministrator();
frmAdministrator.setCtrlAdmin(controllerUI_Administrator);
controllerUI_Administrator.setOdo(administrator);
controllerUI_Administrator.setOef(frmAdministrator);
frmAdministrator.getBtnRegisterAdmin().setVisible(false);
frmAdministrator.getBtnUpdateAdmin().setVisible(true);
frmAdministrator.setVisible(true);
}
});
jpm.add(jmiIzmeni);
// JMenuItem jmiSacuvaj = new JMenuItem();
// jmiSacuvaj.setText("Save administratora");
// jmiSacuvaj.addActionListener(new java.awt.event.ActionListener() {
//
// public void actionPerformed(java.awt.event.ActionEvent evt) {
// jmiSacuvajActionPerformed(evt);
// }
//
// private void jmiSacuvajActionPerformed(ActionEvent evt) {
// throw new UnsupportedOperationException("Not yet implemented");
// }
// });
// jpm.add(jmiSacuvaj);
//
return jpm;
}
ControllerUI_Administrator controllerUI_Administrator;
public void setControllerUI_Administrator(ControllerUI_Administrator controllerUI_Administrator) {
this.controllerUI_Administrator = controllerUI_Administrator;
}
}
| true
|
45b1a60944a8d433067a53a44d9875e24003157f
|
Java
|
minikuma/search-server
|
/src/main/java/com/search/server/dto/search/SearchRequestDto.java
|
UTF-8
| 488
| 1.90625
| 2
|
[] |
no_license
|
package com.search.server.dto.search;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotBlank;
/**
* 검색 요청
* @version 1.0
* @author jeonjihoon
*/
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
public class SearchRequestDto {
@NotBlank(message = "검색 키워드는 필수값입니다.")
private String keyWord;
private int page;
private int size;
}
| true
|
033a8cf8615e7550326235e08eae60ed7d193706
|
Java
|
datcoind/VideoMaker-1
|
/app/src/main/java/com/cliffex/videomaker/videoeditor/introvd/template/app/homepage/pop/C3989d.java
|
UTF-8
| 1,086
| 1.703125
| 2
|
[] |
no_license
|
package com.introvd.template.app.homepage.pop;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import com.introvd.template.app.p177b.C3742b;
import com.introvd.template.app.setting.C4317a;
import com.introvd.template.app.youngermode.C4560d;
import com.introvd.template.common.AppPreferencesSetting;
import com.quvideo.priority.p217a.C4892c;
/* renamed from: com.introvd.template.app.homepage.pop.d */
public class C3989d extends C4892c {
/* access modifiers changed from: protected */
/* renamed from: p */
public boolean mo23396p(Activity activity) {
if (!C4560d.m11516RN().isYoungerMode() && AppPreferencesSetting.getInstance().getAppSettingInt("key_show_rate_dialog_flag", 101) == 102 && C3742b.m9111II().mo23116IJ()) {
return C4317a.m10838a(activity, new OnDismissListener() {
public void onDismiss(DialogInterface dialogInterface) {
C3989d.this.mo25344EW();
}
});
}
return false;
}
}
| true
|
8db548684d7ccc70a8bde6545914891a1d8c8cef
|
Java
|
ffresco/designpatterns
|
/src/interpreter/interpreter2/Interpretador.java
|
UTF-8
| 3,087
| 3.21875
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package interpreter.interpreter2;
import java.util.Deque;
import java.util.Stack;
/**
*
* @author fafre
*/
public class Interpretador {
private String ecuacion;
public Interpretador(String ecuacion) {
this.ecuacion = ecuacion;
}
public String infixToPostFix(){
Stack<String> pilaOp = new Stack<>();
String strPost = "";
String entrada = ecuacion.trim();
for (int i = 0; i < entrada.length(); i++) {
String currChar = entrada.substring(i, i + 1);
if (!isOperador(currChar)) {
strPost+= currChar;
} else {
while ((!pilaOp.empty()) && (precede(pilaOp.lastElement(),currChar))) {
String topSym = pilaOp.pop();
strPost+=topSym;
}
pilaOp.push(currChar);
}
}
while (!pilaOp.empty()) {
String topSym = pilaOp.pop();
strPost+=topSym;
}
return strPost;
}
public int getTotal(){
IExpresion nodoRaiz;
nodoRaiz = buildTree(infixToPostFix());
return nodoRaiz.evaluate();
}
private boolean isOperador(String currChar) {
String[] matches = new String[]{"+","*"};
for (int i = 0; i < matches.length; i++) {
String matche = matches[i];
if(currChar.contains(matche)) return true;
}
return false;
}
private boolean precede(String lastElement, String currChar) {
//aca digo algo tiene mas precedencia si se ejecuta antes que otro operador,
//* precede a +
//+ precede a ()
if ("*".equals(lastElement)) {
return true;
}
return false;
}
private IExpresion buildTree(String infixToPostFix) {
Stack<IExpresion> pila = new Stack<IExpresion>();
for (int i = 0; i < infixToPostFix.length(); i++) {
String currChar = infixToPostFix.substring(i, i + 1);
if (!isOperador(currChar)) {
IExpresion terminal = new TerminalExp(Integer.valueOf(currChar).intValue());
pila.push(terminal);
} else {
IExpresion der = (IExpresion) pila.pop();
IExpresion izq = (IExpresion) pila.pop();
IExpresion nonTerminal = getNonTerminalNoto(currChar,izq,der);
pila.push(nonTerminal);
}
}
return (IExpresion) pila.pop();
}
private IExpresion getNonTerminalNoto(String currChar, IExpresion izq, IExpresion der) {
if ("*".equals(currChar)) {
return new ProdExp(der, izq);
}
return new AddExp(der, izq);
}
}
| true
|
e606229c974027532050748d6862c3223bf5529b
|
Java
|
xiebz/groupon
|
/groupon-services/src/main/java/com/cmazxiaoma/framework/web/controller/BaseController.java
|
UTF-8
| 1,330
| 2.015625
| 2
|
[] |
no_license
|
package com.cmazxiaoma.framework.web.controller;
import com.cmazxiaoma.framework.spring.web.bind.support.DateConvertEditor;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
/**
* Controller基类
*/
public abstract class BaseController {
protected HttpServletRequest httpRequest;
protected HttpServletResponse httpResponse;
protected HttpSession httpSession;
protected ModelMap modelMap;
@ModelAttribute
protected void initSpringMvcApiModel(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
HttpSession httpSession, ModelMap modelMap) {
this.httpRequest = httpRequest;
this.httpResponse = httpResponse;
this.httpSession = httpSession;
this.modelMap = modelMap;
}
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
binder.registerCustomEditor(Date.class, new DateConvertEditor());
}
}
| true
|
6b2165642717e30fce5bc4d0be99057aea6b4617
|
Java
|
RMS92/MonEmploieDuTemps
|
/src/mon/edt/connection/Login.java
|
UTF-8
| 730
| 2.625
| 3
|
[] |
no_license
|
package mon.edt.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Login {
private volatile static Connection connect;
private static String url = "jdbc:mysql://localhost:3306/projetJava?zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=UTC";
private static String user = "root";
private static String passwd = "";
// Optimisation de la connection
public static Connection getInstance() {
if (connect == null) {
synchronized (Login.class) {
if (connect == null) {
try {
connect = DriverManager.getConnection(url, user, passwd);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
return connect;
}
}
| true
|
ea7146745fc7c8a47e4a727ff3ad2eda7b2cbaf4
|
Java
|
imenk1986/scholar-mw
|
/hadrumaths/hadrumaths-java/src/main/java/net/vpc/scholar/hadrumaths/MatrixFromTMatrix.java
|
UTF-8
| 778
| 2.765625
| 3
|
[] |
no_license
|
package net.vpc.scholar.hadrumaths;
/**
* Created by vpc on 3/23/17.
*/
public class MatrixFromTMatrix<T extends Expr> extends AbstractMatrix {
private TMatrix<T> matrix;
public MatrixFromTMatrix(TMatrix<T> matrix) {
this.matrix= matrix;
}
@Override
public Complex get(int row, int col) {
return matrix.get(row,col).toComplex();
}
@Override
public void set(int row, int col, Complex val) {
matrix.set(row,col,(T)val);
}
@Override
public int getColumnCount() {
return matrix.getColumnCount();
}
@Override
public int getRowCount() {
return matrix.getRowCount();
}
@Override
public void resize(int rows, int columns) {
matrix.resize(rows,columns);
}
}
| true
|
2c571314ac64c489ebb7db29881ce365520a3e75
|
Java
|
Ashutosh2u2u/JavaLearning
|
/UdemyPractice/src/test/java/udemyPrac/LowerWildCard.java
|
UTF-8
| 507
| 2.640625
| 3
|
[] |
no_license
|
package udemyPrac;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LowerWildCard {
public static void show(List<? super Number> list){
for(Object o: list)
{
System.out.println(o);
}
}
public static void main(String[] args) {
List<Serializable> list=new ArrayList<>();
list.add("Ashu");
list.add("Ashut");
list.add("Ashuto");
list.add("Ashutos");
show(list);
//sum(Arrays.asList(1,2,7,9,6,44));
}
}
| true
|
30f110e214448a9a9c27f25c54567ae2713ff6ef
|
Java
|
chris-atkins/recipes-website
|
/src/test/java/com/poorknight/testing/matchers/fields/FieldAnnotationValueMatcher.java
|
UTF-8
| 3,635
| 2.640625
| 3
|
[] |
no_license
|
package com.poorknight.testing.matchers.fields;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import com.poorknight.utils.ReflectionUtils;
public class FieldAnnotationValueMatcher extends TypeSafeDiagnosingMatcher<Field> {
private final Class<? extends Annotation> annotationClass;
private final String annotationFieldName;
private final Object annotationFieldValue;
private FieldAnnotationValueMatcher(final Class<? extends Annotation> annotationClass, final String annotationFieldName,
final Object annotationFieldValue) {
super();
this.annotationClass = annotationClass;
this.annotationFieldName = annotationFieldName;
this.annotationFieldValue = annotationFieldValue;
}
@Factory
public static FieldAnnotationValueMatcher hasAnnotationWithFieldOfValue(final Class<? extends Annotation> annotationClass,
final String annotationFieldName, final Object annotationFieldValue) {
return new FieldAnnotationValueMatcher(annotationClass, annotationFieldName, annotationFieldValue);
}
@Factory
public static FieldAnnotationValueMatcher isAnIdentityAutoGeneratedEntityField() {
return new FieldAnnotationValueMatcher(GeneratedValue.class, "strategy", GenerationType.IDENTITY);
}
@Override
public void describeTo(final Description description) {
description.appendText("The field has an annotation of type @").appendText(this.annotationClass.getSimpleName()).appendText(" with a ")
.appendText(this.annotationFieldName).appendText(" field that has a value of ").appendText(this.annotationFieldValue.toString());
}
@Override
protected boolean matchesSafely(final Field fieldToCheck, final Description mismatchDescription) {
if (fieldDoesNotHaveAnnotation(fieldToCheck)) {
appendNoAnnotationExistsMessage(mismatchDescription, fieldToCheck);
return false;
}
if (fieldValueDoesNotMatchExpected(fieldToCheck)) {
appendFieldValueDoesNotMatchMessage(mismatchDescription, fieldToCheck);
return false;
}
return true;
}
private boolean fieldDoesNotHaveAnnotation(final Field fieldToCheck) {
return !(ReflectionUtils.fieldHasAnnotation(fieldToCheck, this.annotationClass));
}
private boolean fieldValueDoesNotMatchExpected(final Field fieldToCheck) {
return !(getActualValue(fieldToCheck).equals(this.annotationFieldValue));
}
private void appendNoAnnotationExistsMessage(final Description mismatchDescription, final Field fieldToCheck) {
mismatchDescription.appendText("The ").appendText(fieldToCheck.getName()).appendText(" does not have an @")
.appendText(this.annotationClass.getSimpleName()).appendText(" annotation.");
}
private void appendFieldValueDoesNotMatchMessage(final Description mismatchDescription, final Field fieldToCheck) {
mismatchDescription.appendText("The ").appendText(fieldToCheck.getName()).appendText(" annotation @")
.appendText(this.annotationClass.getSimpleName()).appendText(" does not have the expected value of ")
.appendText(this.annotationFieldValue.toString()).appendText(". Value found: ").appendText(getActualValue(fieldToCheck).toString());
}
private Object getActualValue(final Field fieldToCheck) {
final Annotation annotation = fieldToCheck.getAnnotation(this.annotationClass);
return ReflectionUtils.getFieldValueFromAnnotation(annotation, this.annotationFieldName);
}
}
| true
|
0d85b4c165fda4079c62053527df1750285f95d4
|
Java
|
nguyenppt/simapp
|
/src/sim/PanelAttributeSetup.java
|
UTF-8
| 22,551
| 2.015625
| 2
|
[] |
no_license
|
package sim;
import java.awt.*;
import javax.swing.*;
import btm.swing.*;
import common.*;
import java.sql.*;
import java.awt.event.*;
import java.util.Vector;
import btm.attr.*;
import java.sql.Statement;
import java.util.ResourceBundle;
/**
* <p>Title: </p>
* <p>Description: Main -> Merch Mgmt -> Attribute Setup</p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class PanelAttributeSetup extends JPanel {
DataAccessLayer DAL;
FrameMainSim frmMain;
Utils ut = new Utils();
Statement stmt = null;
BorderLayout borderLayout1 = new BorderLayout();
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JPanel jPanel3 = new JPanel();
BJButton btnCancel = new BJButton();
BJButton btnDelete = new BJButton();
BJButton btnAdd = new BJButton();
BJButton btnDone = new BJButton();
BJButton btnView = new BJButton();
BorderLayout borderLayout2 = new BorderLayout();
JPanel jPanel4 = new JPanel();
JPanel jPanel5 = new JPanel();
JPanel jPanel6 = new JPanel();
BorderLayout borderLayout3 = new BorderLayout();
JPanel jPanel7 = new JPanel();
JPanel jPanel8 = new JPanel();
JLabel lblColorSize = new JLabel();
JLabel lblProdGroup = new JLabel();
JLabel lblAttribute = new JLabel();
JTextField txtColorSize = new JTextField();
BJComboBox cboProdGroup = new BJComboBox();
BJComboBox cboAttr = new BJComboBox();
JScrollPane jScrollPane1 = new JScrollPane();
SortableTableModel dm = new SortableTableModel();
ResourceBundle lang=DataAccessLayer.getFrameLabel(Utils.sLanguague ,Utils.sCountry);
BJTable table = new BJTable(dm){
public boolean isCellEditable(int row,int col){
return false;
}
};
StripedTableCellRenderer stripedTable = new StripedTableCellRenderer(null,Color.lightGray,Color.white,null,null);
ResultSet rs = null;
String attrDtlID = "";
Vector vSql = new Vector();
Vector vId = new Vector();
public PanelAttributeSetup(FrameMainSim frmMain) {
try {
this.frmMain = frmMain;
this.DAL = frmMain.getDAL();
jbInit();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
void jbInit() throws Exception {
registerKeyboardActions();
this.setSize(new Dimension(795, 600));
this.setLayout(borderLayout1);
jPanel1.setBackground(new Color(121, 152, 198));
jPanel1.setPreferredSize(new Dimension(800, 50));
jPanel2.setPreferredSize(new Dimension(800, 150));
jPanel2.setLayout(borderLayout2);
jPanel3.setPreferredSize(new Dimension(800, 400));
btnCancel.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
btnCancel.setText("<html><center><b>"+lang.getString("Cancel")+" </b></center> &n" +
"bsp; &" + "nbsp;F12</html>");
btnCancel.addActionListener(new PanelAttributeSetup_btnCancel_actionAdapter(this));
btnDelete.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
btnDelete.setText(lang.getString("Delete")+" (F8)");
btnDelete.addActionListener(new PanelAttributeSetup_btnDelete_actionAdapter(this));
btnAdd.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
btnAdd.setText(lang.getString("Add")+" (F2)");
btnAdd.addActionListener(new PanelAttributeSetup_btnAdd_actionAdapter(this));
btnDone.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
btnDone.setText(lang.getString("Done")+" (F1)");
btnDone.addActionListener(new PanelAttributeSetup_btnDone_actionAdapter(this));
btnView.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
btnView.setText(lang.getString("View")+" (F5)");
btnView.addActionListener(new PanelAttributeSetup_btnView_actionAdapter(this));
btnView.setToolTipText(lang.getString("View")+" (F5)");
jPanel4.setPreferredSize(new Dimension(50, 150));
jPanel5.setPreferredSize(new Dimension(300, 150));
jPanel5.setLayout(borderLayout3);
jPanel6.setPreferredSize(new Dimension(420, 150));
jPanel7.setPreferredSize(new Dimension(100, 150));
jPanel8.setPreferredSize(new Dimension(200, 150));
lblColorSize.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
lblColorSize.setPreferredSize(new Dimension(90, 20));
lblColorSize.setText(lang.getString("ColorSize")+":");
lblProdGroup.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
lblProdGroup.setPreferredSize(new Dimension(90, 20));
lblProdGroup.setText(lang.getString("ProGroup")+":");
lblAttribute.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
lblAttribute.setPreferredSize(new Dimension(90, 20));
lblAttribute.setText(lang.getString("Attribute")+":");
txtColorSize.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
txtColorSize.setPreferredSize(new Dimension(200, 20));
// txtColorSize.addFocusListener(new PanelAttributeSetup_txtColorSize_focusAdapter(this));
// txtColorSize.addKeyListener(new PanelAttributeSetup_txtColorSize_keyAdapter(this));
cboAttr.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
cboAttr.setPreferredSize(new Dimension(200, 20));
cboAttr.addActionListener(new PanelAttributeSetup_cboAttr_actionAdapter(this));
cboProdGroup.setFont(new java.awt.Font(lang.getString("FontName_Label"), 1, 12));
cboProdGroup.setPreferredSize(new Dimension(200, 20));
jScrollPane1.setPreferredSize(new Dimension(790, 390));
table.addKeyListener(new PanelAttributeSetup_table_keyAdapter(this));
this.add(jPanel1, BorderLayout.NORTH);
this.add(jPanel2, BorderLayout.CENTER);
jPanel2.add(jPanel4, BorderLayout.WEST);
jPanel2.add(jPanel5, BorderLayout.CENTER);
jPanel5.add(jPanel7, BorderLayout.WEST);
jPanel7.add(lblAttribute, null);
jPanel7.add(lblProdGroup, null);
jPanel7.add(lblColorSize, null);
jPanel5.add(jPanel8, BorderLayout.CENTER);
jPanel2.add(jPanel6, BorderLayout.EAST);
this.add(jPanel3, BorderLayout.SOUTH);
jPanel3.add(jScrollPane1, null);
jScrollPane1.getViewport().add(table, null);
jPanel1.add(btnDone, null);
jPanel1.add(btnAdd, null);
jPanel1.add(btnView, null);
jPanel1.add(btnDelete, null);
jPanel1.add(btnCancel, null);
jPanel8.add(cboAttr, null);
jPanel8.add(cboProdGroup, null);
jPanel8.add(txtColorSize, null);
dm.addColumn(lang.getString("ColorSize"));
dm.addColumn(lang.getString("ProGroup"));
dm.addColumn(lang.getString("Attribute"));
// getAttrDtlID();
}
//apply employee's permission for this screen
public void applyPermission() {
EmpRight er = new EmpRight();
er.initData(DAL, DAL.getEmpID());
er.setData(DAL.getEmpID(), Constant.SCRS_ATTRIBUTE_SETUP);
btnAdd.setEnabled(er.getAdd());
btnDelete.setEnabled(er.getDelete());
}
//Show data
void showdata(){
// setOpenConnection();
getAttrDtlID();
showCboAttr();
showCboProdGroup();
}
//show combo attribute data
void showCboAttr(){
rs = null;
try {
stmt = DAL.getConnection().createStatement(ResultSet.
TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch (Exception ex) {
ex.printStackTrace();
}
try{
String sql = "select attr_id, attr_desc from btm_im_attr where attr_id <> -1";
// System.out.println(sql);
rs = DAL.executeScrollQueries(sql,stmt);
cboAttr.setData(rs);
rs.getStatement().close();
}catch(Exception e){
}
try {
stmt.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
//show combo product group
void showCboProdGroup(){
rs = null;
try{
stmt = DAL.getConnection().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql = "select child_id, child_name from btm_im_prod_hir where recd_curr_flag = 1 and child_id in (select dept_id from BTM_IM_MAP_DEPARTMENT)";
// System.out.println(sql);
rs = DAL.executeScrollQueries(sql,stmt);
cboProdGroup.setData(rs);
rs.close();
stmt.close();
}catch(Exception e){
}
}
//get attr_dtl_id
void getAttrDtlID(){
rs = null;
try{
String sql = "";
stmt = DAL.getConnection().createStatement();
sql = "select attr_dtl_id from btm_im_attr_dtl order by attr_dtl_id desc";
// System.out.println(sql);
rs = DAL.executeQueries(sql,stmt);
if (rs.next()){
this.attrDtlID = rs.getString("attr_dtl_id");
this.attrDtlID = ut.getYeroCode(Integer.parseInt(this.attrDtlID)+1,4);
}else {
this.attrDtlID = "0001";
}
rs.getStatement().close();
stmt.close();
}catch(Exception e){
// ExceptionHandle eh = new ExceptionHandle();
// eh.ouputError(e);
}
}
//Reset data
void resetData(){
// cboAttr.setSelectedIndex(0);
// cboProdGroup.setSelectedIndex(0);
// lblColorSize.setText("Color:");
txtColorSize.setText("");
}
void cboAttr_actionPerformed(ActionEvent e) {
if (cboAttr.getSelectedIndex() == 0){
lblColorSize.setText(lang.getString("Color")+":");
}else{
lblColorSize.setText(lang.getString("Size")+":");
}
}
private boolean checkExistInDatabase(String attrID, String prod_group_id, String attrDtlDesc){
boolean result = false;
String sqlStr = "Select Attr_Dtl_Id From BTM_IM_ATTR_DTL Where Attr_id='" + attrID
+ "' and lower(Attr_Dtl_Desc)=lower('" + attrDtlDesc+ "') and Prod_Group_Id='" + prod_group_id + "'";
try{
stmt = DAL.getConnection().createStatement(ResultSet.
TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = DAL.executeScrollQueries(sqlStr,stmt);
if(rs.next()){
result = true;
}
rs.close();
stmt.close();
}catch(Exception ex){};
return result;
}
private boolean checkExistOnTable(String attrID, String prod_group_id, String attrDtlDesc){
for(int i=0;i<table.getRowCount() ; i++){
String arrId[] = (String [])vId.get(i);
if( attrID.equals(arrId[0]) && prod_group_id.equals(arrId[1])
&& attrDtlDesc.equals(table.getValueAt(i,2))){
return true;
}
}
return false;
}
void btnAdd_actionPerformed(ActionEvent e) {
String attrID = cboAttr.getSelectedData();
String prod_group_id = cboProdGroup.getSelectedData();
String attrDtlDesc = txtColorSize.getText().trim();
if (attrDtlDesc.equals("")) {
ut.showMessage(frmMain, lang.getString("TT001"), lang.getString("MS1003_ColorOrSizeIsNotNull"));
txtColorSize.requestFocus(true);
return;
}
if(checkExistInDatabase(attrID,prod_group_id,attrDtlDesc)){
ut.showMessage(frmMain,lang.getString("TT001"),lang.getString("MS1004_ThisAttributeIsAlreadyExisted"));
txtColorSize.requestFocus(true);
return;
}
if (checkExistOnTable(attrID, prod_group_id, attrDtlDesc)) {
ut.showMessage(frmMain, lang.getString("TT001"), lang.getString("MS1004_ThisAttributeIsAlreadyExisted"));
txtColorSize.requestFocus(true);
return;
}
String sql = "insert into btm_im_attr_dtl values('" + this.attrDtlID +
"','" + attrID + "','" + attrDtlDesc + "',to_date('" + ut.getSystemDate() +
"','" + ut.DATE_FORMAT + "'),'" + DAL.getemployeeID() + "',to_date('" + ut.getSystemDate() +
"','" + ut.DATE_FORMAT + "'),'" + prod_group_id + "')";
// System.out.println(sql);
vSql.addElement(sql);
String arrID[] = {attrID,prod_group_id};
vId.add(arrID);
this.attrDtlID = ut.getYeroCode(Integer.parseInt(this.attrDtlID) + 1, 4);
String attrData = cboAttr.getSelectedItem().toString();
String prodGroupData = cboProdGroup.getSelectedItem().toString();
String colorOrSize = txtColorSize.getText();
Object[] rowData = new Object[]{
attrData, prodGroupData, colorOrSize
};
dm.addRow(rowData);
// stripedTable.installInTable(table, Color.lightGray, Color.white,Color.white, Color.black);
float[] f1 = new float[3];
Color.RGBtoHSB(255,255,230,f1);
stripedTable.installInTable(table, Color.getHSBColor(f1[0],f1[1],f1[2]), Color.black, null, null);
resetData();
txtColorSize.requestFocus(true);
}
// void txtColorSize_keyTyped(KeyEvent e) {
// ut.limitLenjTextField(e,txtColorSize, 120);
// if (lblColorSize.getText().equalsIgnoreCase("Size:")){
// ut.checkNumber(e);
// char key = e.getKeyChar();
// if (ut.isDoubleString("" + key) || key == KeyEvent.VK_BACK_SPACE || key == KeyEvent.VK_DELETE || key == '.'){
// return;
// }else{
// e.consume();
// }
// }
// }
void btnDone_actionPerformed(ActionEvent e) {
try {
stmt = DAL.getConnection().createStatement();
}
catch (Exception ex) {
ex.printStackTrace();
}
if (!vSql.isEmpty()){
DAL.setBeginTrans(DAL.getConnection());
DAL.executeBatchQuery(vSql,stmt);
DAL.setEndTrans(DAL.getConnection());
vSql.clear();
vId.clear();
}
resetData();
cboAttr.setSelectedIndex(0);
cboProdGroup.setSelectedIndex(0);
lblColorSize.setText(lang.getString("Color")+":");
while (table.getRowCount()>0){
dm.removeRow(0);
}
frmMain.showScreen(Constant.SCRS_MAIN_SIM);
frmMain.pnlMainSim.showMerchanSystemButton();
frmMain.setTitle(lang.getString("TT0002"));
try {
stmt.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private void refreshData(){
vSql.clear();
vId.clear();
resetData();
cboAttr.setSelectedIndex(0);
cboProdGroup.setSelectedIndex(0);
lblColorSize.setText(lang.getString("Color")+":");
while(table.getRowCount()>0){
dm.removeRow(0);
}
}
void btnCancel_actionPerformed(ActionEvent e) {
refreshData();
frmMain.showScreen(Constant.SCRS_MAIN_SIM);
frmMain.pnlMainSim.showMerchanSystemButton();
frmMain.setTitle(lang.getString("TT0001"));
}
void btnDelete_actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if(row >=0){
vSql.removeElementAt(row);
vId.removeElementAt(row);
dm.removeRow(row);
}
}
void btnView_actionPerformed(ActionEvent e) {
refreshData();
frmMain.showScreen(Constant.SCRS_ATTRIBUTE_VIEW);
frmMain.pnlAttrView.modifyStatus = false;
frmMain.pnlAttrView.showAttribute();
frmMain.pnlAttrView.cboAttr.setSelectedIndex(0);
}
// void txtColorSize_focusLost(FocusEvent e) {
// String size = txtColorSize.getText().trim();
// if (lblColorSize.getText().equalsIgnoreCase("Size:")){
// String result = "";
// int tempDot = 0;
// int i = 0;
// for (i = 0; i<size.length(); i++){
// if (size.substring(i,i+1).equalsIgnoreCase(".")){
// tempDot ++;
// }
// if (tempDot >= 2){
// break;
// }
// }
// result = size.substring(0,i);
// txtColorSize.setText("" + Double.parseDouble(result));
// }
// }
private void registerKeyboardActions() {
/// set up the maps:
InputMap inputMap = getInputMap(WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getActionMap();
// F1
Integer key = new Integer(KeyEvent.VK_F1);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), key);
actionMap.put(key, new KeyAction(key));
// F2
key = new Integer(KeyEvent.VK_F2);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), key);
actionMap.put(key, new KeyAction(key));
// F3
key = new Integer(KeyEvent.VK_F3);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), key);
actionMap.put(key, new KeyAction(key));
// F4
key = new Integer(KeyEvent.VK_F4);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), key);
actionMap.put(key, new KeyAction(key));
// F5
key = new Integer(KeyEvent.VK_F5);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), key);
actionMap.put(key, new KeyAction(key));
// F5
key = new Integer(KeyEvent.VK_F5);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), key);
actionMap.put(key, new KeyAction(key));
// F6
key = new Integer(KeyEvent.VK_F6);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0), key);
actionMap.put(key, new KeyAction(key));
// F7
key = new Integer(KeyEvent.VK_F7);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0), key);
actionMap.put(key, new KeyAction(key));
// F8
key = new Integer(KeyEvent.VK_F8);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0), key);
actionMap.put(key, new KeyAction(key));
// F9
key = new Integer(KeyEvent.VK_F9);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0), key);
actionMap.put(key, new KeyAction(key));
// F10
key = new Integer(KeyEvent.VK_F10);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F10, 0), key);
actionMap.put(key, new KeyAction(key));
// F11
key = new Integer(KeyEvent.VK_F11);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0), key);
actionMap.put(key, new KeyAction(key));
// F12
key = new Integer(KeyEvent.VK_F12);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), key);
actionMap.put(key, new KeyAction(key));
// ENTER
key = new Integer(KeyEvent.VK_ENTER);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), key);
actionMap.put(key, new KeyAction(key));
// Escape
key = new Integer(KeyEvent.VK_ESCAPE);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), key);
actionMap.put(key, new KeyAction(key));
}
class KeyAction extends AbstractAction {
private Integer identifier = null;
public KeyAction(Integer identifier) {
this.identifier = identifier;
}
/**
* Invoked when an action occurs.
*/
public void actionPerformed(ActionEvent e) {
if (identifier.intValue() == KeyEvent.VK_F1) {
btnDone.doClick();
}
else if (identifier.intValue() == KeyEvent.VK_F2) {
btnAdd.doClick();
}
else if (identifier.intValue() == KeyEvent.VK_F8) {
btnDelete.doClick();
}
else if (identifier.intValue() == KeyEvent.VK_F5) {
btnView.doClick();
}
else if (identifier.intValue() == KeyEvent.VK_F12 ||identifier.intValue() == KeyEvent.VK_ESCAPE) {
btnCancel.doClick();
}
}
}
void table_keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F2) {
btnAdd.doClick();
}
}
}
class PanelAttributeSetup_cboAttr_actionAdapter implements java.awt.event.ActionListener {
PanelAttributeSetup adaptee;
PanelAttributeSetup_cboAttr_actionAdapter(PanelAttributeSetup adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.cboAttr_actionPerformed(e);
}
}
class PanelAttributeSetup_btnAdd_actionAdapter implements java.awt.event.ActionListener {
PanelAttributeSetup adaptee;
PanelAttributeSetup_btnAdd_actionAdapter(PanelAttributeSetup adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.btnAdd_actionPerformed(e);
}
}
//class PanelAttributeSetup_txtColorSize_keyAdapter extends java.awt.event.KeyAdapter {
// PanelAttributeSetup adaptee;
//
// PanelAttributeSetup_txtColorSize_keyAdapter(PanelAttributeSetup adaptee) {
// this.adaptee = adaptee;
// }
// public void keyTyped(KeyEvent e) {
// adaptee.txtColorSize_keyTyped(e);
// }
//}
class PanelAttributeSetup_btnDone_actionAdapter implements java.awt.event.ActionListener {
PanelAttributeSetup adaptee;
PanelAttributeSetup_btnDone_actionAdapter(PanelAttributeSetup adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.btnDone_actionPerformed(e);
}
}
class PanelAttributeSetup_btnCancel_actionAdapter implements java.awt.event.ActionListener {
PanelAttributeSetup adaptee;
PanelAttributeSetup_btnCancel_actionAdapter(PanelAttributeSetup adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.btnCancel_actionPerformed(e);
}
}
class PanelAttributeSetup_btnDelete_actionAdapter implements java.awt.event.ActionListener {
PanelAttributeSetup adaptee;
PanelAttributeSetup_btnDelete_actionAdapter(PanelAttributeSetup adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.btnDelete_actionPerformed(e);
}
}
//class PanelAttributeSetup_txtColorSize_focusAdapter extends java.awt.event.FocusAdapter {
// PanelAttributeSetup adaptee;
//
// PanelAttributeSetup_txtColorSize_focusAdapter(PanelAttributeSetup adaptee) {
// this.adaptee = adaptee;
// }
// public void focusLost(FocusEvent e) {
// adaptee.txtColorSize_focusLost(e);
// }
//}
class PanelAttributeSetup_btnView_actionAdapter implements java.awt.event.ActionListener {
PanelAttributeSetup adaptee;
PanelAttributeSetup_btnView_actionAdapter(PanelAttributeSetup adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.btnView_actionPerformed(e);
}
}
class PanelAttributeSetup_table_keyAdapter extends java.awt.event.KeyAdapter {
PanelAttributeSetup adaptee;
PanelAttributeSetup_table_keyAdapter(PanelAttributeSetup adaptee) {
this.adaptee = adaptee;
}
public void keyPressed(KeyEvent e) {
adaptee.table_keyPressed(e);
}
}
| true
|
a546db9862db645f1722b5038625664b210bd9c2
|
Java
|
nana1220/practice
|
/interview/TheCelebrityProblem.java
|
UTF-8
| 2,149
| 3.9375
| 4
|
[] |
no_license
|
/*
In a party of N people, only one person is known to everyone. Such a person may be present in the party, if yes,
(s)he doesn’t know anyone in the party. We can only ask questions like “does A know B? “. Find the stranger (celebrity) in minimum number of questions.
可以分析几种情况
如果A认识B,那么A不可能是celebrity。去掉A,B则有可能是
如果A不认识B,那么B不可能是celebrity。去掉B,A则有可能是
重复以上两个步骤直到只剩下一个候选人
再次确认是否这最后一个人是否为celebrity
这里用stack来做。
把所有的celebrity压栈
弹出最上面的两个celebrity,根据HaveAcquaintance(A, B)的结果来去掉一个一定不是celebrity的人
将2中剩下的那一位压栈
重复以上两个步骤,直到stack中只剩一个人
确认这个人不认识其他任何人
以上算法需要调用HaveAcquaintance(A,B) 3(N-1)次。
*/
class Solu{
int CelebrityUsingStack(int size) {
// Handle trivial case of size = 2
list<int> stack; // Careful about naming
int i;
int C; // Celebrity
i = 0;
while( i < size ) {
stack.push_back(i);
i = i + 1;
}
int A = stack.back();
stack.pop_back();
int B = stack.back();
stack.pop_back();
while( stack.size() != 1 ) {
if( HaveAcquiantance(A, B) ) {
A = stack.back();
stack.pop_back();
} else {
B = stack.back();
stack.pop_back();
}
}
// Potential candidate?
C = stack.back();
stack.pop_back();
// Last candidate was not examined, it leads one excess comparison (optimise)
if( HaveAcquiantance(C, B) ) C = B;
if( HaveAcquiantance(C, A) ) C = A;
// I know these are redundant,
// we can simply check i against C
i = 0;
while( i < size ) {
if( C != i )
stack.push_back(i);
i = i + 1;
}
while( !stack.empty() ) {
i = stack.back();
stack.pop_back();
// C must not know i
if( HaveAcquiantance(C, i) ) return -1;
// i must know C
if( !HaveAcquiantance(i, C) ) return -1;
}
return C;
}
}
| true
|
61ec432d5887b19f08b876a6b620b897087612d0
|
Java
|
GA07A/Android-Project1
|
/app/src/main/java/com/example/finalproject/SplachScreen.java
|
UTF-8
| 714
| 1.976563
| 2
|
[] |
no_license
|
package com.example.finalproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplachScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splach_screen);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Intent intent=new Intent(SplachScreen.this,SignUp.class);
startActivity(intent);
finish();
}
},6000);
}
}
| true
|
2adf407452a362e1791adc540c1b868aba8efe12
|
Java
|
liangliangle/mass
|
/coreApp/src/main/java/com/mass/service/RegisterService.java
|
UTF-8
| 1,005
| 1.625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.mass.service;
import com.github.pagehelper.PageInfo;
import com.mass.dto.create.CreateRegisterDto;
import com.mass.dto.create.CreateRegisterMemDto;
import com.mass.dto.query.ExportRegister;
import com.mass.dto.query.RegisterQuery;
import com.mass.dto.result.RegisterCodeDto;
import com.mass.dto.result.RegisterDto;
import com.mass.entity.RegisterCode;
import com.mass.entity.RegisterMem;
import java.util.List;
public interface RegisterService {
void create(CreateRegisterDto dto);
void update(CreateRegisterDto dto);
RegisterCodeDto getRegisterCode(Long id);
void register(CreateRegisterMemDto dto);
PageInfo<RegisterDto> getBySnoAndStatus(String sno, Integer status, Integer page);
PageInfo<RegisterDto> query(RegisterQuery query, Integer page);
List<List<String>> export(ExportRegister register);
PageInfo<RegisterMem> result(Long id, Integer page);
List<RegisterDto> getByActivity(Long activityId);
RegisterDto getById(Long id);
}
| true
|
62eaacc1f7a4e3d87d7d577f981ae02ed47faae1
|
Java
|
suyambuganesh82/sitewhere-java-api
|
/sitewhere-java-model/src/main/java/com/sitewhere/rest/model/device/DeviceAssignmentSummary.java
|
UTF-8
| 6,767
| 2.015625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/**
* Copyright © 2014-2021 The SiteWhere Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sitewhere.rest.model.device;
import java.util.Date;
import java.util.UUID;
import com.sitewhere.rest.model.common.PersistentEntity;
import com.sitewhere.spi.device.DeviceAssignmentStatus;
import com.sitewhere.spi.device.IDeviceAssignmentSummary;
/**
* Summarizes device and directly related entities such as device type and
* assignments.
*/
public class DeviceAssignmentSummary extends PersistentEntity implements IDeviceAssignmentSummary {
/** Serial version UID */
private static final long serialVersionUID = -6857027037347179506L;
/** Id of associated device */
private UUID deviceId;
/** Token of associated device */
private String deviceToken;
/** Type id of associated device */
private UUID deviceTypeId;
/** Device type name */
private String deviceTypeName;
/** Device type image url */
private String deviceTypeImageUrl;
/** Id of assigned customer */
private UUID customerId;
/** Customer name */
private String customerName;
/** Customer image url */
private String customerImageUrl;
/** Id of assigned area */
private UUID areaId;
/** Area name */
private String areaName;
/** Area image url */
private String areaImageUrl;
/** Id of assigned asset */
private UUID assetId;
/** Asset name */
private String assetName;
/** Asset image url */
private String assetImageUrl;
/** Assignment status */
private DeviceAssignmentStatus status;
/** Assignment start date */
private Date activeDate;
/** Assignment end date */
private Date releasedDate;
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getDeviceId()
*/
@Override
public UUID getDeviceId() {
return deviceId;
}
public void setDeviceId(UUID deviceId) {
this.deviceId = deviceId;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getDeviceToken()
*/
@Override
public String getDeviceToken() {
return deviceToken;
}
public void setDeviceToken(String deviceToken) {
this.deviceToken = deviceToken;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getDeviceTypeId()
*/
@Override
public UUID getDeviceTypeId() {
return deviceTypeId;
}
public void setDeviceTypeId(UUID deviceTypeId) {
this.deviceTypeId = deviceTypeId;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getDeviceTypeName()
*/
@Override
public String getDeviceTypeName() {
return deviceTypeName;
}
public void setDeviceTypeName(String deviceTypeName) {
this.deviceTypeName = deviceTypeName;
}
/*
* @see
* com.sitewhere.spi.device.IDeviceAssignmentSummary#getDeviceTypeImageUrl()
*/
@Override
public String getDeviceTypeImageUrl() {
return deviceTypeImageUrl;
}
public void setDeviceTypeImageUrl(String deviceTypeImageUrl) {
this.deviceTypeImageUrl = deviceTypeImageUrl;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getCustomerId()
*/
@Override
public UUID getCustomerId() {
return customerId;
}
public void setCustomerId(UUID customerId) {
this.customerId = customerId;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getCustomerName()
*/
@Override
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getCustomerImageUrl()
*/
@Override
public String getCustomerImageUrl() {
return customerImageUrl;
}
public void setCustomerImageUrl(String customerImageUrl) {
this.customerImageUrl = customerImageUrl;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getAreaId()
*/
@Override
public UUID getAreaId() {
return areaId;
}
public void setAreaId(UUID areaId) {
this.areaId = areaId;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getAreaName()
*/
@Override
public String getAreaName() {
return areaName;
}
public void setAreaName(String areaName) {
this.areaName = areaName;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getAreaImageUrl()
*/
@Override
public String getAreaImageUrl() {
return areaImageUrl;
}
public void setAreaImageUrl(String areaImageUrl) {
this.areaImageUrl = areaImageUrl;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getAssetId()
*/
@Override
public UUID getAssetId() {
return assetId;
}
public void setAssetId(UUID assetId) {
this.assetId = assetId;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getAssetName()
*/
@Override
public String getAssetName() {
return assetName;
}
public void setAssetName(String assetName) {
this.assetName = assetName;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getAssetImageUrl()
*/
@Override
public String getAssetImageUrl() {
return assetImageUrl;
}
public void setAssetImageUrl(String assetImageUrl) {
this.assetImageUrl = assetImageUrl;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getStatus()
*/
@Override
public DeviceAssignmentStatus getStatus() {
return status;
}
public void setStatus(DeviceAssignmentStatus status) {
this.status = status;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getActiveDate()
*/
@Override
public Date getActiveDate() {
return activeDate;
}
public void setActiveDate(Date activeDate) {
this.activeDate = activeDate;
}
/*
* @see com.sitewhere.spi.device.IDeviceAssignmentSummary#getReleasedDate()
*/
@Override
public Date getReleasedDate() {
return releasedDate;
}
public void setReleasedDate(Date releasedDate) {
this.releasedDate = releasedDate;
}
}
| true
|
5a156c69ec859968ac0b1b5441788770675f30ba
|
Java
|
Leader0721/JavaStudyDemo
|
/src/day15jdbc01/utils/JDBCUtils.java
|
UTF-8
| 1,954
| 2.875
| 3
|
[] |
no_license
|
package day15jdbc01.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* Created by 83731 on 2017/09/17.
*/
public class JDBCUtils {
private static String driverClass;
private static String url;
private static String user;
private static String password;
//静态代码块是最先加载的 然后再加载方法
static {
try {
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
InputStream in = classLoader.getResourceAsStream("dbcfg.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(driverClass);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws Exception {
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
public static void release(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
connection = null;
}
}
}
| true
|
0aad8a655d094fd0926123efaf55d42116aad5dc
|
Java
|
a3377125a/Database-Project
|
/Backend/src/main/java/edu/fudan/database/controller/request/chiefNurse/ModifyRequest.java
|
UTF-8
| 659
| 2.359375
| 2
|
[] |
no_license
|
package edu.fudan.database.controller.request.chiefNurse;
public class ModifyRequest {
private String chiefNurse;
private String nurseName;
public ModifyRequest() {
}
public ModifyRequest(String chiefNurse, String nurseName) {
this.chiefNurse = chiefNurse;
this.nurseName = nurseName;
}
public String getChiefNurse() {
return chiefNurse;
}
public void setChiefNurse(String chiefNurse) {
this.chiefNurse = chiefNurse;
}
public String getNurseName() {
return nurseName;
}
public void setNurseName(String nurseName) {
this.nurseName = nurseName;
}
}
| true
|
b0e52fc79c7cf91345c98b24f3852070804c98c3
|
Java
|
ccfish86/jvue-admin
|
/server/jvue-api/src/main/java/net/ccfish/jvue/rest/VueController.java
|
UTF-8
| 786
| 1.898438
| 2
|
[
"MIT"
] |
permissive
|
package net.ccfish.jvue.rest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import net.ccfish.common.acl.CurrentUser;
import net.ccfish.jvue.security.JwtUserDetails;
@Controller
public class VueController {
private Logger logger = LoggerFactory.getLogger(getClass());
@GetMapping(path = { "", "/", "/admin", "/admin/**" }, produces = {MediaType.TEXT_HTML_VALUE})
public ModelAndView home(@CurrentUser JwtUserDetails jwtUser) {
logger.debug("vue home {}", jwtUser);
ModelAndView view = new ModelAndView("/index");
return view;
}
}
| true
|
13c077c33054538ded83d36127ee24b507bbb8d4
|
Java
|
STAMP-project/dspot-experiments
|
/benchmark/training/alluxio/test/util/CommonTestUtilsTest.java
|
UTF-8
| 5,544
| 2.3125
| 2
|
[] |
no_license
|
/**
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.test.util;
import alluxio.underfs.UnderFileSystem.SpaceType;
import java.util.Objects;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
/**
* Unit tests for {@link CommonUtils}.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(CommonTestUtilsTest.HardToInstantiateClass.class)
public final class CommonTestUtilsTest {
public static final class HardToInstantiateClass {
private HardToInstantiateClass(Object o) {
}
}
/**
* A simple class that has a correct hashcode method.
*/
private static class Basic {
private String mField;
@Override
public boolean equals(Object o) {
if ((this) == o) {
return true;
}
if (!(o instanceof CommonTestUtilsTest.Basic)) {
return false;
}
CommonTestUtilsTest.Basic that = ((CommonTestUtilsTest.Basic) (o));
return Objects.equals(mField, that.mField);
}
@Override
public int hashCode() {
return Objects.hash(mField);
}
}
/**
* A simple class that has a bad hashcode method.
*/
private static class BadHashCode {
private String mField;
@Override
public boolean equals(Object o) {
if (!(o instanceof CommonTestUtilsTest.Basic)) {
return false;
}
CommonTestUtilsTest.Basic that = ((CommonTestUtilsTest.Basic) (o));
return Objects.equals(mField, that.mField);
}
@Override
public int hashCode() {
return Objects.hash(10);// Should be mField.
}
}
/**
* A simple class that has a correct equals method.
*/
private static class ManyFields {
private String mField1;
private boolean mField2;
// Use HardToInstantiateClass as an example of a final class without a no-arg constructor.
private CommonTestUtilsTest.HardToInstantiateClass mField3;
// Example of an enum.
private SpaceType mField4;
@Override
public boolean equals(Object o) {
if (!(o instanceof CommonTestUtilsTest.ManyFields)) {
return false;
}
CommonTestUtilsTest.ManyFields that = ((CommonTestUtilsTest.ManyFields) (o));
return (((Objects.equals(mField1, that.mField1)) && (Objects.equals(mField2, that.mField2))) && (Objects.equals(mField3, that.mField3))) && (Objects.equals(mField4, that.mField4));
}
@Override
public int hashCode() {
return Objects.hash(mField1, mField2, mField3, mField4);
}
}
/**
* A simple class that has a bad equals method due to missing field.
*/
private static class MissingField {
private String mField1;
private boolean mField2;
private CommonUtils mField3;
@Override
public boolean equals(Object o) {
if (!(o instanceof CommonTestUtilsTest.MissingField)) {
return false;
}
CommonTestUtilsTest.MissingField that = ((CommonTestUtilsTest.MissingField) (o));
// Missing test for mField3.
return (Objects.equals(mField1, that.mField1)) && (Objects.equals(mField2, that.mField2));
}
@Override
public int hashCode() {
// Missing mField3.
return Objects.hash(mField1, mField2);
}
}
/**
* A simple class that has a bad equals method due to missing instance check.
*/
private static class EqualsMissingInstanceCheck {
private String mField1;
private boolean mField2;
private CommonUtils mField3;
@Override
public boolean equals(Object o) {
// Missing test for o instanceof EqualsMissingField.
CommonTestUtilsTest.MissingField that = ((CommonTestUtilsTest.MissingField) (o));
return ((Objects.equals(mField1, that.mField1)) && (Objects.equals(mField2, that.mField2))) && (Objects.equals(mField3, that.mField3));
}
@Override
public int hashCode() {
return Objects.hash(mField1, mField2, mField3);
}
}
@Test
public void testEqualsBasic() throws Exception {
CommonUtils.testEquals(CommonTestUtilsTest.Basic.class);
}
@Test
public void testEqualsManyFields() {
CommonUtils.testEquals(CommonTestUtilsTest.ManyFields.class);
}
@Test
public void testEqualsBadHashCodeCheck() {
testFail(CommonTestUtilsTest.BadHashCode.class);
}
@Test
public void testEqualsMissingFieldCheck() {
testFail(CommonTestUtilsTest.MissingField.class);
}
@Test
public void testEqualsMissingInstanceCheck() {
testFail(CommonTestUtilsTest.EqualsMissingInstanceCheck.class);
}
}
| true
|
289e156266b65974ca553a4c2974ff7a0609a1ec
|
Java
|
nilshan77/Map-Reduce-Example
|
/Srjoin/src/main/java/com/home/Srjoin/App.java
|
UTF-8
| 1,861
| 2.375
| 2
|
[] |
no_license
|
package com.home.Srjoin;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
/**
* Hello world!
*
*/
public class App extends Configured implements Tool {
public static void main(String[] args) throws Exception {
int exitStatus = ToolRunner.run(new App(), args);
System.exit(exitStatus);
}
public int run(String[] args) throws Exception {
Job job = Job.getInstance(getConf());
job.setJarByClass(App.class);
job.setJobName("Service Request Reduce Example");
String[] paths = new GenericOptionsParser(args).getRemainingArgs();
/* Set input and output paths */
MultipleInputs.addInputPath(job, new Path(paths[0]), TextInputFormat.class, SRMapper.class);
MultipleInputs.addInputPath(job, new Path(paths[1]), TextInputFormat.class, SRDetailsMapper.class);
FileOutputFormat.setOutputPath(job, new Path(paths[2]));
/* Set map and map output */
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(GenericSrWritable.class);
/* Set sorting */
job.setGroupingComparatorClass(SrGroupComparator.class);
/* Set Reducer */
job.setReducerClass(SrReducer.class);
/* Set input and output format */
job.setOutputFormatClass(ServiceOutputFormat.class);
int returnStatus = job.waitForCompletion(true) ? 0 : 1;
System.out.println(job.getJobName() + "is successfully Completed :" + job.isSuccessful());
return returnStatus;
}
}
| true
|
3a3b6c43f024d0b5a9af4aaeacc3eba0f701c789
|
Java
|
le-christine/dev-academy
|
/Week4/9-19-19/Abstract-Classes/src/example/Interface2/Tire.java
|
UTF-8
| 398
| 3.21875
| 3
|
[] |
no_license
|
package example.Interface2;
public class Tire implements Moveable, Rollable {
int width;
public boolean isRollable() {
return true;
};
public boolean isMoveable() {
return true;
}
public static void main(String[] args) {
Tire tire = new Tire();
System.out.println(tire.isMoveable());
System.out.println(tire.isRollable());
}
}
| true
|
eefb052e983d67807a6cffa1b427c6acc4dec410
|
Java
|
darshandarane/com-cg-java-demo
|
/src/com/cg/demo/method/App2.java
|
UTF-8
| 147
| 1.523438
| 2
|
[
"MIT"
] |
permissive
|
package com.cg.demo.method;
public class App2 {
public static void main(String[] args) {
Product1 = new Product();
p1.id = 4555
}
}
| true
|
40888c315e1e33ebc4ce0afd148ac42620bd3459
|
Java
|
Brandon3107/Lenguajes-BrandonPG
|
/src/Excepciones/PendejoException.java
|
UTF-8
| 170
| 2.140625
| 2
|
[] |
no_license
|
package Excepciones;
public class PendejoException extends Exception{
public PendejoException(){
super("Pendejo, aun ni naces.");
}
}
| true
|
c860d51ba0e95c347dbed1a1f59ee567486dfc84
|
Java
|
LemesVinicius/BookStore
|
/src/core/dao/CardTypeDAO.java
|
UTF-8
| 1,367
| 2.59375
| 3
|
[] |
no_license
|
package core.dao;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import core.app.DomainEntity;
import core.domain.CardType;
public class CardTypeDAO extends AbstractJdbcDAO{
public CardTypeDAO(String table, String idTable) {
super(table, idTable);
// TODO Auto-generated constructor stub
}
@Override
public void save(DomainEntity entity) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void update(DomainEntity entity) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public List<DomainEntity> read(DomainEntity entity) throws SQLException {
PreparedStatement pst=null;
openConnection();
connection.setAutoCommit(false); //Impede o auto commit no banco de dados.
StringBuilder sql = new StringBuilder();
sql.append("SELECT * FROM tbandcard");
pst = connection.prepareStatement(sql.toString(),
Statement.RETURN_GENERATED_KEYS);
ResultSet rs = pst.executeQuery();
List<DomainEntity> bcards = new ArrayList<DomainEntity>();
while(rs.next()){
CardType b = new CardType();
b.setId(rs.getInt("id"));
b.setName(rs.getString("nome"));
bcards.add(b);
}
connection.close();
return bcards;
}
}
| true
|
8f8923f73fe40fb09f8b7f53da5d31cc203bf1d6
|
Java
|
nacerfarid/GRH
|
/src/web/formations/ListeMetiersDecorator.java
|
UTF-8
| 813
| 2.46875
| 2
|
[] |
no_license
|
package web.formations;
import org.displaytag.decorator.TableDecorator;
import entities.Metier;
public class ListeMetiersDecorator extends TableDecorator {
public String getEditLink()
{
Metier metier = (Metier)this.getCurrentRowObject();
return "<a href=\"modif_metier.htm?id=" + metier.getId() + "\">" +
"<img src=\"./images/edit.png\" alt=\"Modifier le métier\"/>" +
"</a>";
}
public String getSupprLink()
{
Metier metier = (Metier)this.getCurrentRowObject();
return "<a href=\"suppr_metier.htm?id=" + metier.getId() + "\" onclick=\"javascript: return confirm('Voulez-vous supprimer ce métier?');\">" +
"<img src=\"./images/delete.png\" alt=\"Supprimer le métier\"/>" +
"</a>";
}
}
| true
|
8b4a93080be529cb8c35f8026ce2e3f9df6e1bdf
|
Java
|
Darya-Ivanova/Homework
|
/Homework/Work5/Tester.java
|
UTF-8
| 3,012
| 3.34375
| 3
|
[] |
no_license
|
public class Tester {
private String name;
private String surname;
private int expirienceInYears;
private String englishLevel;
private int salary;
public Tester() {
}
public Tester (String name) {
this.name = name;
}
public Tester (String name, String surname) {
this(name);
this.surname = surname;
}
public Tester (String name, String surname, int expirienceInYears) {
this(name, surname);
this.expirienceInYears = expirienceInYears;
}
public Tester (String name, String surname, int expirienceInYears, String englishLevel) {
this(name, surname, expirienceInYears);
this.englishLevel = englishLevel;
}
public Tester (String name, String surname, int expirienceInYears, String englishLevel, int salary) {
this(name, surname, expirienceInYears,englishLevel);
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getExpirienceInYears() {
return expirienceInYears;
}
public void setExpirienceInYears(int expirienceInYears) {
this.expirienceInYears = expirienceInYears;
}
public String getEnglishLevel() {
return englishLevel;
}
public void setEnglishLevel(String englishLevel) {
this.englishLevel = englishLevel;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public void print() {
System.out.println("Name: " + this.name + ", Surname: " + this.surname + ", Expirience in years: " +
this.expirienceInYears + ", English level: " + this.englishLevel + ", Salary: " + this.salary);
}
public void print(String name1) {
System.out.println("Name: " + name1);
}
public void print(String name1, String surname1) {
System.out.println("Name: " + name1 + ", Surname: " + surname1);
}
public void print(String name1, String surname1, int expirienceInYears1) {
System.out.println("Name: " + name1 + ", Surname: " + surname1 + ", Expirience in years: " + expirienceInYears1);
}
public void print(String name1, String surname1, int expirienceInYears1, String englishLevel1) {
System.out.println("Name: " + name1 + ", Surname: " + surname1 + ", Expirience in years: " + expirienceInYears1
+ ", English level: " + englishLevel1);
}
public void print(String name1, String surname1, int expirienceInYears1, String englishLevel1, int salary1) {
System.out.println("Name: " + name1 + ", Surname: " + surname1 + ", Expirience in years: " + expirienceInYears1
+ ", English level: " + englishLevel1 + ", Salary:" + salary1);
}
public static void printStatic (String name1, String surname1, int expirienceInYears1, String englishLevel1, int salary1) {
System.out.println("Name: " + name1 + ", Surname: " + surname1 + ", Expirience in years: " + expirienceInYears1
+ ", English level: " + englishLevel1 + ", Salary:" + salary1);
}
}
| true
|
9fd563ad2c85be8301f405a4f779b59643be2db1
|
Java
|
WJ44/ElementalChemistry
|
/src/main/java/com/wj44/echem/tileentity/TileEntityItemScanner.java
|
UTF-8
| 3,505
| 2.359375
| 2
|
[
"MIT"
] |
permissive
|
package com.wj44.echem.tileentity;
import com.wj44.echem.init.ModItems;
import com.wj44.echem.reference.Names;
import com.wj44.echem.util.APIHelper;
import com.wj44.elementscore.api.Element;
import com.wj44.elementscore.api.ElementAPI;
import com.wj44.elementscore.api.ItemProperties;
import com.wj44.elementscore.api.TooltipHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ITickable;
/**
* Created by Wesley "WJ44" Joosten on 15/01/2016.
* -
* Part of the ElementalChemistry Mod, distributed under a
* Creative Commons Attribution-NonCommercial-ShareAlike 3.0 License
* (https://creativecommons.org/licenses/by-nc-sa/3.0/)
*/
public class TileEntityItemScanner extends TileEntityEChem implements ITickable
{
public static final int INPUT_INVENTORY_INDEX = 0;
public static final int OUTPUT_INVENTORY_INDEX = 1;
public TileEntityItemScanner()
{
inventory = new ItemStack[2];
}
@Override
public void setInventorySlotContents(int index, ItemStack stack)
{
this.inventory[index] = stack;
if (stack != null && stack.stackSize > this.getInventoryStackLimit())
{
stack.stackSize = this.getInventoryStackLimit();
}
}
@Override
public boolean isItemValidForSlot(int index, ItemStack stack)
{
return index == 0;
}
@Override
public int getField(int id)
{
return 0;
}
@Override
public void setField(int id, int value)
{
}
@Override
public int getFieldCount()
{
return 0;
}
@Override
public String getName()
{
return this.hasCustomName() ? this.customName : Names.Containers.ITEM_SCANNER;
}
@Override
public void update()
{
if (inventory[INPUT_INVENTORY_INDEX] != null && inventory[OUTPUT_INVENTORY_INDEX] != null && inventory[OUTPUT_INVENTORY_INDEX].getItem() == ModItems.dataCard &! inventory[OUTPUT_INVENTORY_INDEX].getTagCompound().getBoolean("isScanned"))
{
if (ElementAPI.hasElements(inventory[INPUT_INVENTORY_INDEX]))
{
ItemStack itemStack = inventory[INPUT_INVENTORY_INDEX];
NBTTagCompound dataCard = inventory[OUTPUT_INVENTORY_INDEX].getTagCompound();
itemStack.writeToNBT(dataCard);
String contains = "Contains: ";
for (Element element : APIHelper.getElementList(itemStack).getElements())
{
int amount = APIHelper.getElementAmount(itemStack, element);
contains += amount + " " + element.symbol + ", ";
}
contains = contains.substring(0, contains.length()-2);
ItemProperties properties = APIHelper.getProperties(itemStack);
dataCard.setString("item", itemStack.getDisplayName());
dataCard.setString("elements", contains);
dataCard.setString("formula", TooltipHelper.getFormulaFromItemStack(itemStack));
dataCard.setInteger("density", properties.density);
dataCard.setFloat("volume", properties.volume);
dataCard.setInteger("mass", properties.mass);
dataCard.setBoolean("isScanned", true);
isActive = true;
}
else isActive = false;
}
}
@Override
public int getInventoryStackLimit()
{
return 1;
}
}
| true
|
5e1a9217bee44fdc822a384977ce08e10a873b96
|
Java
|
AdrianN17/PruebaWebserviceAndroid
|
/app/src/main/java/com/example/main/MainActivity.java
|
UTF-8
| 6,114
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
package com.example.main;
import androidx.appcompat.app.AppCompatActivity;
import androidx.arch.core.util.Function;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.conf.configuracion;
import com.example.extra.jwtCreador;
import com.example.extra.postRequest;
import com.example.extra.validador;
import com.example.modelo.objetoValidador;
import com.example.modelo.usuario;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import net.danlew.android.joda.JodaTimeAndroid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
public class MainActivity extends AppCompatActivity {
validador val;
jwtCreador jwtcreador;
protected TextView txtUsuario,txtContrasena;
protected Button btnLogin;
private String url = "WebserviceAndroidJWT/public/login.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
val = new validador();
JodaTimeAndroid.init(this);
txtUsuario = (TextView)findViewById(R.id.txtUsuario);
txtContrasena = (TextView)findViewById(R.id.txtContrasena);
btnLogin = (Button)findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
objetoValidador[] arrayValidador = new objetoValidador[]{
new objetoValidador("user", txtUsuario, String.class),
new objetoValidador("pass", txtContrasena, String.class)
};
Map mapa= val.validateTextView(arrayValidador);
if(!mapa.isEmpty())
{
DateTime iat = new DateTime();
DateTime ex = iat.plusMinutes(5);
DateTime nbf = iat.minusMinutes(1);
String jwtString = jwtCreador.crearJwt(configuracion.KEY_DEFAULT,iat,nbf,ex,"Login",mapa);
HashMap<String, String> params = new HashMap<>();
params.put("Authorization", jwtString);
postRequest post = new postRequest(MainActivity.this,url,params);
post.consulta(
new Function<String,Void>() {
@Override
public Void apply(String response)
{
if(!TextUtils.isEmpty(response))
{
JSONObject json = null;
try
{
json = new JSONObject(response);
try
{
String jwt = json.getString("Authorization");
String JsonString = jwtCreador.extraerJwt(jwt,configuracion.KEY_DEFAULT);
if(!TextUtils.isEmpty(JsonString))
{
Gson gson = new Gson();
usuario[] usuArray = gson.fromJson(JsonString, usuario[].class);
System.out.println(usuArray[0].getUser());
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
}
return null;
}
}
);
}
}
});
}
/*public void CrearJWT(String user,String pass)
{*/
/*byte[] secret = Base64.getDecoder().decode("pG1VvOtDZMtZAylyM+k62Ut1AxQWFUmodq0hj9+TGBs=");*/
//Key key = Keys.hmacShaKeyFor(secret);
//Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
/*DateTime at = new DateTime();
DateTime ex = new DateTime();
ex = ex.plusMinutes(5);
String jwt = Jwts.builder()
.setSubject("Brian Demers")
.setAudience("video demo")
.claim("Usuario", user)
.claim("Contrasena", pass)
.setIssuedAt(at.toDate())
.setExpiration(ex.toDate())
.signWith(Keys.hmacShaKeyFor(secret))
.compact();*/
//System.out.println(jwt);
/*Instant now = Instant.now();
byte[] secret = Base64.getDecoder().decode("o4OdCNjd8mmDN2+/nfHdIB2ZWta80foXqDx2rouL4nw=");
String jwt = Jwts.builder()
.setSubject("Brian Demers")
.setAudience("video demo")
.claim("1d20", new Random().nextInt(20) +1)
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(now.plus(100, ChronoUnit.MINUTES)))
.signWith(Keys.hmacShaKeyFor(secret))
.compact();
System.out.println(jwt);
Jwts<Claims> result = Jwts.parserBuilder()
.setSigningKey(Keys.hmacShaKeyFor(secret))
.build()
.parseClaimsJws(jwt);
System.out.println(result);
System.out.println("1d20: "+ result.getBody().get("1d20", Integer.class));*/
//}
}
| true
|
f2d94711010918a7ae8c4c7ea5c36f616e72b3e8
|
Java
|
VietHoang24/learn_java_core
|
/DevPro_Java38_Core/Example/src/learningJV/Unit8/QuanLyBanHang/Process/Output/XuatHang.java
|
UTF-8
| 1,352
| 2.734375
| 3
|
[] |
no_license
|
package learningJV.Unit8.QuanLyBanHang.Process.Output;
import learningJV.Unit8.QuanLyBanHang.Process.Input.NhapKhachHang;
public class XuatHang extends NhapKhachHang {
public static void tieuDe(){
System.out.printf("%20s%20s%20s%20s%n", "ID", "Ten Hang", "So Luong", "Don Gia");
}
public static void xuatHang(int i, int j, int k){
for (int l=0; l<khachHangs.get(i).getGioHangs().get(j).getLoaiHangs().get(k).getHangs().size(); l++){
System.out.printf("%20s%20s%20d%20.1f%n",
khachHangs.get(i).getGioHangs().get(j).getLoaiHangs().get(k).getHangs().get(l).getId(),
khachHangs.get(i).getGioHangs().get(j).getLoaiHangs().get(k).getHangs().get(l).getTenHang(),
khachHangs.get(i).getGioHangs().get(j).getLoaiHangs().get(k).getHangs().get(l).getSoLuong(),
khachHangs.get(i).getGioHangs().get(j).getLoaiHangs().get(k).getHangs().get(l).getDonGia());
}
}
public static void hienThiDsHang(){
tieuDe();
for (int i=0; i<khachHangs.size(); i++){
for (int j=0; j<khachHangs.get(i).getGioHangs().size(); j++){
for (int k=0; k<khachHangs.get(i).getGioHangs().get(j).getLoaiHangs().size(); k++){
xuatHang(i, j, k);
}
}
}
}
}
| true
|
78e8ee2a909297b05fe0be0fb79cd8fd415bde9e
|
Java
|
SunRisingChang/DHEE_StudentInforMgr_OAS
|
/src/com/dhee/tools/POI_TeacherEva.java
|
UTF-8
| 8,104
| 2.421875
| 2
|
[] |
no_license
|
package com.dhee.tools;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.struts2.ServletActionContext;
import com.dhee.vo.TeacherEva;
public class POI_TeacherEva {
public HSSFWorkbook getExcel(TeacherEva t) {
TeacherEva te = t;
// 获得excel模板的路径
String sourceFilePath = ServletActionContext.getServletContext().getRealPath("/EXL") + "\\TeacherEva.xls";
// 文件链接器
POIFSFileSystem fs;
// exl工作bo
HSSFWorkbook wb = null;
try {
fs = new POIFSFileSystem(new FileInputStream(sourceFilePath));
wb = new HSSFWorkbook(fs);
// 获得exl表
HSSFSheet sheet = wb.getSheetAt(0);
// 设置第二行第一个单元格的值
HSSFRow row = sheet.getRow(1);
HSSFCell cell = row.getCell(0);
cell.setCellValue(te.getStudent());
// 设置第二行第二个单元的值
row = sheet.getRow(1);
cell = row.getCell(1);
cell.setCellValue("班级:" + te.getClasses() + " 培训讲师:" + te.getTeacher() + " 课程:" + te.getCourse());
// 设置第二行第三个单元的值
row = sheet.getRow(1);
cell = row.getCell(2);
cell.setCellValue("总分:" + te.getSumCore());
// 设置第二行第三个单元的值
row = sheet.getRow(1);
cell = row.getCell(3);
cell.setCellValue("日期:" + te.getDate());
// 进行数据处理
String[] a1 = te.getPerQuality().split("#src#");
String[] a11 = te.getPerQualityActual().split("#src#");
String[] a2 = te.getTeachAttitude().split("#src#");
String[] a22 = te.getTeachAttitudeActual().split("#src#");
String[] a3 = te.getTeachLevel().split("#src#");
String[] a33 = te.getTeachLevelActual().split("#src#");
// 设置分值
row = sheet.getRow(3);
cell = row.getCell(2);
cell.setCellValue(a1[0]);
// 设置实际情况
row = sheet.getRow(3);
cell = row.getCell(3);
cell.setCellValue(a11[0]);
int bIndustryLength = a11[0].length();
int bIndustryHeigth = 1;
if (bIndustryLength > 3) {
bIndustryHeigth = bIndustryLength / 3;
if ((bIndustryLength % 3) != 0) {
bIndustryHeigth++;
}
}
// 设置分值
row = sheet.getRow(4);
cell = row.getCell(2);
cell.setCellValue(a1[1]);
// 设置实际情况
row = sheet.getRow(4);
cell = row.getCell(3);
cell.setCellValue(a11[1]);
int cIndustryLength = a11[1].length();
int cIndustryHeigth = 1;
if (cIndustryLength > 3) {
cIndustryHeigth = cIndustryLength / 3;
if ((cIndustryLength % 3) != 0) {
cIndustryHeigth++;
}
}
// 设置分值
row = sheet.getRow(5);
cell = row.getCell(2);
cell.setCellValue(a1[2]);
// 设置实际情况
row = sheet.getRow(5);
cell = row.getCell(3);
cell.setCellValue(a11[2]);
int dIndustryLength = te.getPerQualityActual().length();
int dIndustryHeigth = 1;
if (cIndustryLength > 3) {
dIndustryHeigth = dIndustryLength / 3;
if ((dIndustryLength % 3) != 0) {
dIndustryHeigth++;
}
}
// 设置分值
row = sheet.getRow(6);
cell = row.getCell(2);
cell.setCellValue(a2[0]);
// 设置实际情况
row = sheet.getRow(6);
cell = row.getCell(3);
cell.setCellValue(a22[0]);
int eIndustryLength = a22[0].length();
int eIndustryHeigth = 1;
if (eIndustryLength > 3) {
eIndustryHeigth = eIndustryLength / 3;
if ((eIndustryLength % 3) != 0) {
eIndustryHeigth++;
}
}
// 设置分值
row = sheet.getRow(7);
cell = row.getCell(2);
cell.setCellValue(a2[1]);
// 设置实际情况
row = sheet.getRow(7);
cell = row.getCell(3);
cell.setCellValue(a22[1]);
int fIndustryLength = a22[1].length();
int fIndustryHeigth = 1;
if (fIndustryLength > 3) {
fIndustryHeigth = eIndustryLength / 3;
if ((fIndustryLength % 3) != 0) {
fIndustryHeigth++;
}
}
// 设置分值
row = sheet.getRow(8);
cell = row.getCell(2);
cell.setCellValue(a2[2]);
// 设置实际情况
row = sheet.getRow(8);
cell = row.getCell(3);
cell.setCellValue(a22[2]);
// 设置分值
row = sheet.getRow(9);
cell = row.getCell(2);
cell.setCellValue(a2[3]);
// 设置实际情况
row = sheet.getRow(9);
cell = row.getCell(3);
cell.setCellValue(a22[3]);
// 设置分值
row = sheet.getRow(10);
cell = row.getCell(2);
cell.setCellValue(a2[4]);
// 设置实际情况
row = sheet.getRow(10);
cell = row.getCell(3);
cell.setCellValue(a22[4]);
// 设置分值
row = sheet.getRow(11);
cell = row.getCell(2);
cell.setCellValue(a2[5]);
// 设置实际情况
row = sheet.getRow(11);
cell = row.getCell(3);
cell.setCellValue(a22[5]);
// 设置分值
row = sheet.getRow(12);
cell = row.getCell(2);
cell.setCellValue(a2[6]);
// 设置实际情况
row = sheet.getRow(12);
cell = row.getCell(3);
cell.setCellValue(a22[6]);
// 设置分值
row = sheet.getRow(13);
cell = row.getCell(2);
cell.setCellValue(a2[7]);
// 设置实际情况
row = sheet.getRow(13);
cell = row.getCell(3);
cell.setCellValue(a22[7]);
// 设置分值
row = sheet.getRow(14);
cell = row.getCell(2);
cell.setCellValue(a3[0]);
// 设置实际情况
row = sheet.getRow(14);
cell = row.getCell(3);
cell.setCellValue(a33[0]);
// 设置分值
row = sheet.getRow(15);
cell = row.getCell(2);
cell.setCellValue(a3[1]);
// 设置实际情况
row = sheet.getRow(15);
cell = row.getCell(3);
cell.setCellValue(a33[1]);
// 设置分值
row = sheet.getRow(16);
cell = row.getCell(2);
cell.setCellValue(a3[2]);
// 设置实际情况
row = sheet.getRow(16);
cell = row.getCell(3);
cell.setCellValue(a33[2]);
// 设置分值
row = sheet.getRow(17);
cell = row.getCell(2);
cell.setCellValue(a3[3]);
// 设置实际情况
row = sheet.getRow(17);
cell = row.getCell(3);
cell.setCellValue(a33[3]);
// 设置分值
row = sheet.getRow(18);
cell = row.getCell(2);
cell.setCellValue(a3[4]);
// 设置实际情况
row = sheet.getRow(18);
cell = row.getCell(3);
cell.setCellValue(a33[4]);
// 设置分值
row = sheet.getRow(19);
cell = row.getCell(2);
cell.setCellValue(a3[5]);
// 设置实际情况
row = sheet.getRow(19);
cell = row.getCell(3);
cell.setCellValue(a33[5]);
// 设置意见和建议
row = sheet.getRow(22);
cell = row.getCell(0);
cell.setCellValue(te.getIdea1());
// 设置意见和建议
row = sheet.getRow(25);
cell = row.getCell(0);
cell.setCellValue(te.getIdea2());
// 设置意见和建议
row = sheet.getRow(28);
cell = row.getCell(0);
cell.setCellValue(te.getIdea3());
// 设置后勤支持
row = sheet.getRow(30);
cell = row.getCell(0);
cell.setCellValue("1.教师环境及设备时候合适:" + te.getLogistics1());
// 设置后勤支持
row = sheet.getRow(31);
cell = row.getCell(0);
cell.setCellValue("2.电脑维护及问题解决是否及时充分:" + te.getLogistics2());
// 设置后勤支持
row = sheet.getRow(32);
cell = row.getCell(0);
cell.setCellValue("3.获得课程信息是否及时:" + te.getLogistics3());
// 设置后勤支持
row = sheet.getRow(33);
cell = row.getCell(0);
cell.setCellValue("4.培训中心沟通反馈是否流畅:" + te.getLogistics4());
// 设置行高
int[] h = { bIndustryHeigth, cIndustryHeigth, dIndustryHeigth, eIndustryHeigth, fIndustryHeigth };
Arrays.sort(h);
float height = 15.00f;
row.setHeightInPoints(height * h[4]);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return wb;
}
}
| true
|
bc9dc8c1fac8a99e46f6a1cb5538ae6e1d28aaaf
|
Java
|
usfalami/gwt-extra
|
/src/main/java/com/gwt/extra/client/demo/tools/Code.java
|
UTF-8
| 847
| 2.59375
| 3
|
[] |
no_license
|
package com.gwt.extra.client.demo.tools;
import com.google.gwt.dom.client.Document;
import com.google.gwt.user.client.ui.HasHTML;
import com.google.gwt.user.client.ui.Widget;
import com.gwt.extra.client.demo.tools.CodeFormater.Languages;
public class Code extends Widget implements HasHTML {
protected Languages lang;
public Code(Languages lang) {
this.lang = lang;
setElement(Document.get().createPreElement());
getElement().setClassName("brush:" + lang.name().toLowerCase() + ';');
}
@Override
public String getHTML() {
return getElement().getInnerText();
}
@Override
public void setHTML(String html) {
getElement().setInnerText(lang.format(html));
}
@Override
public String getText() {
return getElement().getInnerText();
}
@Override
public void setText(String text) {
getElement().setInnerText(text);
}
}
| true
|
5944616849237bccc2619c7cde54585415c34b94
|
Java
|
migueltenezaca/pft-ws
|
/src/main/java/edu/utpl/pft/entity/PftPlanificacion.java
|
UTF-8
| 3,607
| 1.90625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.utpl.pft.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author Miguel Tenezaca
*/
@Entity
@Table(name = "pft_planificacion")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "PftPlanificacion.findAll", query = "SELECT p FROM PftPlanificacion p"),
@NamedQuery(name = "PftPlanificacion.findByPlaId", query = "SELECT p FROM PftPlanificacion p WHERE p.plaId = :plaId")})
public class PftPlanificacion implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "pla_id")
private Integer plaId;
@Lob
@Column(name = "pla_cronograma")
private byte[] plaCronograma;
@JoinColumn(name = "pla_id_proyecto", referencedColumnName = "pro_id")
@ManyToOne
private PftProyecto plaIdProyecto;
@OneToMany(mappedBy = "plaEnIdPlanificacion")
private List<PftPlanificacionEntregable> pftPlanificacionEntregableList;
public PftPlanificacion() {
}
public PftPlanificacion(Integer plaId) {
this.plaId = plaId;
}
public Integer getPlaId() {
return plaId;
}
public void setPlaId(Integer plaId) {
this.plaId = plaId;
}
public byte[] getPlaCronograma() {
return plaCronograma;
}
public void setPlaCronograma(byte[] plaCronograma) {
this.plaCronograma = plaCronograma;
}
public PftProyecto getPlaIdProyecto() {
return plaIdProyecto;
}
public void setPlaIdProyecto(PftProyecto plaIdProyecto) {
this.plaIdProyecto = plaIdProyecto;
}
@XmlTransient
public List<PftPlanificacionEntregable> getPftPlanificacionEntregableList() {
return pftPlanificacionEntregableList;
}
public void setPftPlanificacionEntregableList(List<PftPlanificacionEntregable> pftPlanificacionEntregableList) {
this.pftPlanificacionEntregableList = pftPlanificacionEntregableList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (plaId != null ? plaId.hashCode() : 0);
return hash;
}
@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 PftPlanificacion)) {
return false;
}
PftPlanificacion other = (PftPlanificacion) object;
if ((this.plaId == null && other.plaId != null) || (this.plaId != null && !this.plaId.equals(other.plaId))) {
return false;
}
return true;
}
@Override
public String toString() {
return "edu.utpl.pft.entity.PftPlanificacion[ plaId=" + plaId + " ]";
}
}
| true
|
ebc49de8eeb17a9447e2101c93c237088ac2308d
|
Java
|
oleg-rakitin/JavaRushTasks
|
/1.JavaSyntax/src/com/javarush/task/task08/task0828/Solution.java
|
UTF-8
| 387
| 2.140625
| 2
|
[] |
no_license
|
package com.javarush.task.task08.task0828;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/*
Номер месяца
*/
public class Solution {
public static void main(String[] args) throws IOException {
//напишите тут ваш код
Map<String, Integer> map = new HashMap<>();
}
}
| true
|
e49c78b9e85ff0826f502b59f71a07fefa550506
|
Java
|
moutainhigh/spring-assistant-component
|
/spring-assistant-component-util/src/main/java/com/github/jiahaowen/spring/assistant/component/util/diff/internal/linewriter/IterableLineWriter.java
|
UTF-8
| 4,054
| 2.5625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.github.jiahaowen.spring.assistant.component.util.diff.internal.linewriter;
import com.github.jiahaowen.spring.assistant.component.util.diff.algorithm.impl.MyersDiff;
import com.github.jiahaowen.spring.assistant.component.util.diff.differ.CompareResult;
import com.github.jiahaowen.spring.assistant.component.util.diff.exception.DiffException;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
import org.springframework.util.CollectionUtils;
/**
* Iterable类型序列化类
*
* @author jiahaowen.jhw
* @version $Id: IterableLineWriter.java, v 0.1 2016-10-30 下午9:41 jiahaowen.jhw Exp $
*/
public class IterableLineWriter extends TypeSafeCheckableLineWriter<Iterable<Object>> {
private static final MyersDiff myersDiff = new MyersDiff();
/** 内部序列化类 */
private final LineWriter lineWriter;
/** 构造函数 */
public IterableLineWriter(final LineWriter lineWriter) {
this.lineWriter = lineWriter;
}
/**
* @param path 路径描述了给定的对象在对象图中的位置.
* @param iterable
* @return
* @throws DiffException
*/
@Override
public List<String> typeSafeWrite(final String path, final Iterable<Object> iterable)
throws DiffException {
final List<String> lines = Lists.newArrayList();
if (!Iterables.isEmpty(iterable)) {
for (final Object nestedProperty : iterable) {
lines.addAll(lineWriter.write(path, nestedProperty));
}
}
return lines;
}
/**
* @param value
* @return
*/
@Override
public boolean applies(final Object value) {
return value instanceof Iterable;
}
/**
* @param path
* @param base
* @param working
* @return
* @throws DiffException
*/
@Override
public List<CompareResult> typeSafeWrite(
final String path, final Iterable<Object> base, final Iterable<Object> working)
throws DiffException {
if (Iterables.size(base) == 0 && Iterables.size(working) == 0) {
return Lists.newArrayList();
}
if (Iterables.size(base) != Iterables.size(working)) {
return Lists.newArrayList(
new CompareResult(
Lists.newArrayList("路径:" + path + "下对象的size为" + Iterables.size(base)),
Lists.newArrayList(
"路径:" + path + "下对象的size为" + Iterables.size(working))));
}
if (!Iterables.isEmpty(base) && !Iterables.isEmpty(working)) {
// 对理想的顺序场景,单次循环即可完成
// 对存在乱序的场景,性能可能会比较耗时
int index = 0;
for (final Object baseProperty : base) {
boolean isEqual = false;
ArrayList<CompareResult> results = Lists.newArrayList();
for (final Object workingProperty : working) {
final String extendedPath =
PathBuilder.extendPathWithIterableIndex(path, index);
List<CompareResult> result =
lineWriter.write(extendedPath, baseProperty, workingProperty);
if (CollectionUtils.isEmpty(result)) {
isEqual = true;
break;
}
results.addAll(result);
}
if (!isEqual) {
/*return Lists
.newArrayList(new CompareResult(
Lists.newArrayList(
"路径:" + path + "下的Iterable类型属性存在不同:" + baseProperty.toString()),
null));*/
return results;
}
index++;
}
}
return Lists.newArrayList();
}
}
| true
|
0b8e21d55bf9296d638d1032f29d3765b1abde68
|
Java
|
kiichi7/WorkFiles
|
/repos/mms-diy-unicom/mms-cms/src/main/java/com/unicom/mms/cms/service/PhotoFrameService.java
|
UTF-8
| 1,000
| 1.617188
| 2
|
[] |
no_license
|
package com.unicom.mms.cms.service;
import java.util.Map;
import com.unicom.mms.common.Page;
import com.unicom.mms.entity.TbFramePos;
import com.unicom.mms.entity.TbPhotoFrame;
public interface PhotoFrameService extends CommonService<TbPhotoFrame>{
public Page<TbPhotoFrame> findByPage(TbPhotoFrame entity,
Page<TbPhotoFrame> pageInfo);
/**
*
* 方法用途和描述: 新增相框
* @param model
* @param map
* @author lujia 新增日期:2013-4-11
* @since mms-cms
*/
public void savePhotoFrame(TbPhotoFrame model, Map<String, Object> map);
/**
*
* 方法用途和描述: 修改相框
* @param model
* @author chenliang 新增日期:2013-6-19
* @since mms-cms
*/
public void updatePhotoFrame(TbPhotoFrame model,TbFramePos framePos,TbFramePos postmarkFramePos,TbFramePos stampFramePos);
/**
*
* 方法用途和描述: 批量删除
* @param ids
* @author chenliang 新增日期:2013-7-15
* @since mms-cms
*/
public void deleteByPkid(String[] ids);
}
| true
|
fc3fc5641059563593aaec0a2eb7019a76c5f63b
|
Java
|
SunnyNiu/leave-management
|
/test/test/org/niu/leaves/jsp/servlet/dao/MockLoginDao.java
|
UTF-8
| 512
| 2.296875
| 2
|
[] |
no_license
|
package test.org.niu.leaves.jsp.servlet.dao;
import org.niu.leaves.jsp.servlet.dao.LoginDao;
import java.sql.SQLException;
/**
* Created by Sunny on 10/04/2017.
*/
public class MockLoginDao implements LoginDao {
public String getPassword(String login) throws SQLException {
if(login.equals("SunnyN")){
return "Sun123";
}else if(login.equals("John")){
return "Joh123";
}else{
throw new SQLException("password not found");
}
}
}
| true
|
2b3de37582c8a574990a669caa615ccdd4fc2b38
|
Java
|
SShopik/Calculator
|
/src/ui/Calculator.java
|
UTF-8
| 2,966
| 3
| 3
|
[] |
no_license
|
package ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import engine.CalculatorEngine;
import enums.Button;;
public class Calculator
{
public static final String DISPLAY_FIELD_COMPONENT_NAME = "North";
public static final String BUTTONS_COMPONENT_NAME = "Center";
public static final String FRAME_NAME = "Calculator";
JPanel window;
private JTextField displayField;
JPanel buttons;
//set value on display
public void setDisplayField(String value)
{
displayField.setText (value);
}//get value from display
public String getDisplayField()
{
return displayField.getText();
}
public Calculator()
{
window = new JPanel();
BorderLayout borderLayout = new BorderLayout();
window.setLayout (borderLayout);
displayField = new JTextField(20);
displayField.setFont ( new Font("SansSerif", Font.BOLD, 16));
window.add (DISPLAY_FIELD_COMPONENT_NAME , displayField);
buttons = new JPanel();
GridLayout gridLayout = new GridLayout(5,4);
buttons.setLayout(gridLayout);
//sending instance of Calculator to CalculatorEngine
CalculatorEngine listener = new CalculatorEngine(this);
//adding buttons
addButtons(listener);
window.add (BUTTONS_COMPONENT_NAME , buttons);
JFrame frame = new JFrame(FRAME_NAME);
frame.setContentPane(window);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize ( new Dimension(250, 170));
frame.setMinimumSize ( new Dimension(250, 170));
frame.pack();
frame.setVisible(true);
}
//method for making and adding button to the panel
private void addButton (String label , CalculatorEngine listener)
{
JButton button = new JButton(label);
button.addActionListener(listener);
buttons.add(button);
}
//method for adding buttons
private void addButtons (CalculatorEngine listener)
{
addButton(Button.BACKSPACE.getValue() , listener);
addButton(Button.BRACKET_OPEN.getValue() , listener);
addButton(Button.BRACKET_CLOSE.getValue() , listener);
addButton(Button.POWER.getValue() , listener);
addButton(Button.SEVEN.getValue() , listener);
addButton(Button.EIGHT.getValue() , listener);
addButton(Button.NINE.getValue() , listener);
addButton(Button.DIVIDE.getValue() , listener);
addButton(Button.FOUR.getValue() , listener);
addButton(Button.FIVE.getValue() , listener);
addButton(Button.SIX.getValue() , listener);
addButton(Button.MULTIPLY.getValue() , listener);
addButton(Button.ONE.getValue() , listener);
addButton(Button.TWO.getValue() , listener);
addButton(Button.THREE.getValue() , listener);
addButton(Button.PLUS.getValue() , listener);
addButton(Button.ZERO.getValue() , listener);
addButton(Button.DOT.getValue() , listener);
addButton(Button.EQUAL.getValue() , listener);
addButton(Button.MINUS.getValue() , listener);
}
}
| true
|
0a989b7338d1d80f5ea6bf9fbd37e308670166b3
|
Java
|
azsx0020/leetcodePractice
|
/src/main/java/com/adohong/leetcode/practice/integertoroman/Solution.java
|
UTF-8
| 1,265
| 3.671875
| 4
|
[] |
no_license
|
package com.adohong.leetcode.practice.integertoroman;
import java.util.LinkedHashMap;
import java.util.Map;
public class Solution {
public String intToRoman(int num) {
String result = "";
Map<String, Integer> romanIntegerMap = new LinkedHashMap<>();
romanIntegerMap.put("M", 1000);
romanIntegerMap.put("CM", 900);
romanIntegerMap.put("D", 500);
romanIntegerMap.put("CD", 400);
romanIntegerMap.put("C", 100);
romanIntegerMap.put("XC", 90);
romanIntegerMap.put("L", 50);
romanIntegerMap.put("XL", 40);
romanIntegerMap.put("X", 10);
romanIntegerMap.put("IX", 9);
romanIntegerMap.put("V", 5);
romanIntegerMap.put("IV", 4);
romanIntegerMap.put("I", 1);
for (Map.Entry entry : romanIntegerMap.entrySet()) {
int count = (num / (int)entry.getValue());
for (int i = 0; i < count; i++) {
result += entry.getKey();
}
num = num % (int)entry.getValue();
}
return result;
}
public static void main(String[] args) {
Solution solution = new Solution();
String result = solution.intToRoman(1994);
System.out.println(result);
}
}
| true
|
ecd3045b8ef4becdf36a50e8ab4404783ef4a2b5
|
Java
|
xdbas/moshi-jsonapi
|
/core/src/main/java/moe/banana/jsonapi2/ResourceIdentifier.java
|
UTF-8
| 3,862
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package moe.banana.jsonapi2;
import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter;
import com.squareup.moshi.Moshi;
import java.io.IOException;
import java.io.Serializable;
import static moe.banana.jsonapi2.MoshiHelper.*;
public class ResourceIdentifier implements Serializable {
private Document document;
private String type;
public String id;
private JsonBuffer meta;
public ResourceIdentifier() {
//this(null, null);
}
public ResourceIdentifier(ResourceIdentifier identifier) {
this(identifier.getType(), identifier.getId());
}
public ResourceIdentifier(String type, String id) {
this.type = type;
this.id = id;
}
@Deprecated
public Document getContext() {
return getDocument();
}
@Deprecated
public void setContext(Document document) {
setDocument(document);
}
public Document getDocument() {
return document;
}
public void setDocument(Document document) {
this.document = document;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public JsonBuffer getMeta() {
return meta;
}
public void setMeta(JsonBuffer meta) {
this.meta = meta;
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"type='" + type + '\'' +
", id='" + id + '\'' +
'}';
}
@SuppressWarnings("SimplifiableIfStatement")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !getClass().equals(o.getClass())) return false;
ResourceIdentifier that = (ResourceIdentifier) o;
if (type != null ? !type.equals(that.type) : that.type != null) return false;
return id != null ? id.equals(that.id) : that.id == null;
}
@Override
public int hashCode() {
int result = type != null ? type.hashCode() : 0;
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
public static class Adapter extends JsonAdapter<ResourceIdentifier> {
JsonAdapter<JsonBuffer> jsonBufferJsonAdapter;
public Adapter(Moshi moshi) {
jsonBufferJsonAdapter = moshi.adapter(JsonBuffer.class);
}
@Override
public ResourceIdentifier fromJson(JsonReader reader) throws IOException {
ResourceIdentifier object = new ResourceIdentifier();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case "id":
object.setId(nextNullableString(reader));
break;
case "type":
object.setType(nextNullableString(reader));
break;
case "meta":
object.setMeta(nextNullableObject(reader, jsonBufferJsonAdapter));
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return object;
}
@Override
public void toJson(JsonWriter writer, ResourceIdentifier value) throws IOException {
writer.beginObject();
writer.name("type").value(value.getType());
writer.name("id").value(value.getId());
writeNullable(writer, jsonBufferJsonAdapter, "meta", value.getMeta());
writer.endObject();
}
}
}
| true
|
efdbb0015df3ac49fdc99b1182cbeab31805b75e
|
Java
|
pastema/java_spring_data_jpa_practice-2019-10-15-7-53-55-688
|
/src/main/java/com/tw/apistackbase/service/CompanyService.java
|
UTF-8
| 1,458
| 2.28125
| 2
|
[] |
no_license
|
package com.tw.apistackbase.service;
import com.tw.apistackbase.core.Company;
import com.tw.apistackbase.repository.CompanyRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import static java.util.Objects.isNull;
import static org.springframework.data.domain.PageRequest.of;
@Service
public class CompanyService {
@Autowired
private CompanyRepository companyRepository;
public Iterable<Company> findAll() {
return companyRepository.findAll();
}
public Iterable<Company> findAllWithPageRequest(int page, int size) {
return companyRepository.findAll(of(page, size));
}
public Company findByNameContaining(String name) {
return companyRepository.findByNameContaining(name);
}
public Company save(Company company) {
return companyRepository.save(company);
}
public Company update(String name, Long id) {
Company company = findById(id);
if (!isNull(company)) {
company.setName(name);
companyRepository.save(company);
}
return company;
}
public Company deleteById(Long id) {
Company company = findById(id);
if (!isNull(company)) {
companyRepository.deleteById(id);
}
return company;
}
private Company findById(Long id) {
return companyRepository.findById(id).orElse(null);
}
}
| true
|
ca17a9095610d03f0d09c56dbfec0be4885a49ac
|
Java
|
waitme8888/spring-boot-web
|
/src/main/java/com/waitme/jpa/controller/TemplateController.java
|
UTF-8
| 1,007
| 2.28125
| 2
|
[] |
no_license
|
package com.waitme.jpa.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@Controller
public class TemplateController {
// /**
// * 返回html模板.
// */
// @RequestMapping("/hello")
// public String helloHtml(Map<String,Object> map){
// map.put("hello","from TemplateControllerqqq.helloHtml");
// return "hello";
// }
// /**
// * 返回html模板.
// */
// @RequestMapping("/helloFtl")
// public String helloFtl(Map<String,Object> map){
// map.put("hello","from TemplateController.helloFtl");
// return"/helloFtl";
// }
@RequestMapping("/hello/jsp")
public String helloHtml(Map<String, Object> map) {
map.put("hello", "from TemplateControllerqqq.helloHtml");
System.out.println("jsp");
throw new RuntimeException("运行异常!");
// return "helloJsp";
}
}
| true
|
c31742935f217cae0f3aaf20bc362dbb6a18c30d
|
Java
|
zxiter/JGenerator
|
/src/main/java/org/jiuwo/generator/model/Table.java
|
UTF-8
| 735
| 2.3125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.jiuwo.generator.model;
/**
* 表实体
*
* @author junhan
*/
public class Table {
/**
* 表名
*/
private String name;
/**
* 程序用表名
*/
private String proName;
/**
* 描述
*/
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
}
| true
|
a989747530aa7db2c10fb97a38429142bcc47492
|
Java
|
tkushmyruk/e-Agency-Servlet
|
/src/main/java/ua/taras/kushmyruk/command/LogoutCommand.java
|
UTF-8
| 879
| 2.140625
| 2
|
[] |
no_license
|
package ua.taras.kushmyruk.command;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import ua.taras.kushmyruk.exception.AppException;
import ua.taras.kushmyruk.service.UserService;
import ua.taras.kushmyruk.util.LoggerMessage;
import ua.taras.kushmyruk.util.Pages;
import ua.taras.kushmyruk.util.Parameters;
public class LogoutCommand implements Command {
private static final Logger LOGGER = Logger.getLogger(LogoutCommand.class);
private final UserService userService;
public LogoutCommand(UserService userService) {
this.userService = userService;
}
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws AppException {
LOGGER.info(LoggerMessage.USER_LOGOUT);
userService.logoutUser(request);
return Pages.INDEX_PAGE;
}
}
| true
|
1897c0ae98433ed40f44e641e44d1e35719faac1
|
Java
|
clilystudio/NetBook
|
/allsrc/android/support/v4/media/session/MediaControllerCompatApi21$TransportControls.java
|
UTF-8
| 2,389
| 1.65625
| 2
|
[
"Unlicense"
] |
permissive
|
package android.support.v4.media.session;
import android.media.Rating;
import android.media.session.MediaController.TransportControls;
import android.os.Bundle;
public class MediaControllerCompatApi21$TransportControls
{
public static void fastForward(Object paramObject)
{
((MediaController.TransportControls)paramObject).fastForward();
}
public static void pause(Object paramObject)
{
((MediaController.TransportControls)paramObject).pause();
}
public static void play(Object paramObject)
{
((MediaController.TransportControls)paramObject).play();
}
public static void playFromMediaId(Object paramObject, String paramString, Bundle paramBundle)
{
((MediaController.TransportControls)paramObject).playFromMediaId(paramString, paramBundle);
}
public static void playFromSearch(Object paramObject, String paramString, Bundle paramBundle)
{
((MediaController.TransportControls)paramObject).playFromSearch(paramString, paramBundle);
}
public static void rewind(Object paramObject)
{
((MediaController.TransportControls)paramObject).rewind();
}
public static void seekTo(Object paramObject, long paramLong)
{
((MediaController.TransportControls)paramObject).seekTo(paramLong);
}
public static void sendCustomAction(Object paramObject, String paramString, Bundle paramBundle)
{
((MediaController.TransportControls)paramObject).sendCustomAction(paramString, paramBundle);
}
public static void setRating(Object paramObject1, Object paramObject2)
{
((MediaController.TransportControls)paramObject1).setRating((Rating)paramObject2);
}
public static void skipToNext(Object paramObject)
{
((MediaController.TransportControls)paramObject).skipToNext();
}
public static void skipToPrevious(Object paramObject)
{
((MediaController.TransportControls)paramObject).skipToPrevious();
}
public static void skipToQueueItem(Object paramObject, long paramLong)
{
((MediaController.TransportControls)paramObject).skipToQueueItem(paramLong);
}
public static void stop(Object paramObject)
{
((MediaController.TransportControls)paramObject).stop();
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v4.media.session.MediaControllerCompatApi21.TransportControls
* JD-Core Version: 0.6.0
*/
| true
|
d060cca70c62e2aabdb44e1db634d41ebfc1d3f9
|
Java
|
sirajtk/KaiserSentinal
|
/app/src/main/java/com/example/kaisersentinel/pagination/PaginationLayout.java
|
UTF-8
| 4,598
| 2.859375
| 3
|
[] |
no_license
|
package com.example.kaisersentinel.pagination;
import android.content.Context;
import android.graphics.Color;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
public class PaginationLayout extends LinearLayout {
private int mPageActive = 0;
private HorizontalScrollView mScroll;
private LinearLayout mBar;
public PaginationLayout(Context context) {
super(context);
setOrientation(LinearLayout.VERTICAL);
// creates the class that will control the gestures and apply it in the
// scroll
final GestureDetector mGestureDetector = new GestureDetector(new MySimpleOnGestureListener());
mScroll = new HorizontalScrollView(context);
mScroll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mScroll.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (mGestureDetector.onTouchEvent(event)) {
return true;
} else {
return false;
}
}
});
// creates Previous and Next buttons
Button btnPrevious = new Button(getContext());
btnPrevious.setLayoutParams(new LayoutParams(150, LayoutParams.FILL_PARENT));
btnPrevious.setText("Previous");
btnPrevious.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
previous();
}
});
Button btnNext = new Button(getContext());
btnNext.setLayoutParams(new LayoutParams(150, LayoutParams.FILL_PARENT));
btnNext.setText("Next");
btnNext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
next();
}
});
// bar that include the buttons
mBar = new LinearLayout(getContext());
mBar.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
mBar.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
mBar.setBackgroundColor(Color.GRAY);
mBar.addView(btnPrevious);
mBar.addView(btnNext);
mBar.setVisibility(LinearLayout.INVISIBLE);
// add bar and scroll in the super (LinearLayout)
super.addView(mBar);
super.addView(mScroll);
}
/**
* All that the user include is added in the scroll
*/
@Override
public void addView(View child) {
mScroll.addView(child);
}
/**
* Controls if the top bar should appear or not
*/
@Override
protected void onSizeChanged(int arg0, int arg1, int arg2, int arg3) {
super.onSizeChanged(arg0, arg1, arg2, arg3);
View chield = mScroll.getChildAt(0);
if (chield != null) {
if (chield.getMeasuredWidth() > getWidth()) {
mBar.setVisibility(LinearLayout.VISIBLE);
} else {
mBar.setVisibility(LinearLayout.INVISIBLE);
}
}
}
/**
* does the effect "back a page"
*/
public void previous() {
mPageActive = (mPageActive > 0) ? mPageActive - 1 : 0;
mScroll.smoothScrollTo(mPageActive * mScroll.getWidth(), 0);
}
/**
* does the effect "forward a page"
*/
public void next() {
int pageWidth = mScroll.getWidth();
int nextPage = (mPageActive + 1) * pageWidth;
if (nextPage - mScroll.getScrollX() <= pageWidth) {
mScroll.smoothScrollTo(nextPage, 0);
mPageActive++;
} else {
mScroll.smoothScrollTo(mScroll.getScrollX(), 0);
}
}
/**
* Private class that controls the gestures, forward or back a page.
*/
private class MySimpleOnGestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (e1 != null && e2 != null) {
if (e1.getX() - e2.getX() > 0) {
// forward...
next();
return true;
} else if (e2.getX() - e1.getX() > 0) {
// back...
previous();
return true;
}
}
return false;
}
}
}
| true
|
2789e507a851525ad455bfe56c1470e07b9677d6
|
Java
|
gtongue/StockTool
|
/src/LiveData.java
|
UTF-8
| 3,124
| 2.890625
| 3
|
[] |
no_license
|
import java.util.ArrayList;
public class LiveData {
public static void GetStockMCap(ArrayList<Stock> stocks) {
int counter = 0;
for (Stock stock : stocks) {
System.out.println(counter + "out of " + stocks.size());
try {
String URL = "https://ycharts.com/companies/" + stock.SYM + "/market_cap";
String data = Getter.getURL(URL);
String find = "<td class=\"col2\">";
data = data.substring(data.indexOf(find) + find.length());
data = data.substring(0, data.indexOf("</td>"));
String mCap = data.replaceAll(" ", "");
mCap = mCap.replaceAll("\\n", "");
float MCap = Float.parseFloat(mCap.substring(0, mCap.length() - 1));
if (mCap.charAt(mCap.length() - 1) == 'B')
MCap = MCap * 1000000000;
else
MCap = MCap * 1000000;
stock.MCap = MCap;
}catch(Exception e){
}
counter++;
}
}
// Get Data for the last trading day about these stocks
public static void GetStockDailyInfo(ArrayList<Stock> stocks) {
String URL = "http://finance.yahoo.com/d/quotes.csv?s=";
for (Stock stock : stocks) {
URL += (stock.SYM + "+");
}
URL = URL.substring(0, URL.length());
URL += "&f=sl1erdjkj1";
String data = Getter.getURL(URL);
String[] dataArr = data.split("\n");
for (int i = 0; i < dataArr.length; i++) {
String s = dataArr[i];
String[] line = s.split(",");
try {
stocks.get(i).Price = Double.parseDouble(line[1]);
} catch (Exception e) {
stocks.get(i).Price = 0;
}
try {
stocks.get(i).EPS = Double.parseDouble(line[2]);
} catch (Exception e) {
stocks.get(i).EPS = 0;
}
try {
stocks.get(i).PE = Double.parseDouble(line[3]);
} catch (Exception e) {
stocks.get(i).PE = 0;
}
try {
stocks.get(i).DPS = Double.parseDouble(line[4]);
} catch (Exception e) {
stocks.get(i).DPS = 0;
}
try {
stocks.get(i).FiftyTwoLow = Double.parseDouble(line[5]);
} catch (Exception e) {
stocks.get(i).FiftyTwoLow = 0;
}
try {
stocks.get(i).FiftyTwoHigh = Double.parseDouble(line[6]);
double MCap = Double.parseDouble(line[7].substring(0, line[7].length() - 1));
if (line[7].charAt(line[7].length() - 1) == 'B')
MCap = MCap * 1000000000;
else
MCap = MCap * 1000000;
stocks.get(i).MCap = MCap;
} catch (Exception e) {
stocks.get(i).MCap = 0;
}
}
}
}
| true
|
ab2141bc97462e0e53c8040759d3097725e8de08
|
Java
|
daegeonkim/Study_Java
|
/Java_Programming/Junk/Chapter2의 필요없는 파일/z/Junk/StudentTest.java
|
UTF-8
| 1,206
| 3.421875
| 3
|
[] |
no_license
|
package z.Junk;
public class StudentTest extends junit.framework.TestCase{
public void testCreate(){
final String firstStudentName = "Jane Doe";
final String secondStudentName = "John Snow";
// Student student = new Student("Jane Doe");// 해당 값에 스트링 값을 그냥 넣는건 좋지않다고 한다..
Student student = new Student(firstStudentName); // 그래서 위에서 선언한 상수값을 대입한다 (수정시 편하게하려는건가)
// String studentName = student.getName(); // 왜 스테틱으로 선언하라는걸까 어차피 스튜던트 클래스 내에서 사용하는건ㄷ[ ..
// assertEquals("Jane Doe", studentName);
assertEquals(firstStudentName,student.getName());
Student secondStudent = new Student(secondStudentName);
// String secondStudentName = secondStudent.getName();
// assertEquals("John Snow", secondStudentName); 그냥 리턴받아온 getName메소드를 쓰면 더효율적이다.
assertEquals(secondStudentName , secondStudent.getName());
}
}
class Student{
String name;
public Student(String name){ // 원
this.name = name;
}
String getName(){ // 얘는 퍼블릭이 아닌데 괜찮은건가 ??
return name;
}
}
| true
|
996474a067d2365422b9f82fe40ed121eff8f1ad
|
Java
|
AdarshMaurya/LookAndFeel
|
/src/main/java/com/softhinkers/galsen/server/http/HttpRequest.java
|
UTF-8
| 307
| 2.046875
| 2
|
[] |
no_license
|
package com.softhinkers.galsen.server.http;
import java.util.Map;
public abstract interface HttpRequest {
public abstract String method();
public abstract String uri();
public abstract String body();
public abstract String header(String paramString);
public abstract Map<String, Object> data();
}
| true
|
f2b18a94d276149c459aec38475bbcbf35b21208
|
Java
|
OberstK/GameYT
|
/src/de/benni/firstgame/level/tile/spawn_level/SpawnHedgeTile.java
|
UTF-8
| 510
| 2.5625
| 3
|
[] |
no_license
|
package de.benni.firstgame.level.tile.spawn_level;
import de.benni.firstgame.graphics.Screen;
import de.benni.firstgame.graphics.Sprite;
import de.benni.firstgame.level.tile.Tile;
public class SpawnHedgeTile extends Tile {
public SpawnHedgeTile(Sprite sprite) {
super(sprite);
}
@Override
public void render(int x, int y, Screen screen) {
screen.renderTile(x << 4, y << 4, this.sprite);
}
@Override
public boolean solid() {
return true;
}
public boolean breakable() {
return false;
}
}
| true
|
3d18e1cace2a4a9742f3a0aba1ebcb4c576ee768
|
Java
|
PhoenixxClaw/SchulProjekt
|
/SchulProjekt/src/methods/AusweisFunktionen.java
|
UTF-8
| 6,272
| 2.46875
| 2
|
[] |
no_license
|
package methods;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import alerts.Alerts;
import dao.AusweisDAO;
import dao.BenutzerDAO;
import entities.Ausweis;
import entities.Benutzer;
public class AusweisFunktionen {
public void ausweisAnlegenMitBenutzer(Benutzer benutzer) {
BenutzerDAO benutzerDAO = new BenutzerDAO();
AusweisDAO ausweisDAO = new AusweisDAO();
Ausweis ausweis = new Ausweis();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
String datum = dateFormat.format(date);
ausweis.setErstellDatum(datum);
String erstellDatum = datum;
String[] split = erstellDatum.split("-");
String ablaufJahr = split[2];
ablaufJahr = Integer.toString(Integer.valueOf(ablaufJahr) + 1);
String ablaufDatum = split[0] + "-" + split[1] + "-" + ablaufJahr;
ausweis.setAblaufDatum(ablaufDatum);
ausweis.setBenutzer(benutzer);
ausweis.setStatus("Gültig");
String ausweisNummer = "1";
int latestAusweisID = ausweisDAO.findLastAusweis().getAusweisID();
System.out.println(latestAusweisID);
Ausweis latestAusweis = ausweisDAO.find(latestAusweisID);
System.out.println(latestAusweis.getBenutzer());
String latestAusweisNumber = latestAusweis.getAusweisNummer();
System.out.println(latestAusweisNumber);
int ausweisNumber = (Integer.valueOf(latestAusweisNumber) - 1000000000) + 1;
int ausweisStringSize = Integer.toString(ausweisNumber).length();
for (int i = 0; i < (9 - ausweisStringSize); i++) {
ausweisNummer = ausweisNummer + "0";
}
ausweisNummer = ausweisNummer + ausweisNumber;
ausweis.setAusweisNummer(ausweisNummer);
ausweis.setBenutzer(benutzer);
ausweisDAO.persist(ausweis);
ausweisDAO.shutdown();
benutzerDAO.shutdown();
}
public void ausweisAnlegenMitBenutzerNummer(String benutzerNummer) {
BenutzerDAO benutzerDAO = new BenutzerDAO();
Benutzer benutzer = benutzerDAO.findByBenutzerNummer(benutzerNummer);
AusweisDAO ausweisDAO = new AusweisDAO();
Ausweis ausweis = new Ausweis();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
String datum = dateFormat.format(date);
ausweis.setErstellDatum(datum);
String erstellDatum = datum;
String[] split = erstellDatum.split("-");
String ablaufJahr = split[2];
ablaufJahr = Integer.toString(Integer.valueOf(ablaufJahr) + 1);
String ablaufDatum = split[0] + "-" + split[1] + "-" + ablaufJahr;
ausweis.setAblaufDatum(ablaufDatum);
ausweis.setBenutzer(benutzer);
ausweis.setStatus("Gültig");
String ausweisNummer = "1";
int latestAusweisID = ausweisDAO.findLastAusweis().getAusweisID();
System.out.println(latestAusweisID);
Ausweis latestAusweis = ausweisDAO.find(latestAusweisID);
System.out.println(latestAusweis.getBenutzer());
String latestAusweisNumber = latestAusweis.getAusweisNummer();
System.out.println(latestAusweisNumber);
int ausweisNumber = (Integer.valueOf(latestAusweisNumber) - 1000000000) + 1;
int ausweisStringSize = Integer.toString(ausweisNumber).length();
for (int i = 0; i < (9 - ausweisStringSize); i++) {
ausweisNummer = ausweisNummer + "0";
}
ausweisNummer = ausweisNummer + ausweisNumber;
ausweis.setAusweisNummer(ausweisNummer);
ausweis.setBenutzer(benutzer);
ausweisDAO.persist(ausweis);
ausweisDAO.shutdown();
benutzerDAO.shutdown();
}
public void ausweisVerlaengern(String ausweisNummer, int monatsZahl) {
DateConverter dateConverter = new DateConverter();
AusweisDAO ausweisDAO = new AusweisDAO();
Ausweis ausweis = ausweisDAO.findByAusweisNummer(ausweisNummer);
ausweis.setAblaufDatum(dateConverter.convertMonth(ausweis.getAblaufDatum(), monatsZahl));
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
}
public void ausweisVerlaengernByAusweisID(int ausweisID, int monatsZahl) {
DateConverter dateConverter = new DateConverter();
AusweisDAO ausweisDAO = new AusweisDAO();
Ausweis ausweis = ausweisDAO.find(ausweisID);
ausweis.setAblaufDatum(dateConverter.convertMonth(ausweis.getAblaufDatum(), monatsZahl));
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
}
public void statusAnpassen (String ausweisNummer, int aktion, boolean console) {
AusweisDAO ausweisDAO = new AusweisDAO();
Ausweis ausweis = ausweisDAO
.findByAusweisNummer(ausweisNummer);
switch (aktion) {
case 1:
ausweis.setStatus("Abgelaufen");
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
break;
case 2:
ausweis.setStatus("Gültig");
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
case 3:
Alerts alert = new Alerts();
ausweis.setStatus("Verloren");
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
if (console) {
boolean check = alert.ausweisVerlorenNeuenAnlegen();
if (check) {
ausweisAnlegenMitBenutzerNummer(ausweis.getBenutzer().getBenutzerNummer());
}
} else {
System.out.println("Wollen Sie einen neuen Ausweis für den Benutzer anlegen?"
+"\n1: Ja\n2: Nein\nEingabe: ");
Scanner sc = new Scanner(System.in);
if (sc.nextInt()==1) {
ausweisAnlegenMitBenutzerNummer(ausweis.getBenutzer().getBenutzerNummer());
}
}
default:
break;
}
}
public void statusAnpassenByAusweisID (int ausweisID, int aktion, boolean console) {
AusweisDAO ausweisDAO = new AusweisDAO();
Ausweis ausweis = ausweisDAO.find(ausweisID);
switch (aktion) {
case 1:
ausweis.setStatus("Abgelaufen");
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
break;
case 2:
ausweis.setStatus("Gültig");
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
case 3:
Alerts alert = new Alerts();
ausweis.setStatus("Verloren");
ausweisDAO.update(ausweis);
ausweisDAO.shutdown();
if (console) {
boolean check = alert.ausweisVerlorenNeuenAnlegen();
if (check) {
ausweisAnlegenMitBenutzerNummer(ausweis.getBenutzer().getBenutzerNummer());
}
} else {
System.out.println("Wollen Sie einen neuen Ausweis für den Benutzer anlegen?"
+"\n1: Ja\n2: Nein\nEingabe: ");
Scanner sc = new Scanner(System.in);
if (sc.nextInt()==1) {
ausweisAnlegenMitBenutzerNummer(ausweis.getBenutzer().getBenutzerNummer());
}
}
default:
break;
}
}
}
| true
|
f37b440bc9814a7d4a7125f462dac718566b883b
|
Java
|
Mohinder10/TestRepo
|
/src/test/java/utilities/DriverFactory.java
|
UTF-8
| 922
| 2.859375
| 3
|
[] |
no_license
|
package utilities;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DriverFactory {
public static ThreadLocal<WebDriver> threadLocal= new ThreadLocal<>();
public WebDriver init_driver(String browser){
System.out.println("Opening in "+browser+"browser...");
switch (browser.toUpperCase()) {
case "CHROME":
WebDriverManager.chromedriver().setup();
threadLocal.set(new ChromeDriver());
break;
case "FIREFOX":
WebDriverManager.firefoxdriver().setup();
threadLocal.set(new FirefoxDriver());
break;
default:
System.out.println("Invalid browser name..");
break;
}
return getDriver();
}
public static synchronized WebDriver getDriver(){
return threadLocal.get();
}
}
| true
|
5a37da5c83ec973d5358885a08098f42bd854af5
|
Java
|
lmlyiwai/lshtc
|
/src/com/scene/TestBinaryScene.java
|
GB18030
| 1,985
| 2.171875
| 2
|
[] |
no_license
|
package com.scene;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import com.fileInputOutput.InvalidInputDataException;
import com.fileInputOutput.Parameter;
import com.fileInputOutput.Problem;
import com.rssvm.Measures;
import com.rssvm.OneVsAllMultilabel;
import com.sparseVector.DataPoint;
import com.tools.FileIO;
public class TestBinaryScene {
@Test
public void test() throws IOException, InvalidInputDataException {
String trainfile = "F:\\DataSets\\scene\\scene-train.svm";
String testfile = "F:\\DataSets\\scene\\scene-test.svm";
Problem train = Problem.readProblem(new File(trainfile), 1);
Parameter param = new Parameter(0.2, 1000, 0.001);
OneVsAllMultilabel rs = new OneVsAllMultilabel(train, param);
double[] c = new double[15];
for(int i = -7; i < 8; i++) {
c[i + 7] = Math.pow(2, i);
}
int[] K = {1, 3, 5, 7, 11, 21, 31, 41, 51, 61, 71, 81, 91, 101};
for(int i = 0; i < c.length; i++) {
// param.setC(c[i]);
// rs.crossValidation(train, param, 5);
}
Problem test = Problem.readProblem(new File(testfile), 1);
DataPoint[][] w = rs.train(train, param);
double[][] prev = rs.predictValues(w, test.x);
int[][] pre = rs.predict(prev);
double microf1 = Measures.microf1(rs.getUniqueLabels(), test.y, pre);
double macrof1 = Measures.macrof1(rs.getUniqueLabels(), test.y, pre);
double hammmingLoss = Measures.averageSymLoss(test.y, pre);
double zeroneloss = Measures.zeroOneLoss(test.y, pre);
System.out.println("C = " + param.getC() + ", Micro-F1 = " + microf1 + ", Macro-F1 = " + macrof1 +
", Hamming Loss = " + hammmingLoss + ", Zero One Loss = " + zeroneloss);
String testlabel = "F:\\\\ʵ\\scene\\ǩ.txt";
String prelabel = "F:\\\\ʵ\\scene\\ԤǩBinarySVM.txt";
FileIO.writeLabelToFile(testlabel, test.y);
FileIO.writeLabelToFile(prelabel, pre);
}
}
| true
|
2f6e9ab87733b8aa585d543d25fde7588afe1181
|
Java
|
wojtazzz/appium-template
|
/src/test/java/steps/MapSteps.java
|
UTF-8
| 453
| 1.78125
| 2
|
[] |
no_license
|
package steps;
import config.TestRunner;
import cucumber.api.CucumberOptions;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import cucumber.api.java.en.Given;
import page.MapView;;
public class MapSteps extends TestRunner {
@Given("^User is on map screen$")
public void userIsOnMap() throws Throwable {
new MapView()
.checkingLeadMeButtonIsDisplayed()
.mapGuyIsDisplayed();
}
}
| true
|
84fb3f6c7c76e662e8ed8840ce8e01fdfd438286
|
Java
|
Duongnvse62382/grouptravel
|
/group-travel-assistant-android/app/src/main/java/com/fpt/gta/util/ChangeValue.java
|
UTF-8
| 3,685
| 2.859375
| 3
|
[] |
no_license
|
package com.fpt.gta.util;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ChangeValue {
public static String formatDecimalPrice(double number) {
DecimalFormat formatter = new DecimalFormat("###,###,###,###.##");
return formatter.format(number);
}
public static String priceWithoutDecimal(Double price) {
DecimalFormat formatter = new DecimalFormat("###,###,###.##");
return formatter.format(price);
}
public static int formatFloatToInt(Float number) {
return number.intValue();
}
public static String changePercentFloat(float cate_percent, float total) {
float result = Math.round((cate_percent / total) * 100);
return result + " % ";
}
public static String fomatStringDate(String date1) {
String newFormatData;
SimpleDateFormat oldformat = new SimpleDateFormat(
"dd/MM/yyyy");
SimpleDateFormat newFormat = new SimpleDateFormat("yyyy/MM/dd");
Date old = null;
try {
old = oldformat.parse(date1);
} catch (ParseException e) {
e.printStackTrace();
}
newFormatData = newFormat.format(old);
return newFormatData;
}
public static String formatCurrency(BigDecimal currency) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "##,###,###.##";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
String bigDecimalConvertedValue = decimalFormat.format(currency);
return bigDecimalConvertedValue;
}
public static String formatOcrCurrency(Double currency) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "##,###,###.##";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
String bigDecimalConvertedValue = decimalFormat.format(currency);
return bigDecimalConvertedValue;
}
public static String formatBigCurrency(BigDecimal currency) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,###,###,###,###.##";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
String bigDecimalConvertedValue = decimalFormat.format(currency);
return bigDecimalConvertedValue;
}
public static String formatOcrMoney(BigDecimal currency) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,###,###,###,###.#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
String bigDecimalConvertedValue = decimalFormat.format(currency);
return bigDecimalConvertedValue;
}
public static String formatRateCurrency(BigDecimal currency) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "##,###,###.#########";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
String bigDecimalConvertedValue = decimalFormat.format(currency);
return bigDecimalConvertedValue;
}
}
| true
|
41a2e376be6dc59fd46c36a264830f6b89f18a25
|
Java
|
kalrapranav/ds
|
/src/com/hrishikeshmishra/practices/dynamicprogramming/RangeSumQuery.java
|
UTF-8
| 1,453
| 4.09375
| 4
|
[] |
no_license
|
package com.hrishikeshmishra.practices.dynamicprogramming;
import java.util.Arrays;
/**
* Problem:
* Range Sum Query
* How to find sum of elements from given index interval (i, j) in constant time?
*
* @author hrishikesh.mishra
* @link http://stackoverflow.com/questions/2473114/how-to-find-sum-of-elements-from-given-index-interval-i-j-in-constant-time
*/
public class RangeSumQuery {
private final int[] sumArray;
public RangeSumQuery(int[] array) {
sumArray = new int[array.length];
init(array);
}
private void init(int[] array) {
sumArray[0] = array[0];
for (int i = 1; i < array.length; i++) {
sumArray[i] = sumArray[i - 1] + array[i];
}
}
public int getSumOfItoJ(int i, int j) {
int sumTillJ = sumArray[j];
int sumTillI = 0;
if (i > 0) {
sumTillI = sumArray[i - 1];
}
return sumTillJ - sumTillI;
}
}
class RangeSumQueryTest {
public static void main(String[] args) {
int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
RangeSumQuery rangeSumQuery = new RangeSumQuery(array);
System.out.println("Array :" + Arrays.toString(array));
System.out.println("Sum (0, 9): " + rangeSumQuery.getSumOfItoJ(0, 9));
System.out.println("Sum (1, 9): " + rangeSumQuery.getSumOfItoJ(1, 9));
System.out.println("Sum (1, 4): " + rangeSumQuery.getSumOfItoJ(1, 4));
}
}
| true
|
9523a70a12d3440073b75339bde1dd74c2a3480f
|
Java
|
KerwinJT/MidtermProject
|
/JPAUrbanGarden/src/main/java/com/skilldistillery/urbangarden/entities/Product.java
|
UTF-8
| 2,534
| 2.5625
| 3
|
[] |
no_license
|
package com.skilldistillery.urbangarden.entities;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String type;
private String description;
@Column(name = "size_of_product")
@Enumerated(EnumType.STRING)
private SizeOfProduct sizeOfProduct;
@Column(name = "image_url")
private String imageURL;
@OneToMany(mappedBy = "product")
private List<GardenProduce> gardenProduces;
//
//Methods Begin
//
public Product() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public SizeOfProduct getSizeOfProduct() {
return sizeOfProduct;
}
public void setSizeOfProduct(SizeOfProduct sizeOfProduct) {
this.sizeOfProduct = sizeOfProduct;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public List<GardenProduce> getGardenProduces() {
return gardenProduces;
}
public void setGardenProduces(List<GardenProduce> gardenProduces) {
this.gardenProduces = gardenProduces;
}
@Override
public String toString() {
return "Product [id=" + id + ", name=" + name + ", type=" + type + ", description=" + description
+ ", sizeOfProduct=" + sizeOfProduct + ", imageURL=" + imageURL + "]";
}
public void addGardenProduce(GardenProduce gp) {
if (gardenProduces == null) {
gardenProduces = new ArrayList<GardenProduce>();
}
if (!gardenProduces.contains(gp)) {
gardenProduces.add(gp);
if(gp.getGardenStoreFront() != null) {
gp.getGardenStoreFront().getGardenProduces().remove(gp);
}
gp.setProduct(this);
}
}
public void removeGardenProduce(GardenProduce gp) {
gp.setGardenStoreFront(null);
if (gardenProduces != null) {
gardenProduces.remove(gp);
}
}
}
| true
|
890a81642e7b8cd37f81817d8cdf23509de4a521
|
Java
|
luismanuelamengual/NeoGroup-Warp
|
/src/main/java/org/neogroup/warp/data/query/DeleteQuery.java
|
UTF-8
| 1,035
| 2.140625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.neogroup.warp.data.query;
import org.neogroup.warp.data.query.conditions.ConditionGroup;
import org.neogroup.warp.data.query.traits.HasTable;
import org.neogroup.warp.data.query.traits.HasWhereConditions;
public class DeleteQuery extends Query implements
HasTable<DeleteQuery>,
HasWhereConditions<DeleteQuery> {
private String tableName;
private ConditionGroup whereConditionGroup;
public DeleteQuery() {
this.tableName = null;
this.whereConditionGroup = new ConditionGroup();
}
@Override
public String getTableName() {
return tableName;
}
@Override
public DeleteQuery setTableName(String tableName) {
this.tableName = tableName;
return this;
}
@Override
public ConditionGroup getWhereConditions() {
return whereConditionGroup;
}
@Override
public DeleteQuery setWhereConditions(ConditionGroup conditionGroup) {
this.whereConditionGroup = conditionGroup;
return this;
}
}
| true
|
573d477612f96d9bdbfa96bd03ef9a65837942cb
|
Java
|
chantheepic/java-server-Space_Forum
|
/src/main/java/space_forum_server/java_server/repositories/ForumPostRepository.java
|
UTF-8
| 232
| 1.679688
| 2
|
[] |
no_license
|
package space_forum_server.java_server.repositories;
import space_forum_server.java_server.models.*;
import org.springframework.data.repository.*;
public interface ForumPostRepository extends CrudRepository<ForumPost, Integer> {
}
| true
|
47f99f7cd65b3a0c74f67d7c0bc957fce8f68cdb
|
Java
|
haohaodiniyao/dolphin
|
/src/main/java/org/dolphin/commons/hystrix/CommandHelloWorld.java
|
UTF-8
| 516
| 2.296875
| 2
|
[] |
no_license
|
package org.dolphin.commons.hystrix;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
/**
* hystrix http://www.jianshu.com/p/b9af028efebb
* @author yaokai
*
*/
public class CommandHelloWorld extends HystrixCommand<String> {
private final String name;
public CommandHelloWorld(String name){
super(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"));
this.name = name;
}
@Override
protected String run() throws Exception {
return "Hello "+name+"!";
}
}
| true
|
cf7e0b82f732c7c655a557aa6954b8cac146af3b
|
Java
|
matgou/jimapfilter
|
/src/main/java/info/kapable/app/Actions/VacationAction.java
|
UTF-8
| 643
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package info.kapable.app.Actions;
import javax.mail.Message;
import javax.mail.MessagingException;
import org.apache.jsieve.mail.Action;
import info.kapable.app.Exception.NotImplementedException;
import info.kapable.app.Protocole.ProtocoleInterface;
public class VacationAction implements MailAction {
public void execute(Action anAction, Message message, ProtocoleInterface server) throws MessagingException {
try {
// TODO Implements function
throw new NotImplementedException("Action RedirectAction isn't implemented in this version of JImapFilter");
} catch (NotImplementedException e) {
e.printStackTrace();
}
}
}
| true
|
61979368d0d4ed575c521797c3e15c16b5041a95
|
Java
|
medes-imps/imogene
|
/model/org.imogene.model.core.editor/src/org/imogene/model/core/descriptions/FieldGroupDescriptionWidget.java
|
UTF-8
| 2,527
| 2.234375
| 2
|
[] |
no_license
|
package org.imogene.model.core.descriptions;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.imogene.model.core.Description;
import org.imogene.model.core.FieldGroup;
public class FieldGroupDescriptionWidget extends Composite implements MyItem {
private FieldGroup fieldGroup;
private Group descriptions;
private EditingDomain editingDomain;
private List<MyItem> children;
public FieldGroupDescriptionWidget(Composite parent, int style) {
super(parent, style);
}
public void setFieldGroup(FieldGroup fieldGroup) {
this.fieldGroup = fieldGroup;
onFieldGroupChanged();
}
public void setEditingDomain(EditingDomain editingDomain) {
this.editingDomain = editingDomain;
}
protected void onFieldGroupChanged() {
if (descriptions != null) {
descriptions.dispose();
}
if (children != null) {
children.clear();
}
createComposite();
Notifier.getInstance().layout(fieldGroup.getParentCard());
}
private void createComposite() {
setLayout(new GridLayout());
descriptions = new Group(this, SWT.NONE);
descriptions.setText("Field group descriptions");
descriptions.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
descriptions.setLayout(new GridLayout(2, false));
for (Description description : fieldGroup.getDescriptions()) {
LabelWidget label = new LabelWidget(descriptions, SWT.NONE);
label.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING));
label.setDescription(description);
DescriptionWidget text = new DescriptionWidget(descriptions, SWT.NONE);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
text.setEditingDomain(editingDomain);
text.setLabel(label);
text.setDescription(description);
if (children == null) {
children = new ArrayList<MyItem>();
}
children.add(text);
}
}
@Override
public void refreshItem() {
onFieldGroupChanged();
}
@Override
public void updateItem() {
}
@Override
public List<MyItem> getChildrenItem() {
if (children != null) {
return new ArrayList<MyItem>(children);
}
return null;
}
public EObject getEObject() {
return null;
};
@Override
public boolean hasChildren() {
return children != null && children.size() > 0;
}
}
| true
|
bf88d40ce85ea91862f93170753c732060ffa75b
|
Java
|
newtonker/wechat6.5.3
|
/app/src/main/wechat6.5.3/com/tencent/mm/plugin/wallet_core/id_verify/a/a.java
|
UTF-8
| 764
| 1.585938
| 2
|
[] |
no_license
|
package com.tencent.mm.plugin.wallet_core.id_verify.a;
import com.tencent.mm.sdk.platformtools.v;
import com.tencent.mm.wallet_core.e.a.g;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
public final class a extends g {
public a(int i) {
Map hashMap = new HashMap();
hashMap.put("scene", String.valueOf(i));
u(hashMap);
}
public final int aed() {
return 1584;
}
public final void a(int i, String str, JSONObject jSONObject) {
v.i("MicroMsg.NetSceneAgreeDisclaimer", "errCode = " + i + ";errMsg = " + str);
}
public final int zg() {
return 1584;
}
public final String getUri() {
return "/cgi-bin/mmpay-bin/tenpay/realnamesetduty";
}
}
| true
|
472e51341b7d4d69cfa39348e094433da8377f52
|
Java
|
sterwill/spark-2012
|
/client/src/org/tailfeather/client/model/Command.java
|
UTF-8
| 1,759
| 2.28125
| 2
|
[] |
no_license
|
package org.tailfeather.client.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.tailfeather.client.model.exec.Echo;
import org.tailfeather.client.model.exec.Executable;
import org.tailfeather.client.model.exec.Exit;
import org.tailfeather.client.model.exec.MatchGame;
import org.tailfeather.client.model.exec.PrintStatus;
import org.tailfeather.client.model.exec.Register;
@XmlRootElement(name = "command")
@XmlAccessorType(XmlAccessType.FIELD)
public class Command {
@XmlElement(name = "name")
private List<String> names;
@XmlElements({ @XmlElement(name = "echo", type = Echo.class),
@XmlElement(name = "printStatus", type = PrintStatus.class),
@XmlElement(name = "matchgame", type = MatchGame.class),
@XmlElement(name = "register", type = Register.class), @XmlElement(name = "exit", type = Exit.class) })
private List<Executable> exec = new ArrayList<Executable>();
@XmlTransient
private boolean exit;
@XmlTransient
private Acorn acorn;
public List<String> getNames() {
return names;
}
public boolean isExit() {
return this.exit;
}
public void setExit(boolean exit) {
this.exit = exit;
}
public void setAcorn(Acorn acorn) {
this.acorn = acorn;
}
public Acorn getAcorn() {
return acorn;
}
public boolean enabled() {
for (Executable e : exec) {
if (e.enabled(this)) {
return true;
}
}
return false;
}
public void execute() {
for (Executable e : exec) {
e.execute(this);
}
}
}
| true
|
47b6aaf8148558adb19252810b3b0e9e5b4ffc92
|
Java
|
SexCastException/design-pattern
|
/GOF24/src/com/huazai/gof/facade/Power.java
|
UTF-8
| 213
| 2.265625
| 2
|
[] |
no_license
|
package com.huazai.gof.facade;
public class Power {
public void startup() {
System.out.println("电源启动");
}
public void shutdown() {
System.out.println("电源关闭");
}
}
| true
|
710e8505b60b6b3a6bff13f0d8fcb685c594b235
|
Java
|
vilcs/ing_soft_final
|
/src/main/java/bo/edu/ucb/sis/piratebay/bl/OrderBl.java
|
UTF-8
| 845
| 1.984375
| 2
|
[] |
no_license
|
package bo.edu.ucb.sis.piratebay.bl;
import bo.edu.ucb.sis.piratebay.dao.OrderDao;
import bo.edu.ucb.sis.piratebay.model.OrderModel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class OrderBl {
private OrderDao orderDao;
@Autowired
public OrderBl(OrderDao orderDao) {
this.orderDao = orderDao;
}
public List<PayedModel> findAllPayed() {
return this.orderDao.findAllPayed();
}
public List<ReadyModel> findAllReady() {
return this.orderDao.findAllReady();
}
public List<DispatchedModel> findAllDispatched() {
return this.orderDao.findAllDispatched();
}
public List<DeliveredModel> findAllDelivered() {
return this.orderDao.findAllDelivered();
}
}
| true
|
971a81861bc7375a9a76c94b60a6bd4f18521003
|
Java
|
PedroPareschi/CollegeManagement
|
/src/main/java/br/com/pedropareschi/collegemanagement/domain/Address.java
|
UTF-8
| 2,499
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
package br.com.pedropareschi.collegemanagement.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
import java.util.Objects;
@Entity
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String street;
private String number;
private String addressLine2;
private String district;
private String cep;
private String town;
private String state;
public Address() {
}
public Address(Integer id, String street, String number, String addressLine2, String district, String cep, String town, String state) {
this.id = id;
this.street = street;
this.number = number;
this.addressLine2 = addressLine2;
this.district = district;
this.cep = cep;
this.town = town;
this.state = state;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public String getDistrict() {
return district;
}
public void setDistrict(String neighborhood) {
this.district = neighborhood;
}
public String getCep() {
return cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Address)) return false;
Address address = (Address) o;
return id.equals(address.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| true
|
8eeced80f791064bd56e8fccd45f375506145168
|
Java
|
Savage-E/JUnit
|
/models/src/main/java/ru/mail/library/BookModel.java
|
UTF-8
| 290
| 1.734375
| 2
|
[] |
no_license
|
package ru.mail.library;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.jetbrains.annotations.NotNull;
@AllArgsConstructor
@Setter
@Getter
public class BookModel {
private @NotNull
AuthorModel author;
private @NotNull String name;
}
| true
|
3d323cc9364a232dc44f1ae874c6916fe0937d13
|
Java
|
379924269/springboot1.5.9-oauth2-demo
|
/authorization-code/qq/src/main/java/moe/cnkirito/security/oauth2/code/module/entity/OauthClientDetails.java
|
UTF-8
| 2,092
| 1.953125
| 2
|
[] |
no_license
|
package moe.cnkirito.security.oauth2.code.module.entity;
import io.swagger.annotations.ApiModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* <p>
* 客户端信息
* </p>
*
* @author huazai
* @since 2020-04-29
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@ApiModel(value = "OauthClientDetails对象", description = " 客户端信息")
public class OauthClientDetails implements Serializable {
private static final long serialVersionUID = 1L;
private String clientId;
private String resourceIds;
private String clientSecret;
private String scope;
private String authorizedGrantTypes;
private String webServerRedirectUri;
private String authorities;
private Integer accessTokenValidity;
private Integer refreshTokenValidity;
private String additionalInformation;
private String autoapprove;
public OauthClientDetails() {
}
public OauthClientDetails(
String clientId
,
String resourceIds
,
String clientSecret
,
String scope
,
String authorizedGrantTypes
,
String webServerRedirectUri
,
String authorities
,
Integer accessTokenValidity
,
Integer refreshTokenValidity
,
String additionalInformation
,
String autoapprove
) {
this.clientId = clientId;
this.resourceIds = resourceIds;
this.clientSecret = clientSecret;
this.scope = scope;
this.authorizedGrantTypes = authorizedGrantTypes;
this.webServerRedirectUri = webServerRedirectUri;
this.authorities = authorities;
this.accessTokenValidity = accessTokenValidity;
this.refreshTokenValidity = refreshTokenValidity;
this.additionalInformation = additionalInformation;
this.autoapprove = autoapprove;
}
}
| true
|
d9386ffa52cb2f19a764399f7746cdcff1da25e0
|
Java
|
two-astronauts/java-set-operations
|
/src/JavaSetOperations/Node.java
|
UTF-8
| 666
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package JavaSetOperations;
/**
*
* @author User
*/
public class Node {
private Node nextNode;
private String data;
public Node(String data){
this.data = data;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
| true
|
698f826413a00781240b8bbff4bee84699fef5e7
|
Java
|
fenggao86/ACEIS
|
/src/org/insight_centre/aceis/subscriptions/TechnicalAdaptationManager.java
|
UTF-8
| 22,639
| 1.539063
| 2
|
[] |
no_license
|
package org.insight_centre.aceis.subscriptions;
import java.io.FileWriter;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import org.glassfish.tyrus.client.ClientManager;
import org.insight_centre.aceis.engine.ACEISEngine;
import org.insight_centre.aceis.engine.ACEISFactory;
import org.insight_centre.aceis.engine.CompositionPlanEnumerator;
import org.insight_centre.aceis.eventmodel.EventDeclaration;
import org.insight_centre.aceis.eventmodel.EventPattern;
import org.insight_centre.aceis.eventmodel.NodeRemovalException;
import org.insight_centre.aceis.eventmodel.QosVector;
import org.insight_centre.aceis.eventmodel.WeightVector;
import org.insight_centre.aceis.io.rdf.RDFFileManager;
import org.insight_centre.aceis.observations.QosUpdate;
import org.insight_centre.citypulse.server.QosServerEndpoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.csvreader.CsvWriter;
import com.google.gson.Gson;
@ClientEndpoint
public class TechnicalAdaptationManager {
public enum AdaptationMode {
global, incremental, local, na;
}
private class AdpatationMonitor implements Runnable {
private CsvWriter cw;
private ACEISEngine engine;
private final Logger logger = LoggerFactory.getLogger(AdpatationMonitor.class);
private String qid;
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
public AdpatationMonitor(String qid, ACEISEngine engine) {
super();
this.qid = qid;
this.engine = engine;
}
private void printResults() {
// print results
long resultCnt = SubscriptionManagerFactory.getSubscriptionManager().getConsumedMessageCnt().get(qid);
// long updateCnt1 = updateCnt;
int criticalUpdates = adaptations.size();
int successfulAdpt = 0;
long delaySum = 0;
for (AdaptationResult ar : adaptations) {
delaySum += ar.getTime();
if (ar.isSucess())
successfulAdpt += 1;
}
long violated = 0;
long total = 0;
for (Entry<Date, List<QosVector>> e : qosMap.entrySet()) {
for (QosVector q : e.getValue())
if (q.getAccuracy() < constraint.getAccuracy())
violated++;
total += e.getValue().size();
}
double avgDelay = 0.0;
if (adaptations.size() > 0)
avgDelay = delaySum / adaptations.size();
try {
cw = new CsvWriter(new FileWriter("resultLog/adpt/" + qid + ".csv", true), ',');
cw.write("result_cnt");
cw.write("update_rcv");
cw.write("update_sent");
cw.write("crit_update_cnt");
cw.write("avg_adpt_time");
cw.write("success_adpt_cnt");
cw.write("total_updates");
cw.write("violated_updates");
cw.write("localReplacement");
cw.write("localRecompose");
cw.write("parentReplacement");
cw.write("globalRecompose");
cw.endRecord();
cw.write(resultCnt + "");
cw.write(updateCnt + "");
cw.write(QosServerEndpoint.updateCnt + "");
cw.write(criticalUpdates + "");
cw.write(avgDelay + "");
cw.write(successfulAdpt + "");
cw.write(total + "");
cw.write(violated + "");
cw.write(localReplacement + "");
cw.write(localRecompose + "");
cw.write(parentReplacement + "");
cw.write(globalRecompose + "");
cw.endRecord();
cw.write(" ");
cw.write("acc");
cw.write("agg_from");
cw.endRecord();
Date start = null;
ArrayList<QosVector> qosList = new ArrayList<QosVector>();
for (Entry<Date, List<QosVector>> e : qosMap.entrySet()) {
if (start == null)
start = e.getKey();
if (TimeUnit.MILLISECONDS.toMinutes(e.getKey().getTime() - start.getTime()) >= 55) {
cw.write(sdf.format(e.getKey()).split("T")[1]);
Double avgAcc = 0.0;
for (QosVector qos : qosList)
avgAcc += qos.getAccuracy();
cw.write(avgAcc / qosList.size() + "");
cw.write(qosList.size() + "");
cw.endRecord();
start = null;
qosList = new ArrayList<QosVector>();
} else {
qosList.addAll(e.getValue());
}
}
cw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (liveQosStreams.size() > 3) {
try {
logger.info("remaining live qos streams: " + liveQosStreams.size()
+ ", current received csparql msgs: " + sub.getConsumedMessageCnt().get(qid));
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.printResults();
System.exit(0);
}
}
private class QosMonitor implements Runnable {
private Map<String, QosVector> epQosMap = new HashMap<String, QosVector>();
private final Logger logger = LoggerFactory.getLogger(QosMonitor.class);
public QosMonitor() {
super();
for (EventPattern ep : engine.getRepo().getEps().values()) {
try {
QosVector orginalQos = ep.aggregateQos();
this.epQosMap.put(ep.getID(), orginalQos);
logger.debug("Putting: " + orginalQos + " for: " + ep.getID());
} catch (CloneNotSupportedException | NodeRemovalException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
while (true) {
try {
boolean changed = false;
for (EventPattern ep : engine.getRepo().getEps().values()) {
// logger.info("Checking qos: " + ep.getID());
QosVector currentQos = ep.aggregateQos();
if (!currentQos.equals(this.epQosMap.get(ep.getID()))) {
logger.debug("CES qos update: " + ep.getID());
this.epQosMap.put(ep.getID(), currentQos);
if (!changed)
changed = true;
}
}
// logger.info("No qos changes affected CES.");
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
} catch (NodeRemovalException e) {
e.printStackTrace();
}
}
}
}
// public enum IncrementalSuccessMode {
// localReplacement, localRecompose, parentReplacement, globalRecompose
// }
private boolean adaptationLock = false;
private List<AdaptationResult> adaptations = new ArrayList<AdaptationResult>();
ClientManager client = ClientManager.createClient();
private QosVector constraint;
private EventDeclaration currentCompositionPlan;
private ACEISEngine engine;
private Double freq;
private CountDownLatch latch;
private HashMap<String, QosVector> latestQosMap = new HashMap<String, QosVector>();
private List<String> liveQosStreams = new ArrayList<String>();
private int localReplacement, localRecompose, parentReplacement, globalRecompose = 0;
private Logger logger = LoggerFactory.getLogger(this.getClass());
private AdaptationMode mode;
private TreeMap<Date, List<QosVector>> qosMap = new TreeMap<Date, List<QosVector>>();
private Date start, end;
// private EventPattern query;
private SubscriptionManager sub;
private long updateCnt = 0;
final String uri = "ws://localhost:8081/websockets/qos";
private WeightVector weight;
public TechnicalAdaptationManager(SubscriptionManager sub, EventDeclaration currentCompositionPlan,
QosVector constraint, WeightVector weight, Double freq, AdaptationMode mode, Date start, Date end) {
super();
this.sub = sub;
this.currentCompositionPlan = currentCompositionPlan;
this.constraint = constraint;
this.weight = weight;
this.freq = freq;
this.mode = mode;
this.start = start;
this.end = end;
// this.forceRealSensors(currentCompositionPlan);
}
/**
* @param serviceID
* @return new composition plan conforming with user's constraints
* @throws Exception
*/
protected EventDeclaration adaptation(String serviceID) throws Exception {
// adaptationLock = true;
logger.info("identifying service: " + serviceID + " current plan: " + this.currentCompositionPlan.getEp());
serviceID = this.identifyLocalServiceID(serviceID);
logger.info("identified service: " + serviceID);
EventDeclaration result = null;
if (this.mode == AdaptationMode.local) {
EventPattern newPattern = currentCompositionPlan.getEp().clone();
CompositionPlanEnumerator cpe = new CompositionPlanEnumerator(engine.getRepo(), newPattern);
for (EventDeclaration ed : currentCompositionPlan.getEp().getEds()) {
if (ed.getServiceId().equals(serviceID)) {
EventDeclaration newEd = cpe.getBestSubsitituteEDforED(ed, constraint, weight);
if (newEd != null) {
// if(newEd)
newPattern.replaceED(serviceID, newEd);
if (newPattern.aggregateQos().satisfyConstraint(constraint)) {
result = this.currentCompositionPlan.clone();
result.setEp(newPattern);
result.setComposedFor(this.currentCompositionPlan.getComposedFor());
break;
} else {
logger.info("Adaptation failed. Mode: " + this.mode);
// logger.info("====== qos details ======");
// logger.info("old: " + currentCompositionPlan.getEp().aggregateQos());
// for (EventDeclaration ed3 : currentCompositionPlan.getEp().getEds()) {
// logger.info(ed3.getServiceId().split("#")[1] + ": " + ed3.getExternalQos());
// }
// logger.info("-------------------------");
// logger.info("new: " + newPattern.aggregateQos());
// for (EventDeclaration ed2 : newPattern.getEds()) {
// logger.info(ed2.getServiceId().split("#")[1] + ": " + ed2.getExternalQos());
// }
}
}
}
}
} else if (this.mode == AdaptationMode.global) {
EventDeclaration newCompositionPlan = SubscriptionManagerFactory.getSubscriptionManager()
.createCompositionPlan(engine, this.currentCompositionPlan.getComposedFor(), constraint, weight,
false, false);
if (newCompositionPlan.getEp().aggregateQos().satisfyConstraint(constraint)) {
result = newCompositionPlan;
result.getEp().setTimeWindow(this.currentCompositionPlan.getEp().getTimeWindow());
// result.setEp(newPattern);
// result.setComposedFor(this.currentCompositionPlan.getComposedFor());
} else {
logger.info("Adaptation failed. Mode: " + this.mode);
}
} else if (this.mode == AdaptationMode.incremental) {
logger.info("Starting Incremental Adaptation for: " + serviceID);
boolean adapted = false;
EventPattern newPattern = currentCompositionPlan.getEp().clone();
CompositionPlanEnumerator cpe = new CompositionPlanEnumerator(engine.getRepo(), newPattern);
for (EventDeclaration ed : currentCompositionPlan.getEp().getEds()) {
if (ed.getServiceId().equals(serviceID)) {
EventDeclaration newEd = cpe.getBestSubsitituteEDforED(ed, constraint, weight);
if (newEd != null) { // try to replace this service
// if(newEd)
newPattern.replaceED(serviceID, newEd);
if (newPattern.aggregateQos().satisfyConstraint(constraint)) {
result = this.currentCompositionPlan.clone();
result.setEp(newPattern);
result.setComposedFor(this.currentCompositionPlan.getComposedFor());
adapted = true;
logger.info("Local replacement sucess. Mode: " + this.mode);
localReplacement += 1;
break;
} else {
logger.info("Local replacement failed. Mode: " + this.mode);
}
}
if (!adapted) {// try to re-compose this service
newPattern = currentCompositionPlan.getEp().clone();
EventPattern subPattern = currentCompositionPlan.getEp().getSubtreeByRoot(serviceID).clone();
if (subPattern.getSize() > 1) {
EventDeclaration newSubCompositionPlan;
if (subPattern.getSize() > 4) // GA suitable for large sub-patterns only
newSubCompositionPlan = SubscriptionManagerFactory.getSubscriptionManager()
.createCompositionPlan(engine, subPattern, constraint, weight, false, false);
else
newSubCompositionPlan = this.sub.createCompositionPlan(engine, subPattern, constraint,
weight, false, true);
newPattern.replaceSubtree(serviceID, newSubCompositionPlan.getEp());
if (newPattern.aggregateQos().satisfyConstraint(constraint)) {
result = this.currentCompositionPlan.clone();
result.setEp(newPattern);
result.setComposedFor(this.currentCompositionPlan.getComposedFor());
adapted = true;
logger.info("Local re-composition sucess. Mode: " + this.mode);
localRecompose += 1;
} else {
logger.info("Local re-composition failed - constraint not satisfied. Mode: "
+ this.mode);
}
} else {
logger.info("Local re-composition failed - subPattern size = 1. Mode: " + this.mode);
}
}
if (!adapted) { // try to replace parent services
List<String> candidates = engine.getRepo().getReusabilityHierarchy()
.getAllDescendants(this.currentCompositionPlan.getComposedFor().getID());
List<EventDeclaration> eds = new ArrayList<EventDeclaration>();
for (String s : candidates)
eds.add(engine.getRepo().getEDByEPId(s));
logger.info("Parent replacements found: " + eds.size());
List<EventDeclaration> sortedEds = this.getSortedEdByEpSize(eds);
for (EventDeclaration candidate : sortedEds) {
newPattern = currentCompositionPlan.getEp().clone();
newPattern.replaceAndSubPattern(newPattern.getRootId(), candidate);
if (newPattern.aggregateQos().satisfyConstraint(constraint)) {
result = this.currentCompositionPlan.clone();
result.setEp(newPattern);
result.setComposedFor(this.currentCompositionPlan.getComposedFor());
adapted = true;
logger.info("Local parent replacement sucess: " + candidate.toString() + " Mode: "
+ this.mode);
parentReplacement += 1;
break;
}
}
if (!adapted) {
logger.info("Local parent replacement failed - constraint not satisfied. Mode: "
+ this.mode);
}
}
if (!adapted) { // try global adaptation
EventDeclaration newCompositionPlan = SubscriptionManagerFactory.getSubscriptionManager()
.createCompositionPlan(engine, this.currentCompositionPlan.getComposedFor(),
constraint, weight, false, false);
if (newCompositionPlan.getEp().aggregateQos().satisfyConstraint(constraint)) {
result = newCompositionPlan;
result.getEp().setTimeWindow(this.currentCompositionPlan.getEp().getTimeWindow());
globalRecompose += 1;
} else {
logger.info("Global Adaptation failed. Mode: " + this.mode);
}
}
}
}
}
return result;
}
private void findDifferences(EventDeclaration newPlan, List<String> streamsToRemove, List<String> streamsToAdd)
throws CloneNotSupportedException {
List<String> oldSids = new ArrayList<String>();
for (EventDeclaration ed : this.currentCompositionPlan.getEp().clone().getCompletePattern().getEds()) {
oldSids.add(ed.getServiceId());
}
List<String> newSids = new ArrayList<String>();
for (EventDeclaration ed : newPlan.getEp().clone().getCompletePattern().getEds()) {
newSids.add(ed.getServiceId());
}
for (String s : oldSids) {
if (!newSids.contains(s)) {
streamsToRemove.add(s);
}
}
for (String s : newSids) {
if (!oldSids.contains(s)) {
streamsToAdd.add(s);
}
}
logger.info("Streams to remove: " + streamsToRemove);
logger.info("Streams to add: " + streamsToAdd);
this.liveQosStreams.addAll(streamsToAdd);
this.liveQosStreams.removeAll(streamsToRemove);
}
private void forceRealSensors(EventDeclaration plan) {
for (EventDeclaration ed : plan.getEp().getEds()) {
ed.setServiceId(RDFFileManager.defaultPrefix + ed.getServiceId().split("#")[1].split("-")[0]);
}
}
public QosVector getConstraint() {
return constraint;
}
private EventDeclaration getEDByEPId(String epId, List<EventDeclaration> eds) {
for (EventDeclaration ed : eds) {
if (ed.getEp().getID().equals(epId))
return ed;
}
return null;
}
public AdaptationMode getMode() {
return mode;
}
private List<EventDeclaration> getSortedEdByEpSize(List<EventDeclaration> eds) throws Exception {
List<EventDeclaration> results = new ArrayList<EventDeclaration>();
List<EventPattern> eps = new ArrayList<EventPattern>();
int maxCnt = 0;
for (EventDeclaration ed : eds) {
if (ed.getEp() != null) {
eps.add(ed.getEp());
} else
throw new Exception("Sorting EDs with null EP.");
}
Collections.sort(eps);
for (EventPattern ep : eps) {
results.add(this.getEDByEPId(ep.getID(), eds));
}
return results;
}
public long getUpdateCnt() {
return updateCnt;
}
public WeightVector getWeight() {
return weight;
}
private String identifyLocalServiceID(String serviceID) throws CloneNotSupportedException {
List<EventDeclaration> complexEds = new ArrayList<EventDeclaration>();
for (EventDeclaration ed : this.currentCompositionPlan.getEp().getEds()) {
if (ed.getEp() != null)
complexEds.add(ed);
else if (serviceID.equals(ed.getServiceId()))
return serviceID;
}
for (EventDeclaration ed : complexEds)
for (EventDeclaration ed2 : ed.getEp().clone().getCompletePattern().getEds())
if (ed2.getServiceId().equals(serviceID))
return ed.getServiceId();
return null;
}
@OnClose
public void onClose(Session session, CloseReason closeReason) {
logger.info(String.format("Session %s close because of %s", session.getId(), closeReason));
latch.countDown();
}
@OnMessage
public synchronized void onMessage(String message, Session session) throws Exception {
if (message.contains("stopped")) {
this.liveQosStreams.remove(message.split(" ")[1]);
} else if (message.contains("sensorId")) {
logger.warn("unexpected msg: " + message);
} else {
// logger.info("Received ...." + message);
if (!adaptationLock) {
QosUpdate qu = new Gson().fromJson(message, QosUpdate.class);
this.setUpdateCnt(this.getUpdateCnt() + 1);
String sid = qu.getCorrespondingServiceId();
boolean isNew = false;
QosVector newQos = qu.getQos();
if (this.latestQosMap.containsKey(sid)) {
if (!latestQosMap.get(sid).equals(newQos))
isNew = true;
} else
isNew = true;
QosVector currentQos = this.currentCompositionPlan.getEp().aggregateQos();
logger.debug("received qos: " + qu.getQos().getAccuracy() + "for:"
+ qu.getCorrespondingServiceId().split("#")[1] + " @" + qu.getObTimestamp());
if (isNew) {
long adaptationBegin = System.currentTimeMillis();
this.latestQosMap.put(sid, newQos);
for (EventDeclaration ed : this.currentCompositionPlan.getEp().clone().getCompletePattern()
.getEds()) {
if (ed.getServiceId().equals(sid)) {
logger.info("updating qos: " + newQos + " for: " + sid.split("#")[1] + " @"
+ qu.getObTimestamp());
ed.updateExternalQos(newQos);
break;
}
}
currentQos = this.currentCompositionPlan.getEp().aggregateQos();
logger.info("Current Total qos: " + currentQos);
if (!currentQos.satisfyConstraint(constraint)) {
logger.warn("Constraint Violated, const: " + constraint);
this.adaptationLock = true;
boolean success = false;
EventDeclaration newPlan = this.adaptation(sid);
if (this.mode != AdaptationMode.na)
if (newPlan != null) {// adaptation success
success = true;
logger.info("Adaptation result: " + newPlan.getEp().toSimpleString());
List<String> streamsToRemove = new ArrayList<String>();
List<String> streamsToAdd = new ArrayList<String>();
this.findDifferences(newPlan, streamsToRemove, streamsToAdd);
Date restartDate = this.sub.unSubscribeToQosUpdate(session, streamsToRemove, freq);
this.sub.subscribeToQosUpdate(newPlan, session, streamsToAdd, freq, restartDate);
this.updateStreamReasoningQuery(newPlan, streamsToRemove, streamsToAdd);
logger.info("current plan: " + this.currentCompositionPlan.getEp().toSimpleString());
}
this.adaptationLock = false;
long adaptationComplete = System.currentTimeMillis();
AdaptationResult ar = new AdaptationResult("AR-" + UUID.randomUUID(), success,
adaptationComplete - adaptationBegin, qu.getObTimestamp());
this.adaptations.add(ar);
currentQos = this.currentCompositionPlan.getEp().aggregateQos();
}
}
if (this.qosMap.get(qu.getObTimestamp()) == null)
this.qosMap.put(qu.getObTimestamp(), new ArrayList<QosVector>());
this.qosMap.get(qu.getObTimestamp()).add(currentQos);
// logger.info("current plan: " + this.currentCompositionPlan.getEp().toSimpleString());
}
}
}
@OnOpen
public void onOpen(Session session) {
logger.info("Connected ... " + session.getId());
this.liveQosStreams = this.sub.initializeQoSUpdates(currentCompositionPlan, session, freq, start, end);
}
public void setConstraint(QosVector constraint) {
this.constraint = constraint;
}
public void setMode(AdaptationMode mode) {
this.mode = mode;
}
public void setUpdateCnt(long updateCnt) {
this.updateCnt = updateCnt;
}
public void setWeight(WeightVector weight) {
this.weight = weight;
}
public void start(Double freq) throws Exception {
latch = new CountDownLatch(1);
try {
logger.info("connecting...");
client.connectToServer(this, new URI(uri));
// new Thread(new QosMonitor()).start();
latch.await(100, TimeUnit.SECONDS);
AdpatationMonitor am = new AdpatationMonitor(currentCompositionPlan.getComposedFor().getID(),
ACEISFactory.getACEISInstance());
new Thread(am).start();
// session.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private void updateStreamReasoningQuery(EventDeclaration newPlan, List<String> streamsToRemove,
List<String> streamsToAdd) throws Exception {
Date restartDate = SubscriptionManagerFactory.getSubscriptionManager().deregisterEventRequest(
currentCompositionPlan, false);
for (String s : streamsToRemove) {
this.sub.stopCsparqlStream(s);
}
SubscriptionManagerFactory.getSubscriptionManager().registerEventRequest(engine, newPlan, null,
this.sub.getQidSessionMap().get(this.currentCompositionPlan.getComposedFor().getID()), freq,
restartDate, this.end, null, null);
this.currentCompositionPlan = newPlan;
}
}
| true
|
c14a3defc04016db62410f629debfd66f6cbdbc7
|
Java
|
zz2200271428/viode
|
/bxw-server/src/main/java/com/znsd/instapundit/bxwserver/dao/OrderDao.java
|
UTF-8
| 669
| 1.851563
| 2
|
[] |
no_license
|
package com.znsd.instapundit.bxwserver.dao;
import com.znsd.instapundit.bean.OrderBean;
import com.znsd.instapundit.param.OrderParam;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface OrderDao {
List<OrderBean> pagingList(OrderParam param);
int getPagingCount(OrderParam param);
List<OrderBean> getMyOrder(@Param("status") Integer status,@Param("id")Integer id);
int deleteOrder(@Param("id") Integer id);
OrderBean getOrderByOid(@Param("oid") Long oid);
List<OrderBean> getCenterList();
int centerOrder(@Param("list") List<OrderBean> order);
}
| true
|