method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
45e7da39-9ea3-4f40-8622-8c0df8e81e3a
| 9
|
public int timeToCode(Object tableData)
{
int hours = -1;
int minutes = -1;
boolean afternoon = false;
try {
//Convert the given time to an actual time
if(tableData.toString().contains("PM") || tableData.toString().contains("pm"))
afternoon = true;
String temp = tableData.toString().replaceAll("[A-Za-z]*","").trim();
hours = Integer.parseInt(temp.substring(0,temp.indexOf(':')));
if(afternoon && hours <= 12)
hours = hours + 12;
minutes = Integer.parseInt(temp.substring(temp.indexOf(':')+1,temp.length()));
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Not a valid time entry, should follow the form HH:MM [AM/PM], such as 1:30 PM for 13:30");
return -1;
}
if(hours < 0 || hours > 23 || minutes < 0 || minutes > 59)
return -1;
return hours*100+minutes;
}
|
00627386-6df6-4246-b714-0c795ed45302
| 3
|
*/
BSTNode find(BSTNode tree, K key) {
// Special case: Empty tree. Give up
if (tree == null) {
return null;
} // if (tree == null)
else {
int tmp = order.compare(key, tree.key);
if (tmp == 0) {
return tree;
} else if (tmp < 0) {
return find(tree.smaller, key);
} else {
return find(tree.larger, key);
} // if the key is larger than the key at the node
} // if the tree is nonempty
}
|
791955fa-b68c-442c-b68c-19a04ac472e7
| 9
|
@Override
public String generateInnerPaging(PageBean pageBean, int showPages) {
StringBuilder htmlBuf = new StringBuilder();
PaginationGenUtil genUtil = PaginationGenUtil.getInstance();
htmlBuf.append(genUtil.generateCommonPagingPart(pageBean));
if (pageBean.getCurrentPage() > 1) {
htmlBuf.append(genUtil.generatePageAnchor(1, "first"));
htmlBuf.append(genUtil.generatePageAnchor(pageBean.getPreviousPage(), "previous"));
}
int currentPageOffset = showPages / 2;
int startPosition = 1;
if (pageBean.getCurrentPage() - currentPageOffset > 0) {
startPosition = pageBean.getCurrentPage() - currentPageOffset;
}
int endPosition = pageBean.getCurrentPage() + currentPageOffset;
if (showPages % 2 == 0) {
endPosition--;
}
if (endPosition > pageBean.getTotalPage()) {
endPosition = pageBean.getTotalPage();
}
if (endPosition < showPages) {
endPosition = showPages;
}
for (int pageInd = startPosition; pageInd >= startPosition && pageInd <= endPosition; pageInd++) {
if (pageInd == pageBean.getCurrentPage()) {
htmlBuf.append("<strong>").append(pageInd).append("</strong>").append(PaginationGenUtil.LINE_SEPARATOR);
} else {
htmlBuf.append(genUtil.generatePageAnchor(pageInd, "" + pageInd));
}
}
if (pageBean.getCurrentPage() < pageBean.getTotalPage()) {
htmlBuf.append(genUtil.generatePageAnchor(pageBean.getNextPage(), "next"));
htmlBuf.append(genUtil.generatePageAnchor(pageBean.getTotalPage(), "last"));
}
return htmlBuf.toString();
}
|
838c79a2-8c28-44f8-88c2-108b1e085cf3
| 2
|
@Override
public double[][] solve(double[] T_0, int n, double k, double u, double dt, double dx) {
double[][] ans = new double[n][];
int m = T_0.length;
ans[0] = T_0;
for (int layer = 1; layer < n; layer++) {
double[] T = ans[layer - 1];
double[] curLayer = new double[m];
for (int i = 1; i < m - 1; i++)
curLayer[i] = T[i] + dt * (k * (T[i + 1] - 2 * T[i] + T[i - 1]) / dx / dx - u * (T[i + 1] - T[i]) / dx);/*
dt k (T[i + 1, n] - 2T[i, n] + T[i - 1, n]) dt u (T[i + 1, n] - T[i, n])
T[i, n + 1] = T[i, n] + ——————————————————————————————————————————— - ————————————————————————————
dx * dx dx */
curLayer[0 ] = T[0 ];
curLayer[m - 1] = T[m - 1];
ans[layer] = curLayer;
}
return ans;
}
|
adea5581-a6bd-4023-9ae1-259154eddd78
| 2
|
@Override
public int hashCode() {
int result = prpPosId != null ? prpPosId.hashCode() : 0;
result = 31 * result + (prpMoaTipo != null ? prpMoaTipo.hashCode() : 0);
result = 31 * result + prpMoaConsec;
result = 31 * result + prpIdElemento;
return result;
}
|
d17e60d0-10ac-4175-bf42-792e918e6a96
| 5
|
public static void main(String[] args)
{
System.out.println("Starting failure example 2...");
try
{
if (args.length < 1)
{
System.out.println("Usage: java ResFailureEx02 network_ex02.txt");
return;
}
//////////////////////////////////////////
// First step: Initialize the GridSim package. It should be called
// before creating any entities. We can't run this example without
// initializing GridSim first. We will get a run-time exception
// error.
// a flag that denotes whether to trace GridSim events or not.
boolean trace_flag = false; // dont use SimJava trace
int num_user = 20; // number of grid users
Calendar calendar = Calendar.getInstance();
// Initialize the GridSim package
System.out.println("Initializing GridSim package");
GridSim.init(num_user, calendar, trace_flag);
trace_flag = true;
//////////////////////////////////////////
// Second step: Builds the network topology among Routers.
String filename = args[0]; // get the network topology
System.out.println("Reading network from " + filename);
LinkedList routerList = NetworkReader.createFIFO(filename);
//////////////////////////////////////////
// Third step: Creates one RegionalGISWithFailure entity,
// linked to a router in the topology
Router router = null;
double baud_rate = 100000000; // 100Mbps, i.e. baud rate of links
double propDelay = 10; // propagation delay in milliseconds
int mtu = 1500; // max. transmission unit in byte
int totalMachines = 16; // num of machines each resource has
String NAME = "Ex02_"; // a common name
String gisName = NAME + "Regional_GIS"; // GIS name
// a network link attached to this regional GIS entity
Link link = new SimpleLink(gisName + "_link", baud_rate,
propDelay, mtu);
// HyperExponential: mean, standard deviation, stream
// how many resources will fail
HyperExponential failureNumResPattern =
new HyperExponential(totalMachines / 2, totalMachines, 4);
// when they will fail
HyperExponential failureTimePattern =
new HyperExponential(25, 100, 4);
// how long the failure will be
HyperExponential failureLengthPattern =
new HyperExponential(20, 25, 4); // big test: (20, 100, 4);
// creates a new Regional GIS entity that generates a resource
// failure message according to these patterns.
RegionalGISWithFailure gis = new RegionalGISWithFailure(gisName,
link, failureNumResPattern, failureTimePattern,
failureLengthPattern);
gis.setTrace(trace_flag); // record this GIS activity
// link these GIS to a router
router = NetworkReader.getRouter("Router0", routerList);
linkNetwork(router, gis);
// print some info messages
System.out.println("Created a REGIONAL GIS with name " + gisName +
" and id = " + gis.get_id() + ", connected to " +
router.get_name() );
//////////////////////////////////////////
// Fourth step: Creates one or more GridResourceWithFailure
// entities, linked to a router in the topology
String sched_alg = "SPACE"; // use space-shared policy
int totalResource = 6; // number of resources
ArrayList resList = new ArrayList(totalResource);
// Each resource may have different baud rate,
// totalMachine, rating, allocation policy and the router to
// which it will be connected. However, in this example, we assume
// all have the same properties for simplicity.
int totalPE = 4; // num of PEs each machine has
int rating = 49000; // rating (MIPS) of PEs
int GB = 1000000000; // 1 GB in bits
baud_rate = 2.5 * GB;
for (int i = 0; i < totalResource; i++)
{
// gets the router object from the list
router = NetworkReader.getRouter("Router0", routerList);
// creates a new grid resource
String resName = NAME + "Res_" + i;
GridResourceWithFailure res = createGridResource(resName,
baud_rate, propDelay, mtu, totalPE, totalMachines,
rating, sched_alg);
// add a resource into a list
resList.add(res);
res.setRegionalGIS(gis); // set the regional GIS entity
res.setTrace(trace_flag); // record this resource activity
// link a resource to this router object
linkNetwork(router, res);
System.out.println("Created a RESOURCE (" + totalMachines +
" machines, each with " + totalPE + " PEs) with name = " +
resName + " and id = " + res.get_id() +
", connected to router " + router.get_name() +
" and registered to " + gis.get_name() );
}
//////////////////////////////////////////
// Fifth step: Creates one or more GridUserFailure entities,
// linked to a router of the topology
int totalGridlet = 5; // total jobs
double pollTime = 100; // time between polls
int glSize = 100000; // the size of gridlets (input/output)
int glLength = 42000000; // the length (MI) of gridlets
// gets the router object from the list
router = NetworkReader.getRouter("Router0", routerList);
for (int i = 0; i < num_user; i++)
{
String userName = NAME + "User_" + i;
// a network link attached to this entity
Link link2 = new SimpleLink(userName + "_link", baud_rate,
propDelay, mtu);
// only keeps track activities from User_0
if (i != 0) {
trace_flag = false;
}
GridUserFailureEx02 user = new GridUserFailureEx02(userName, link2,
pollTime, glLength, glSize, glSize, trace_flag);
user.setRegionalGIS(gis); // set the regional GIS entity
user.setGridletNumber(totalGridlet);
// link a resource to this router object
linkNetwork(router, user);
System.out.println("Created a USER with name " + userName +
" and id = " + user.get_id() + ", connected to " +
router.get_name() + ", and with " + totalGridlet +
" gridlets. Registered to " + gis.get_name() );
}
System.out.println();
//////////////////////////////////////////
// Sixth step: Starts the simulation
GridSim.startGridSimulation();
System.out.println("\nFinish failure example 2... \n");
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Unwanted errors happen");
}
}
|
3f593b69-4f81-4ae6-b697-02dc686bf547
| 3
|
public Display findDisplayFor(Class cl)
{
// Go up through the class hierarchy for obj and see
// if there is a display for its class or superclasses.
if (cl == Object.class)
return defaultDisplay;
Display display = map.get(cl);
if (display != null)
return display;
display = createDisplay(cl);
if (display != null)
{
map.put(cl, display);
return display;
}
display = findDisplayFor(cl.getSuperclass());
map.put(cl, display);
return display;
}
|
5012e112-7a02-4a66-b491-5fff1dc8c436
| 2
|
public List<ParkClass> resultSet(List<ParkClass> list)
{
List<ParkClass> result = new ArrayList();
int count = list.size();
int i;
for(i=0;i<count;i++)
{
if(GetDistance(y, x, list.get(i).getLatitude(), list.get(i).getLongitude())<=3)
{
result.add(list.get(i));
}
}
return result;
}
|
1e214cd8-d138-411a-a57c-e8048fc7f08e
| 7
|
public static void topDiamond(){
final int ITER_NUM = 2;
int cnt = ITER_NUM - 1;
for (int i = ITER_NUM; i >=0; i--, cnt++) { //overall itration
System.out.print("|");
for (int j = 1; j <= i; j++) { //dot generator
System.out.print(".");
}
for (int j = 1; j <=cnt; j++) {
System.out.print("/\\");
}
for (int j = 1; j <= i; j++) { //dot generator
System.out.print(".");
}
for (int j = 1; j <= i; j++) { //dot generator
System.out.print(".");
}
for (int j = 1; j <=cnt; j++) {
System.out.print("/\\");
}
for (int j = 1; j <= i; j++) { //dot generator
System.out.print(".");
}
System.out.print("|");
System.out.println();
}
cnt = 1;
}
|
5e94d694-bf45-4e84-8cd3-9731984f339b
| 1
|
public void setPWResetFontsize(int fontsize) {
if (fontsize <= 0) {
this.pwResetFontSize = UIFontInits.PWRESET.getSize();
} else {
this.pwResetFontSize = fontsize;
}
somethingChanged();
}
|
1c49051a-88bc-40b0-8d3b-8fe31e2651c9
| 7
|
public void transportClosed() {
boolean changed=false;
lock.lock();
try {
for(Map.Entry<Address, Rsp<T>> entry: rsps.entrySet()) {
Rsp<T> rsp=entry.getValue();
if(rsp != null && !(rsp.wasReceived() || rsp.wasSuspected() || rsp.wasUnreachable())) {
rsp.setException(new IllegalStateException("transport was closed"));
num_received++;
changed=true;
}
}
if(changed && responsesComplete()) {
complete(this.rsps);
corrDone();
}
}
finally {
lock.unlock();
}
}
|
67c20797-7b9e-416a-a0a2-98e228b58e2b
| 0
|
public Ticket[] getTickets() {
return this._tickets;
}
|
225c7e20-2242-44b1-a15d-431a83c0f0a6
| 5
|
private byte offer(SmallPacket d) throws CallbackException {
System.out.println("Offering");
Byte ack = sequencer.put(d);
if (ack == null)
return 0;
System.out.println("Getting packets");
LinkedList<DataPacket> readyPackets = sequencer.getPackets(d
.getSource());
System.out.println("YAY! " + readyPackets.size()
+ " packets to process! WOOOO!");
LinkedList<DataPacket> buffer = new LinkedList<DataPacket>();
System.out.println("Looping packets");
while (!readyPackets.isEmpty()) {
if (!readyPackets.peek().hasMore()) {
buffer.add(readyPackets.poll());
communication.newPacket(processPackets(buffer));
} else {
while (!readyPackets.isEmpty() && readyPackets.peek().hasMore()) {
buffer.add(readyPackets.poll());
}
buffer.add(readyPackets.poll());
communication.newPacket(processPackets(buffer));
}
buffer = new LinkedList<DataPacket>();
}
return ack;
}
|
bdf2a047-b90e-4514-adea-e18fd85b75bc
| 7
|
@Override
public HashMap<String,ClassNode> refactor(){
Deob.deobOutput.add("* Starting Method Removal*"+System.getProperty("line.separator"));
System.out.println("* Starting Method Removal*");
List<MethodWrapper>remove = getRedundantMethods();
List<MethodNode> toRemove = new ArrayList<>();
for(MethodWrapper wrap : remove){
for(ClassNode node : classes.values()){
if(!wrap.owner.equals(node.name))
continue;
for (MethodNode mn : (Iterable<MethodNode>) node.methods) {
if(mn.name.equals(wrap.name) && mn.desc.equals(wrap.desc))
toRemove.add(mn);
}
for(MethodNode mn : toRemove)
node.methods.remove(mn);
}
}
Deob.deobOutput.add("* Method Removal Finished*"+System.getProperty("line.separator"));
System.out.println("* Method Removal Finished*");
return classes;
}
|
c0526007-14f7-49ee-9c63-af56b19d9d1f
| 7
|
public TermWin(Shell parent)
{
super (parent);
port = null;
self.addShellListener(new ShellAdapter()
{
public void shellClosed(ShellEvent de)
{
rxRun = false;
if (port != null)
{
port.close();
}
self.getParent().setEnabled(true);
}
});
/* close the terminal */
close.addMouseListener(new MouseAdapter()
{
public void mouseUp(MouseEvent e)
{
self.close();
}
});
/* pause the terminal */
pause.addMouseListener(new MouseAdapter()
{
public void mouseUp(MouseEvent e)
{
pauseTerm = pause.getSelection();
}
});
/* clear the terminal text */
clear.addMouseListener(new MouseAdapter()
{
public void mouseUp(MouseEvent e)
{
terminal.setText("");
}
});
/* define the thread for receiving data */
rxThread = new Thread()
{
public void run()
{
while (!self.isDisposed() && rxRun)
{
try
{
int buff = rx.read();
if (buff < 0)
{
break;
}
inChar = (char)buff;
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
port.close();
self.getDisplay().syncExec(new Runnable()
{
public void run()
{
MessageBox err = new MessageBox(self, SWT.ICON_ERROR);
err.setMessage("Unable to read from port.\nCheck connection and port.");
err.open();
self.close();
}
});
}
/* if not paused, update the terminal */
if (!pauseTerm)
{
self.getDisplay().syncExec(new Runnable()
{
public void run()
{
/* make sure shell still exists */
if (!self.isDisposed())
{
terminal.append(String.valueOf(inChar));
}
}
});
}
}
}
};
}
|
fb8d8d28-a24c-49f8-9758-02a8143575e2
| 2
|
public void openResultaten() {
for (views.panels.GekozenAntwoord gk : gekozenAntwoorden)
gk.geefLijntje(true);
middenvlak.removeAll();
for (JButton button : buttons)
button.setEnabled(false);
middenvlak.revalidate();
middenvlak.repaint();
middenvlak.add(new ResultatenScherm(spel));
}
|
85113e30-fab3-4a15-92ad-d887542f07fd
| 4
|
public boolean doesThreaten(Point p){
char c=aiarr[(int)p.getX()][(int)p.getY()].toString().charAt(0);
if(c=='B')c='W';
else c='B';
checkThreats(gameBoard,c);
for(int i=0;i<numThreatening;i++){
if(locThreatening[i].getX()==p.getX() &&locThreatening[i].getY()==p.getY()){
return true;
}
}
return false;
}
|
fd5de35a-c085-4051-9cad-8efbc4fc2751
| 8
|
public void getConnection() throws IOException
{
Socket socket;
Client client;
byte[] respons;
byte[] tmpRespons;
while(true)
{
socket = this.socket.accept();
client = new Client(socket, "", new String(Server.secKey), this);
// TODO creats a key exchange
client.writes(Server.secKey);
byte[] inp = client.reads();
// for(byte b : inp)
// System.out.print(b + ", ");
// System.out.println();
byte[] dec = this.chipher.decrypt(inp);
// for(byte b : dec)
// System.out.print(b + ", ");
// System.out.print("\n" + new String(dec));
//
// System.out.println("\n###########################");
Packet com = PacketFactory.build(dec);
// unkown command
if(com == null)
{
System.out.println("unkown command");
System.out.println("new msg.length=" + inp.length);
for(byte b : inp)
System.out.print(b + ", ");
System.out.print("\ndecoded: ");
for(byte b : dec)
System.out.print(b + ", ");
System.out.println("\n###########################");
client.killConnection();
}
else
{
// get respons
tmpRespons = com.doTask(this);
// encrypt respons
respons = com.getPacket(this.chipher);
// sends respons to client
client.writes(respons);
// client didt tries to login
if(com.getCommand() != 2)
{
client.killConnection();
}
// the client successfull log in
else if(tmpRespons != null && tmpRespons.length == 1 && tmpRespons[0] == 1)
{
client.setUser(((Login) com).getUsername());
this.clients.put(client.getUser(), client);
new Thread(client).start();
}
}
}
}
|
8aca09d8-b1c1-48d4-b660-d119753ee14a
| 4
|
public void playerAction(int startIndex) {
List<Player> playerList = game.getPlayerList();
game.tableView.updateAllPlayer(playerList);
game.tableView.appendLog(game.getBoardCards().toString());
for(int i = startIndex; !game.isOnlyOneAlive() && !game.isAllCall(); i = (i+1)%playerList.size()) {
Player player = playerList.get(i);
// MassageSender.updateView(playerList, game.getUpdateMassage(player));
MassageSender.updateView(player, game.getUpdateMassage(player));
game.tableView.setActingPlayer(playerList.indexOf(player));
game.tableView.updatePlayer(player, playerList.indexOf(player));
String availableAction = game.getPlayerAvalableAction(i);
if(null == availableAction) {
continue;
}
// game.printGameState();
MassageSender.yourTurn(player, availableAction);
MassageDecoder.process(game, player);
game.tableView.updatePlayer(player, playerList.indexOf(player));
System.out.println(availableAction);
System.out.println(player.getPrintMsg());
// game.printGameState();
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
next();
}
|
91e6adb5-a545-47ee-949a-aa339d735783
| 2
|
public void Start(String id, String serverIp) {
try {
// Ͽ ûѴ.
Socket socket = new Socket(serverIp, 7777);
System.out.println(" Ǿϴ.");
Thread sender = new Thread(new ClientSender(socket, id));
Thread receiver = new Thread(new ClientReceiver(socket));
// Ŭ̾Ʈ
sender.start(); // sender
receiver.start(); // receiver
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
}
}
|
6f8701d0-89e5-45d8-a279-96b5e0eac08a
| 7
|
@Test
public void placeFigures() {
HashMap<String, Integer> figureQuantityMap = new HashMap<>();
figureQuantityMap.put(BISHOP.toString(), 4);
FiguresChain figuresChain = new Bishop(figureQuantityMap);
FiguresChain figuresChain1 = new Queen(figureQuantityMap);
figuresChain.setNextFigure(figuresChain1);
Set<String> objects = new HashSet<>();
objects.add(EMPTY_BOARD_SIZE_6);
Set<String> boards = figuresChain.placeFigures(objects.stream()).collect(Collectors.toSet());
assertThat("figures are standing on different places", boards.contains("bbbb..\n" +
"xxxxx.\n" +
"xxxxxx\n" +
"x..xxx\n" +
"....xx\n" +
".....x\n"),
is(true));
assertThat("all elements are not present on each board", boards
.parallelStream()
.filter(board -> !board.contains(KING.getFigureAsString())
&& !board.contains(QUEEN.getFigureAsString())
&& !board.contains(ROOK.getFigureAsString())
&& !board.contains(KNIGHT.getFigureAsString())
&& board.contains(FIELD_UNDER_ATTACK_STRING)
&& board.contains(EMPTY_FIELD_STRING)
&& board.contains(BISHOP.getFigureAsString())
&& leftOnlyFigures(board).length() == 4)
.map(e -> 1)
.reduce(0, (x, y) -> x + y), is(16428));
}
|
4aae512b-e7a0-407d-97ce-7569c5685606
| 5
|
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // FIRST_NAME
return FIRST_NAME;
case 2: // LAST_NAME
return LAST_NAME;
case 3: // STATUS
return STATUS;
case 4: // ID
return ID;
case 5: // EMAIL
return EMAIL;
default:
return null;
}
}
|
3e062cc5-ba14-47ae-b15e-9a57f3a646a2
| 6
|
@Override
public void run() {
try {
URL pagina = new URL("http://chapuzas.comocreartuweb.es/documentos/version.txt");
HttpURLConnection con = (HttpURLConnection) pagina.openConnection();
con.connect();
InputStreamReader in = new InputStreamReader((InputStream) con.getContent());
BufferedReader buff = new BufferedReader(in);
String versionI = buff.readLine();
if (version == null ? versionI != null : !version.equals(versionI)) {
int g = JOptionPane.showConfirmDialog(null, "Hay una nueva version "
+ "de Vnomina disponible, ¿quieres descargarla?");
if (g == 0) {
UtilNavegador.abrirURL("http://sourceforge.net/projects/vnomina/files/latest/download?source=directory");
}
} else if (version == null ? versionI == null : version.equals(versionI)) {
JOptionPane.showMessageDialog(null,
"Ya tienes la ultima version del programa",
"Aviso",
JOptionPane.INFORMATION_MESSAGE);
}
} catch (IOException ex) {
JOptionPane.showMessageDialog(null,
"Chungo, Ha fallado la conexion",
"Error",
JOptionPane.ERROR_MESSAGE);
} finally {
btnBuscar.setText("Buscar actualizaciones");
hilo = null;
}
}
|
c3e9ff86-309e-4450-a83f-e85b707d1737
| 2
|
public static double lireDecimal(String message) {
double d = 0;
boolean ok;
do {
ok = true;
try {
System.out.print(message);
clavier = new Scanner(System.in);
d = clavier.nextDouble();
} catch (Exception e) {
System.out.println("Mauvais format");
ok = false;
}
} while (!ok);
return d;
}
|
6e11e9f0-4ac5-4794-93da-f6c12a940781
| 4
|
public void renderPhysics() {
Array bodies = new Array();
for (int i = 0; i < deadBodies.size(); ++i) {
try {
world.getBodies(bodies);
if (bodies.contains(deadBodies.get(i), true)) {
world.destroyBody(deadBodies.get(i));
}
} catch (NullPointerException e) {
System.out.println("ERROR : " + e.getMessage());
}
}
deadBodies.clear();
world.step(1.0f / 60.0f, 6, 2);
for (int i = 0; i < deadBodies.size(); ++i) {
world.destroyBody(deadBodies.get(i));
}
deadBodies.clear();
}
|
a1e97351-2397-44d5-adf7-f17929148d86
| 1
|
@Override
public void characters (char[] ch, int start, int length) {
if(bconverse == true){
String str = new String(ch,start,length);
temp =temp + " " +str.trim();
temp = temp.replaceAll("(?i)(<)(.+?)(>)"," ");
temp = temp.replaceAll("\\s+", " ");
}
}
|
4eac6ee3-51e9-4153-93ed-dd0110bbbaca
| 2
|
public static int indexOf(byte[] s, byte w) {
for (int i = 0; i < s.length; i++)
if (s[i] == w)
return i;
return -1;
}
|
d6226a5f-7d17-4885-b565-c0690e7d8a99
| 5
|
@Override
public MoveResult makeMove(HantoPieceType pieceType, HantoCoordinate from,
HantoCoordinate to) throws HantoException {
MoveResult moveResult = null;
if (from == null && to == null){
switch(gameManager.getPlayerTurn()){
case BLUE:
moveResult = MoveResult.RED_WINS;
break;
case RED:
moveResult = MoveResult.BLUE_WINS;
break;
}
} else {
moveResult = super.makeMove(pieceType, from, to);
}
if (gameOver){
throw new HantoException("The game is over bro!");
} else {
gameOver = isOver(moveResult);
}
return moveResult;
}
|
c3dd4809-a4c2-4d5b-93ee-05edca227b32
| 1
|
public Permission getPermissions() {
if (permHook == null) {
throw new NullPointerException("Permissions was called but hasn't been setup!");
}
return permHook;
}
|
d98fdb19-a438-44f7-afee-085851b5df25
| 7
|
private void btnInserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInserActionPerformed
if ("0".equals(txtId.getText())||"".equals(txtId.getText())) {
JOptionPane.showMessageDialog(this, "Ingrese un Id valida");
}
else if ("".equals(txtNombre.getText())) {
JOptionPane.showMessageDialog(this, "Ingrese un Nombre");
}
else if ("".equals(txtApe.getText())) {
JOptionPane.showMessageDialog(this, "Ingrese un Apellido");
}
else if ("".equals(txtCed.getText())) {
JOptionPane.showMessageDialog(this, "Ingrese un numero de Cedula");
}
else{
usuario.getUsuario().setId(Integer.parseInt(txtId.getText()));
usuario.getUsuario().setNombre(txtNombre.getText());
usuario.getUsuario().setApellido(txtApe.getText());
usuario.getUsuario().setCedula(txtCed.getText());
try {
usuario.Insertar();
JOptionPane.showMessageDialog(this, "Dato insertado correctamente");
if (this.Tabla_datos.isVisible()) {
tabla();
} else {
}
}
catch (SQLException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
}//GEN-LAST:event_btnInserActionPerformed
|
a18cfe5a-dfd7-4fe1-bfd5-500ca4c29eaf
| 3
|
public static Units[] getGenerals() {
ArrayList<Units> units = new ArrayList<Units>();
try {
Statement s1 = conn.createStatement();
ResultSet rs = s1
.executeQuery("Exec getGeneral");
if (rs != null) {
while (rs.next()) {
String unitName = rs.getString("unitName");
int ability = rs.getInt("ability");
int attack = rs.getInt("attack");
int defense = rs.getInt("defense");
int attackRange = rs.getInt("attackRange");
int type = rs.getInt("type");
String name = rs.getString("name");
String genName = rs.getString("genName");
int mobility = rs.getInt("mobility");
int life = rs.getInt("life");
units.add(new Units(unitName, ability, attack, defense, attackRange, type, name, genName, mobility, life));
System.out.println(unitName + " " + ability + " " + attack
+ " " + defense + " " + attackRange + " " + type
+ " " + name + " " + genName + " " + mobility + " "
+ life);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return units.toArray(new Units[units.size()]);
}
|
54ebb6eb-7d21-4228-97ed-1495ace56125
| 3
|
public FruitManager()
{
if(fruits.isEmpty())
{
try {
loadFruits();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
instance = this;
}
|
6fe75a74-8fbc-4d4e-bcc8-42ee7a66d565
| 4
|
public boolean checkLegal(String prev_pos, String new_pos)
{
if((prev_pos.substring(0,1).equals(new_pos.substring(0,1)))&&(prev_pos.substring(1).equals(new_pos.substring(1))==false))//up down
{
return true;
}
else if((prev_pos.substring(0,1).equals(new_pos.substring(0,1))==false)&&(prev_pos.substring(1).equals(new_pos.substring(1))))//left right
{
return true;
}
return false;
}
|
8e4e4c18-1be8-4b93-95f2-3fff88bbdcd7
| 0
|
public static void main(String[] args) {
IceCream ic = new IceCream();
Sundae s = ic.getSundae();
}
|
92eaf9fb-2f0c-4cc9-ad5a-f9131354ed76
| 9
|
static final void method2255(int i, int i_3_, byte i_4_, int i_5_,
int i_6_, int i_7_, int i_8_) {
Class117.method1070((byte) 117, i);
anInt3812++;
if (i_4_ >= -65)
method2255(-118, -20, (byte) -121, 100, -62, 77, -119);
int i_9_ = 0;
int i_10_ = -i_5_ + i;
if ((i_10_ ^ 0xffffffff) > -1)
i_10_ = 0;
int i_11_ = i;
int i_12_ = -i;
int i_13_ = i_10_;
int i_14_ = -i_10_;
int i_15_ = -1;
int i_16_ = -1;
int[] is = AnimationDefinition.anIntArrayArray255[i_6_];
int i_17_ = i_3_ + -i_10_;
int i_18_ = i_10_ + i_3_;
Class135_Sub2.method1156(-27, i_17_, is, -i + i_3_, i_8_);
Class135_Sub2.method1156(-27, i_18_, is, i_17_, i_7_);
Class135_Sub2.method1156(-27, i + i_3_, is, i_18_, i_8_);
while (i_11_ > i_9_) {
i_16_ += 2;
i_15_ += 2;
i_14_ += i_16_;
i_12_ += i_15_;
if (i_14_ >= 0 && (i_13_ ^ 0xffffffff) <= -2) {
GameBuffer.anIntArray9757[i_13_] = i_9_;
i_13_--;
i_14_ -= i_13_ << -840432831;
}
i_9_++;
if (i_12_ >= 0) {
i_11_--;
i_12_ -= i_11_ << -2028572287;
if (i_10_ <= i_11_) {
int[] is_19_ = AnimationDefinition.anIntArrayArray255[i_11_ + i_6_];
int[] is_20_ = AnimationDefinition.anIntArrayArray255[i_6_ + -i_11_];
int i_21_ = i_3_ - -i_9_;
int i_22_ = -i_9_ + i_3_;
Class135_Sub2.method1156(-27, i_21_, is_19_, i_22_, i_8_);
Class135_Sub2.method1156(-27, i_21_, is_20_, i_22_, i_8_);
} else {
int[] is_23_ = AnimationDefinition.anIntArrayArray255[i_6_ - -i_11_];
int[] is_24_ = AnimationDefinition.anIntArrayArray255[-i_11_ + i_6_];
int i_25_ = GameBuffer.anIntArray9757[i_11_];
int i_26_ = i_9_ + i_3_;
int i_27_ = i_3_ - i_9_;
int i_28_ = i_3_ - -i_25_;
int i_29_ = -i_25_ + i_3_;
Class135_Sub2.method1156(-27, i_29_, is_23_, i_27_, i_8_);
Class135_Sub2.method1156(-27, i_28_, is_23_, i_29_, i_7_);
Class135_Sub2.method1156(-27, i_26_, is_23_, i_28_, i_8_);
Class135_Sub2.method1156(-27, i_29_, is_24_, i_27_, i_8_);
Class135_Sub2.method1156(-27, i_28_, is_24_, i_29_, i_7_);
Class135_Sub2.method1156(-27, i_26_, is_24_, i_28_, i_8_);
}
}
int[] is_30_ = AnimationDefinition.anIntArrayArray255[i_6_ + i_9_];
int[] is_31_ = AnimationDefinition.anIntArrayArray255[-i_9_ + i_6_];
int i_32_ = i_3_ - -i_11_;
int i_33_ = i_3_ - i_11_;
if (i_10_ > i_9_) {
int i_34_
= ((i_13_ ^ 0xffffffff) <= (i_9_ ^ 0xffffffff) ? i_13_
: GameBuffer.anIntArray9757[i_9_]);
int i_35_ = i_34_ + i_3_;
int i_36_ = i_3_ + -i_34_;
Class135_Sub2.method1156(-27, i_36_, is_30_, i_33_, i_8_);
Class135_Sub2.method1156(-27, i_35_, is_30_, i_36_, i_7_);
Class135_Sub2.method1156(-27, i_32_, is_30_, i_35_, i_8_);
Class135_Sub2.method1156(-27, i_36_, is_31_, i_33_, i_8_);
Class135_Sub2.method1156(-27, i_35_, is_31_, i_36_, i_7_);
Class135_Sub2.method1156(-27, i_32_, is_31_, i_35_, i_8_);
} else {
Class135_Sub2.method1156(-27, i_32_, is_30_, i_33_, i_8_);
Class135_Sub2.method1156(-27, i_32_, is_31_, i_33_, i_8_);
}
}
}
|
22e3f88b-d180-45a8-8702-cfb797e30f0f
| 9
|
public void setValue(Object aKey, Object aValue)
{
if(aKey == null) throw new IllegalArgumentException("Client property key cannot be null.");
final Object lOldValue = values.get(aKey);
// Only take action when the new value is different from the old value.
// If nothing changes nobody should be asked or notified about the change.
if(((aValue == null) && (aValue != lOldValue)) ||
((aValue != null) && (!aValue.equals(lOldValue))))
{
if(constrained && (bus != null))
{
final VetoablePropertyChangeEvent lEvent = new VetoablePropertyChangeEvent(source, aKey.toString(), lOldValue, aValue);
bus.publish(lEvent);
}
if(aValue == null) values.remove(aKey);
else values.put(aKey, aValue);
if(bus != null)
{
PropertyChangeEvent lEvent = new PropertyChangeEvent(source, aKey.toString(), lOldValue, aValue);
bus.publish(lEvent);
}
}
}
|
56c9ec89-1e11-45cd-81e7-938903c45355
| 8
|
public ManagePadsController(List groupIds, final MainViewController mainViewController) {
final ManagePadsView managePadView = new ManagePadsView();
managePadView.setGroupComboBoxValues(groupIds);
managePadView.setGroupComboBoxActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox) e.getSource();
String groupId = (String) cb.getSelectedItem();
List<String> pads = null;
try {
if (cb.getSelectedIndex() == 1) {
List<String> allPads = EPLite.getInstance().getAllPads();
pads = new ArrayList<String>();
for (int i = 0; i < allPads.size(); i++) {
if (!allPads.get(i).toString().contains("$")) {
pads.add(allPads.get(i));
}
}
} else if (cb.getSelectedIndex() > 1) {
pads = EPLite.getInstance().getAllPads(groupId);
}
} catch (EPLiteException epEx) {
epEx.printStackTrace();
JOptionPane.showMessageDialog(managePadView, "Error: " + epEx.getMessage(), "Error listing pads", JOptionPane.ERROR_MESSAGE);
}
managePadView.setPadComboBoxValues(pads);
}
});
managePadView.setOpenButtonListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String padName = managePadView.getPadNamePadComboBox();
if (padName != null) {
mainViewController.openPad(padName);
managePadView.dispose();
}
}
});
managePadView.setDeleteButtonListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String padName = managePadView.getPadNamePadComboBox();
if (padName != null) {
try {
EPLite.getInstance().deletePad(padName);
JOptionPane.showMessageDialog(managePadView, "Pad '" + padName + "' was deleted", "Pad deleted",
JOptionPane.INFORMATION_MESSAGE);
managePadView.dispose();
} catch (EPLiteException epEx) {
epEx.printStackTrace();
JOptionPane.showMessageDialog(managePadView, "Error: " + epEx.getMessage(), "Error deleting pad", JOptionPane.ERROR_MESSAGE);
}
}
}
});
managePadView.setVisible(true);
}
|
fa900dcc-672f-45ef-a4a9-207315542dce
| 2
|
private String userTopic(String userInput)
{
String userBasedResponse = "";
int randomUserTopic = (int) (Math.random() * 6);
switch (randomUserTopic)
{
case 1:
userBasedResponse = myUser.hasTattoos() + " is the response to tattoos :D";
break;
case 0:
userBasedResponse = myUser.getUserName() + " is a silly name :P";
break;
default:
userBasedResponse = myUser.getAge() + " is realllly reallllllly old";
break;
}
return userBasedResponse;
}
|
7217d1eb-2219-44e9-ba35-3bd88cad5aa2
| 9
|
public static void main(String[] args) {
try {
DistriControl control = new DistriControl();
FileInputStream handlesFile = new FileInputStream(
DistriControlTest.class.getResource(HANDLES_FILE).getPath());
BufferedReader handlesReader = new BufferedReader(
new InputStreamReader(handlesFile));
String handleHost = handlesReader.readLine();
while (handleHost != null) {
control.createHandle(handleHost, "tamu_ecologyLab");
DistriHandle handle = control.getHandleByHost(handleHost);
handle.setKeyPath("/Users/Chen/.ssh/id_rsa");
handle.setKnownHosts("/Users/Chen/.ssh/known_hosts");
try {
handle.connect();
} catch (Exception e) {
e.printStackTrace();
}
handleHost = handlesReader.readLine();
if (handleHost == null)
break;
}
handlesReader.close();
FileInputStream urlsFile = new FileInputStream(
DistriControlTest.class.getResource(URLS_FILE).getPath());
BufferedReader urlsReader = new BufferedReader(
new InputStreamReader(urlsFile));
ArrayList<String> urls = new ArrayList<String>();
String url = urlsReader.readLine();
while (url != null) {
urls.add(url);
url = urlsReader.readLine();
if (url == null)
break;
}
urlsReader.close();
totalCount = urls.size();
remainCount = totalCount;
lock = new Object();
System.out.println(String.format("Remain: %d", remainCount));
final Date startTime = new Date();
for (String theUrl : urls) {
final DistriTask task = new DistriTask("", theUrl, 10, 1);
task.setLinkSelector("a[href~=^\\/patents\\/[A-Z0-9]+$]");
task.setFinishCallback(new DistriTask.FinishCallback() {
public void execute(DistriResult result) {
synchronized (lock) {
remainCount += result.getQueryLinks().size();
}
}
});
task.setFailCallback(new DistriTask.FailCallback() {
public void execute(Exception e, String s) {
e.printStackTrace();
}
});
task.setTerminateCallback(new DistriTask.TerminateCallback() {
public void execute() {
totalLatency += task.timeSinceInitial();
totalCount++;
synchronized (lock) {
System.out.println(String.format("Remain: %d", remainCount));
if (--remainCount == 0) {
Date endTime = new Date();
long diff = endTime.getTime()
- startTime.getTime();
double throughput = (double) totalCount
/ (diff / 1000.);
double latency = totalLatency
/ (double) totalCount;
System.out.println(String.format(
"Finished %d tasks in %d ms",
totalCount, diff));
System.out.println(String.format(
"Throughtput: %f /s", throughput));
System.out.println(String.format(
"Average latency: %f ms", latency));
System.exit(0);
}
}
}
});
control.addTask(task);
}
while (true)
;
} catch (Exception e) {
e.printStackTrace();
}
}
|
0a1bf1bc-9973-4d3b-8b45-9f0af3d34b64
| 2
|
public void endElement() throws IOException {
String name = openElements.pop();
// If start tag still open, end with />, else with </name>.
if (bStartTagOpen) {
w.write("/>" + newLine);
bStartTagOpen = false;
} else {
writeIndent();
w.write("</" + name + ">" + newLine);
}
// Set document closed when last element is closed
if (openElements.isEmpty()) {
bDocumentOpen = false;
}
}
|
39fcb65e-4b43-4be1-a61b-1438a100f1ee
| 1
|
public void printResults() {
for (int i = 0; i < tondeuses.size(); i++) {
System.out.println("Tondeuse N°" + i + " : " + tondeuses.get(i).toString());
}
}
|
aa3680ec-f037-4b82-b73c-24170aac0164
| 0
|
public void setEventId(int eventId) {
this.eventId = eventId;
}
|
97fb4695-06fe-437e-9900-2e3c143d49b9
| 8
|
public String readMassProperties(BufferedReader massPropertiesReader, String propertiesToFind) throws IOException{
String propertyName = null,
propertyData = null,
readIn = null;
do{
readIn = massPropertiesReader.readLine();
try {
if(readIn.equals(null)){
break;
}
} catch (NullPointerException massPropertiesReaderNPE) {
break;
}
if(readIn.startsWith("*")){
continue;
}else if(readIn.contains("\"")){
StringTokenizer propertyTokens = new StringTokenizer(readIn);
propertyName = propertyTokens.nextToken("\"");
propertyName = propertyName.trim();
if(propertyName.equalsIgnoreCase(propertiesToFind)){
try {
if(propertyData.equals(null)){
propertyData = propertyTokens.nextToken("\"") + ";";
}else{
propertyData += propertyTokens.nextToken("\"") + ";";
}
} catch (NullPointerException propertyDataNPE) {
propertyData = propertyTokens.nextToken("\"") + ";";
}
}else{
continue;
}
}
}while(!readIn.equals(null));
return propertyData;
}
|
8d19f997-1cf8-4659-84ac-232402dc85da
| 6
|
protected static Ptg calcMRound( Ptg[] operands )
{
if( operands.length != 2 )
{
return new PtgErr( PtgErr.ERROR_NA );
}
double m = 0.0;
double n = 0.0;
try
{
n = operands[0].getDoubleVal();
m = operands[1].getDoubleVal();
}
catch( NumberFormatException e )
{
return PtgCalculator.getValueError();
}
if( ((n < 0) && (m > 0)) || ((n > 0) && (m < 0)) )
{
return new PtgErr( PtgErr.ERROR_NUM );
}
double result = Math.round( n / m ) * m;
PtgNumber pnum = new PtgNumber( result );
return pnum;
}
|
a4093326-1e30-4796-8f6b-30f78327baaa
| 2
|
public void addLstore(int n) {
if (n < 4)
addOpcode(63 + n); // lstore_<n>
else if (n < 0x100) {
addOpcode(LSTORE); // lstore
add(n);
}
else {
addOpcode(WIDE);
addOpcode(LSTORE);
addIndex(n);
}
}
|
1e32d5e5-96f7-4aef-8928-31443e9690c1
| 2
|
private int calc(int begin, int end, int number) {
int min = begin % number == 0 ? begin : (begin / number + 1) * number;
int max = end % number == 0 ? end : end / number * number;
int count = (max - min) / number + 1;
return (min + max) * count / 2;
}
|
d63ba629-eb8d-49d3-9339-367e581cf26c
| 7
|
public boolean pause(Session sess)
{
if((sess==null)||(sess.isStopped()))
return false;
sess.rawCharsOut("<pause - enter>".toCharArray());
try
{
String s=sess.blockingIn(10 * 60 * 1000, true);
if(s!=null)
{
s=s.toLowerCase();
if(s.startsWith("qu")||s.startsWith("ex")||s.equals("x"))
return false;
}
}
catch (final Exception e)
{
return false;
}
return !sess.isStopped();
}
|
d421c402-371f-4df4-8576-91154bf61cfe
| 0
|
@Override
public String toString() {
return nom + " " + prenom;
}
|
bd12c65b-9546-4027-95b4-7ee1c258495a
| 2
|
public int compareTo(Object tmp )
{
int result;
result = (this.ticks < ((Event)tmp).GetTicks() ? -1 : (this.ticks == ((Event)tmp).GetTicks() ? 0 : 1));
return result;
}
|
7e0a74c8-bd73-4693-8a7e-c677ce2980fc
| 5
|
@Override
public String saveQuestion(ua.edu.odeku.pet.database.entry.Test test) {
if (test == null || test.getId_test() == null){
return "Для сохранения вопроса необходимо передать объект теста";
}
question = new Question();
question.setIdTest(test);
question.setNameQuestion(this.getTask());
question.setTypeQuestion(this.getTypeQuestion());
try {
// Сохраним тест
int ret = question.insertInto();
if (ret == -1){
return "Такое задание для этого теста уже есть в базе";
}
} catch (SQLException ex) {
Logger.getLogger(AlternativePanel.class.getName()).log(Level.SEVERE, null, ex);
return ex.toString();
}
try {
// Получим код теста
question.setIdQuestion(question.getIdFromDataBase());
} catch (SQLException ex) {
Logger.getLogger(AlternativePanel.class.getName()).log(Level.SEVERE, null, ex);
return ex.toString();
}
return this.saveAnswer(question);
}
|
e2a52323-a354-4f1c-b862-c139a496b425
| 2
|
public byte[] getPublicKeyBlob(){
if(publickeyblob!=null) return publickeyblob;
if(type==RSA) return getPublicKeyBlob_rsa();
return getPublicKeyBlob_dss();
}
|
74382f14-e202-461f-b3bd-9d36ee8e9536
| 3
|
public void stopGame() {
// Setting isRunning to false will
// make the thread stop (see run())
this.isRunning = false;
// Make sure we wait until the thread has stopped...
if (this.gameThread != null) {
while (this.gameThread.isAlive()) {
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
// Pass the call on.
Thread.currentThread().interrupt();
}
}
}
}
|
7c95036c-7a01-407e-84fd-1ebbc6295e45
| 6
|
@EventHandler
public void onPlayerInteractEntity(PlayerInteractEntityEvent event){
Player player = event.getPlayer();
Entity entity = event.getRightClicked();
if(AnimalUtil.isAnimal(entity) && player.getItemInHand() != null && !ExplodeUtil.isAnimalGoingToExplode((LivingEntity) entity)){
if(ExplodingAnimals.gunpowder){
if(player.getItemInHand().getType() == Material.SULPHUR){
ExplodeUtil.explodeAnimal((LivingEntity) entity, plugin);
}
}else{
if(AnimalUtil.isExplosiveForAnimal(entity.getType(), player.getItemInHand())){
ExplodeUtil.explodeAnimal((LivingEntity) entity, plugin);
}
}
}
}
|
7037ac6d-9c2a-46ad-b377-789d2c1e8888
| 7
|
@Override
public void paintComponent(Graphics g)
{
int x = 0;
int y = 0;
int jobTime = 0;
int count = 0;
int fontBorder = 1;
int stepwidth = 20;
Font font = new Font("Verdana", Font.BOLD, 12);
color.add(new Color(185, 211, 238));
color.add(new Color(159, 182, 205));
//draw jobs
Iterator it = schedules.entrySet().iterator();
int currentScheduleNr = 0;
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
Schedule currentSchedule = (Schedule) pairs.getValue();
int currentJobNr = 0;
for (Job job : currentSchedule.getSchedule() ) {
y = graphBorder + currentScheduleNr*50;
g.setColor(color.get(count));
jobTime = (width * job.getProcessingTime()) / totalTime;
if( currentSchedule.jobsDone.get(currentJobNr).booleanValue() ) {
g.setColor( Color.green);
}
g.fillRect(x, y, jobTime, graphHeight);
g.setColor(Color.black);
g.setFont(font);
g.drawString(Integer.toString(job.getJobNumber()), x + fontBorder, y + graphHeight - graphBorder);
x += jobTime;
++count;
currentJobNr++;
if (count >= color.size())
count = 0;
}
x = 0;
currentScheduleNr++;
}
//draw timeline (as soon as 'a' schedule is received)
if ( totalTime != 0) {
count = 0;
Font timelineFont = new Font("Verdana", Font.PLAIN, 8);
g.setFont(timelineFont);
g.drawLine( 0, windowHeight-bottomPadding, width, windowHeight-bottomPadding );
for ( int i = 0; i < width; i += width/totalTime ) {
if ( i%stepwidth==0 ) {
g.drawString("o", i+count, windowHeight-bottomPadding+graphBorder);
g.drawString(Integer.toString(count), i+count, windowHeight);
}
++count;
}
// draw time indicator
g.drawLine( ((width*this.systemTime)/totalTime) - 2*width/totalTime, 0, ((width*this.systemTime)/totalTime) - 2*width/totalTime, windowHeight );
}
}
|
76249666-6b1f-4122-b03f-4ffba315d299
| 8
|
public static void startMinecraft(String memory,String version) throws FileNotFoundException{
try
{
String path = getMainPath()+File.separator;
String versionDir = new File(path,"versions"+File.separator+version).getAbsolutePath()+File.separator;
String assetsDir = new File(path, "assets").getAbsolutePath() + File.separator;
List<String> params = new ArrayList<String>();
if (Utils.getPlatform() == 2) params.add("javaw"); else params.add("java");
params.add("-Xincgc");
params.add("-Xmx"+memory+"m");
params.add("-Djava.library.path=\"" + versionDir + "natives\"");
JsonParser parser = new JsonParser();
JsonObject elem = parser.parse(
new InputStreamReader(new FileInputStream(versionDir + version+".json"))).getAsJsonObject();
JsonArray libraries = elem.get("libraries").getAsJsonArray();
params.add("-cp");
StringBuilder path1 = new StringBuilder();
for (JsonElement lib : libraries) {
String[] vars = lib.getAsJsonObject().get("name").getAsString()
.split(":");
String libPath = path + "libraries/"
+ vars[0].replaceAll("\\.", "/") + "/" + vars[1] + "/"
+ vars[2] + "/" + vars[1] + "-" + vars[2] + ".jar";
path1.append(libPath + ";");
JsonElement natives = lib.getAsJsonObject().get("natives");
if (natives != null) {
String os = "windows";
if (Utils.getPlatform() == 2) {
os = "windows";
} else if (Utils.getPlatform() == 3) {
os = "osx";
} else if (Utils.getPlatform() == 0) {
os = "linux";
}
File nativesZip = new File(path + "libraries/"
+ vars[0].replaceAll("\\.", "/") + "/" + vars[1] + "/"
+ vars[2] + "/" + vars[1] + "-" + vars[2] + "-"
+ "natives-" + os + ".jar");
Zipper.unzipFolder(nativesZip, new File(versionDir, "natives"));
}
}
SecureRandom rand = new SecureRandom();
String name = new BigInteger(10,rand).toString(32);
path1.append(versionDir + version+".jar");
params.add("\"" + path1.toString() + "\"");
params.add(elem.get("mainClass").getAsString());
params.add(elem.get("minecraftArguments").getAsString()
.replace("${auth_player_name}", name)
.replace("${auth_session}", "Hello World! ^^")
.replace("${version_name}", version)
.replace("${game_directory}", path)
.replace("${game_assets}", assetsDir)
.replace("${auth_uuid}", "1")
.replace("${auth_access_token}", "1")
.replace("${auth_uuid}", "Hello World Again! ^^"));
StringBuilder sb = new StringBuilder();
for (String s : params) {
//System.out.print(s + " ");
sb.append(s + " ");
}
System.out.println(sb.toString());
System.out.println(name);
Runtime.getRuntime().exec(sb.toString());
System.exit(150);
} catch (Exception e)
{
e.printStackTrace();
}
}
|
407d31c0-b967-4cfa-b5f7-9563c87cb9ef
| 4
|
public static BufferedImage sharpen(BufferedImage input) {
int sharpen[][] = new int[][]{
{0, -1, 0},
{-1, 5, -1},
{0, -1, 0}
};
BufferedImage result = new BufferedImage(input.getWidth(), input.getHeight(), input.getType());
for (int i = 0; i < result.getWidth(); i++)
for (int j = 0; j < result.getHeight(); j++) {
double newRed = 0;
double newGreen = 0;
double newBlue = 0;
for (int s = -1; s < 2; s++) {
for (int k = -1; k < 2; k++) {
Color c = new Color(input.getRGB(Math.abs(i + s) % result.getWidth(),
Math.abs(j + k) % result.getHeight()));
newRed += sharpen[s + 1][k + 1] * c.getRed();
newGreen += sharpen[s + 1][k + 1] * c.getGreen();
newBlue += sharpen[s + 1][k + 1] * c.getBlue();
}
}
result.setRGB(i, j, normColor(newRed, newGreen, newBlue).getRGB());
}
return result;
}
|
107b8734-48b4-452c-8a34-0690f6e01ae0
| 4
|
public double getYSpeed(int which) {
switch(which){
case 1:
return leftDriveJoy.getY();
case 2:
return rightDriveJoy.getY();
case 3:
return leftJoy.getY();
case 4:
return rightJoy.getY();
}
return 0;
}
|
c370855b-166e-4fd3-85b2-a5cdb33284b9
| 2
|
public void setInternalButtonPadding(int widthPadding, int heightPadding) {
if ((this.buttonWidthPadding == widthPadding) && (this.buttonHeightPadding == heightPadding)) {
return;
}
this.buttonWidthPadding = widthPadding;
this.buttonHeightPadding = heightPadding;
installGUI();
}
|
6f44ac92-a6b3-4f3f-8843-765c55a046f8
| 2
|
public Expression simplify() {
Expression expr = simplifyAccess();
if (expr != null)
return expr.simplify();
expr = simplifyString();
if (expr != this)
return expr.simplify();
return super.simplify();
}
|
72f858f9-f9b4-4473-aac4-4c781700ef80
| 5
|
public static void main(String[] args) throws IOException {
Grid g = new Grid(4, 2048);
g.printGrid();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = br.readLine()) != null) {
switch (s) {
case "w":
g.move(Operators2048.UP);
break;
case "s":
g.move(Operators2048.DOWN);
break;
case "a":
g.move(Operators2048.LEFT);
break;
case "d":
g.move(Operators2048.RIGHT);
break;
}
g.printGrid();
}
}
|
cb9a5541-e306-45ab-9823-c1e6b691802f
| 5
|
public int typeLen(){
if(length<=0) return 0;
if(tagVal() != 0x1f) return 1;
int k=offset+1;
int len=2;
while((k<length+offset) && (gs(data[k])>127)) {len++; k++;}
if (len > length) return 0;
return len;
}
|
0a764835-abb6-4c97-90a9-2fcfc8b57ef6
| 3
|
public void setField(Field fieldIn){
if(fieldSize == fieldIn.fieldSize){
//System.arraycopy(fieldIn.field,0,this.field,0,fieldSize); Does not work
for (int i = 0; i < fieldSize; i++){
for (int j = 0; j < fieldSize; j++){
this.field[i][j] = fieldIn.field[i][j];
}
}
}
}
|
b3895531-b4f8-4ea9-ac75-90a02bbd2542
| 4
|
public ArrayList<Usuarios> getByDNI(Usuarios u){
PreparedStatement ps;
ArrayList<Usuarios> usuarios = new ArrayList<>();
try {
ps = mycon.prepareStatement("SELECT * FROM Usuarios WHERE dni=?");
ps.setString(1, u.getDNI());
ResultSet rs = ps.executeQuery();
if(rs!=null){
try {
while(rs.next()){
usuarios.add(
new Usuarios(
rs.getString("codigo"),
rs.getString("nombre"),
rs.getString("dni")
)
);
}
} catch (SQLException ex) {
Logger.getLogger(Usuarios.class.getName()).
log(Level.SEVERE, null, ex);
}
}else{
System.out.println("Total de registros encontrados es: 0");
}
} catch (SQLException ex) {
Logger.getLogger(UsuariosCRUD.class.getName()).log(Level.SEVERE, null, ex);
}
return usuarios;
}
|
cfe13268-6b7c-41cb-b032-44afbdbddbd6
| 2
|
public String toString() {
StringBuffer result = new StringBuffer("[");
for (int i = 0; i < stackMap.length; i++) {
if (i > 0)
result.append(", ");
result.append(stackMap[i].getName());
}
return result.append("]").toString();
}
|
1245d60f-6eba-4e25-9377-0a36177f4e24
| 1
|
public void connect() {
System.out.println("Attempting to connect to server...");
try {
conn.connect("1.1.1.1", 9876);
} catch (CouldNotConnectException e) {
System.out.println("Could not connect: " + e.getMessage());
}
}
|
10072dcb-bb27-43d0-9f28-7a307e589101
| 2
|
public GeneratorWebClient() {
isRunning = false;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JPanel panel = new JPanel();
panel.setBackground(Color.LIGHT_GRAY);
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(null);
JLabel lblMinimumSupportLevel = new JLabel("Minimum Support Level");
lblMinimumSupportLevel.setBounds(10, 11, 202, 43);
lblMinimumSupportLevel.setFont(new Font("Tahoma", Font.PLAIN, 18));
panel.add(lblMinimumSupportLevel);
JLabel lblNewLabel = new JLabel("Minimum Confidence Level");
lblNewLabel.setBounds(10, 60, 232, 41);
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
panel.add(lblNewLabel);
mslTextField = new JTextField();
mslTextField.setText("0.0");
mslTextField.setFont(new Font("Tahoma", Font.PLAIN, 18));
mslTextField.setBounds(270, 23, 86, 31);
panel.add(mslTextField);
mslTextField.setColumns(10);
mclTextField = new JTextField();
mclTextField.setText("0.0");
mclTextField.setFont(new Font("Tahoma", Font.PLAIN, 18));
mclTextField.setBounds(270, 72, 86, 29);
panel.add(mclTextField);
mclTextField.setColumns(10);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 296, 370, 245);
panel.add(scrollPane);
final JTextPane textPane = new JTextPane();
scrollPane.setViewportView(textPane);
textPane.setEditable(false);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(394, 296, 370, 245);
panel.add(scrollPane_1);
final JTextPane textErrorPane = new JTextPane();
scrollPane_1.setViewportView(textErrorPane);
textErrorPane.setEditable(false);
JLabel lblInputFile = new JLabel("Input Transaction File");
lblInputFile.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblInputFile.setBounds(10, 109, 202, 36);
panel.add(lblInputFile);
JLabel lblOutputRuleFile = new JLabel("Output Rule File");
lblOutputRuleFile.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblOutputRuleFile.setBounds(10, 151, 157, 32);
panel.add(lblOutputRuleFile);
inputText = new JTextField();
lblInputFile.setLabelFor(inputText);
inputText.setFont(new Font("Tahoma", Font.PLAIN, 18));
inputText.setBounds(270, 112, 327, 33);
panel.add(inputText);
inputText.setColumns(10);
outputRuleText = new JTextField();
lblOutputRuleFile.setLabelFor(outputRuleText);
outputRuleText.setFont(new Font("Tahoma", Font.PLAIN, 18));
outputRuleText.setBounds(270, 154, 327, 29);
panel.add(outputRuleText);
outputRuleText.setColumns(10);
JButton btnPressMe = new JButton("Perform Apriori");
JButton btnReset = new JButton("Reset");
btnReset.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
inputText.setText("");
outputRuleText.setText("");
outputErrorText.setText("");
mslTextField.setText("0.0");
mclTextField.setText("0.0");
textPane.setText("");
textErrorPane.setText("");
textPane.repaint();
textErrorPane.repaint();
//outputDialog(textPane);
//outputErrorDialog(textErrorPane);
}
});
btnPressMe.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
inputFilePath = inputText.getText();
outputErrorFilePath = outputErrorText.getText();
outputRuleFilePath = outputRuleText.getText();
msl = Double.parseDouble(mslTextField.getText());
mcl = Double.parseDouble(mclTextField.getText());
//ClientResource clientResource = new ClientResource("http://localhost:8111/");
//TransactionSetResource proxy = clientResource.wrap(TransactionSetResource.class);
///proxy.store(transSet);
//newTransSet = proxy.retrieve();
if(isRunning == false){
isRunning = true;
thread = new Thread() {
public void run() {
//Function for what happens after mouse click
if(formatFilePaths()){
ClientResource clientResource = new ClientResource("http://localhost:8111/");
GeneratorResource proxy = clientResource.wrap(GeneratorResource.class);
System.out.println("IN IF of format file paths");
System.out.println(inputFilePath);
System.out.println(outputErrorFilePath);
System.out.println(outputRuleFilePath);
runTest(inputFilePath, outputRuleFilePath, msl, mcl, clientResource, proxy);
outputDialog(textPane);
//outputRuleDialog(textPane);
outputErrorDialog(textErrorPane);
isRunning = false;
}
}
};
thread.start();
}
}
});
btnPressMe.setBounds(100, 251, 139, 33);
btnReset.setBounds(500, 251, 139, 33);
panel.add(btnPressMe);
panel.add(btnReset);
JLabel lblOutputErrorFile = new JLabel("Output Error File");
lblOutputErrorFile.setFont(new Font("Tahoma", Font.PLAIN, 18));
lblOutputErrorFile.setBounds(10, 197, 157, 32);
panel.add(lblOutputErrorFile);
outputErrorText = new JTextField();
lblOutputErrorFile.setLabelFor(outputErrorText);
outputErrorText.setFont(new Font("Tahoma", Font.PLAIN, 18));
outputErrorText.setColumns(10);
outputErrorText.setBounds(270, 200, 327, 29);
panel.add(outputErrorText);
}
|
64ec86c5-cd05-4b4c-be87-6e0ffc0d3a3c
| 3
|
public void randDnaSeqGetBaseTest(int numTests, int numTestsPerSeq, int lenMask, long seed) {
Random rand = new Random(seed);
for( int t = 0; t < numTests; t++ ) {
String seq = "";
int len = (rand.nextInt() & lenMask) + 10; // Randomly select sequence length
seq = randSeq(len, rand); // Create a random sequence
if( verbose ) System.out.println("DnaSequence test:" + t + "\tlen:" + len + "\t" + seq);
DnaSequence bseq = new DnaSequence(seq);
// Retrieve numTestsPerSeq random bases from the sequence
for( int i = 0; i < numTestsPerSeq; i++ ) {
int randPos = rand.nextInt(len);
char baseOri = seq.charAt(randPos);
char baseBin = bseq.getBase(randPos);
Assert.assertEquals(baseOri, baseBin);
}
}
}
|
7fb63941-2a52-44d5-b983-58a81fbf1f9a
| 6
|
private void formatAll() {
try {
final Matcher m = FORMATTING_PATTERN.matcher(getDoc().getText(0, getDoc().getLength()));
Integer start = 0;
while (m.find()) {
if (m.group(8) != null) {
// comment
start = format(m.start(8), m.end(8), start, commentStyle());
} else if (m.group(7) != null) {
// line comment
start = format(m.start(7), m.end(7), start, commentStyle());
} else if (m.group(2) != null) {
// value
start = format(m.start(2), m.end(2), start, valueStyle());
} else if (m.group(1) != null) {
// keyword
start = format(m.start(1), m.end(1), start, keywordStyle());
}
}
getDoc().setCharacterAttributes(start, getDoc().getLength() - start, standardStyle(), false);
} catch (final BadLocationException e) {
e.printStackTrace();
}
}
|
64c34e76-de56-48a6-9bc3-211216509b4f
| 7
|
public static void main(String[] args){
//////////////////Checking get alternatives////////////////////////////////
String str = "thisisalongstringthatshouldbeovertwentycharacterslong";
int length = 53;
int compare = 53*(length+1) + 25;
Word[] w = d.getAlternatives(new Word(str));
if(w.length != compare)
System.out.println("Error in length of alternatives");
/////////////////Adding 26 more characters to the string///////////////////////////
str = str + "abcdefghijklmnopqrstuvwxyz";
length += 26;
compare = 53*(length+1) + 25;
w = d.getAlternatives(new Word(str));
if(w.length != compare)
System.out.println("Error in the extended length of alternatives");
/*
* To test spell checking a file we can create files with misspelled words and run them in the interface
*
* testFile1.txt
*/
Word correct = d.find("whyle", false);
if(!correct.getWord().equals("while"))
System.out.println("Find method in dictionary correct whyle to while");
//These tests were done by putting all the words with their frequencies into
//an excel sheet and then sorting them in alphabetical order to find words
//that have similar spellings with different frequencies.
correct = d.find("aga", false);
if(!correct.getWord().equals("ago"))
System.out.println("Did not find the closest word to aga, instead found " +correct.getWord());
correct = d.find("aiz", false);
if(!correct.getWord().equals("air"))
System.out.println("Did not find air, instead found " + correct.getWord());
correct = d.find("appeam", false);
if(!correct.getWord().equals("appear"))
System.out.println("Did not find appear, instead found " + correct.getWord());
String ahead = "ahead";
correct = d.find(ahead, false);
if(!correct.getWord().equals(ahead))
System.out.println("Did not return the correct word as supposed to");
// FileCompression.compress("testFile1.txt", "testCompress1");
// FileCompression.decompress("testCompress1", "testDecompress.txt");
// FileCompression.compress("great_expectations.txt" , "ge_cd_com");
// FileCompression.decompress("ge_cd_com", "ge_decom.txt");
System.out.println("Done Testing");
}
|
f57c3a2f-b610-4fbe-888c-6319292d7676
| 9
|
private void init(){
TextureRegion[] tr = null;
boolean direction = false;
Texture t;
time = 3;
// System.out.println("init splash: "+type);
switch(type){
case DO_BATTLE:
t = Game.res.getTexture("doBattlebase");
tr=TextureRegion.split(Game.res.getTexture("doBattle"), t.getWidth(), t.getHeight())[0];
break;
case DO_IT:
t = Game.res.getTexture("doItbase");
tr=TextureRegion.split(Game.res.getTexture("doIt"), t.getWidth(), t.getHeight())[0];
break;
case FIGHT:
t = Game.res.getTexture("fightbase");
tr=TextureRegion.split(Game.res.getTexture("fight"), t.getWidth(), t.getHeight())[0];
break;
case ITS_ALIVE:
t = Game.res.getTexture("itsAlivebase");
tr=TextureRegion.split(Game.res.getTexture("itsAlive"), t.getWidth(), t.getHeight())[0];
break;
case KICK_ASS:
t = Game.res.getTexture("kickAssbase");
tr=TextureRegion.split(Game.res.getTexture("kickAss"), t.getWidth(), t.getHeight())[0];
break;
case KILL_IT:
time = 2f;
t = Game.res.getTexture("killItbase");
tr=TextureRegion.split(Game.res.getTexture("killIt"), t.getWidth(), t.getHeight())[0];
break;
case TO_DEATH:
t = Game.res.getTexture("toDeathbase");
tr=TextureRegion.split(Game.res.getTexture("toDeath"), t.getWidth(), t.getHeight())[0];
break;
case WASTED:
overlay = Game.res.getTexture("splashOverlay");
default:
break;
}
maxTime = time;
if (tr!=null){
animation = new Animation(null);
animation.initFrames(tr, Vars.ANIMATION_RATE, direction);
}
}
|
d354c2c0-e919-4757-8fe2-d02690d60bb7
| 6
|
public NpcDefinition child(IClientContext ctx) {
int index = 0;
if (scriptId == -1) {
index = configId != -1 ? ctx.varpbits.varpbit(configId) : -1;
} else {
final Script script = ctx.definitions.varp(scriptId);
if (script != null) {
index = script.execute(ctx);
}
}
if (index >= 0 && index < childrenIds.length && childrenIds[index] != -1) {
return ctx.definitions.npc(childrenIds[index]);
}
return null;
}
|
ed01eed7-ae00-4a30-bb0d-784d873b137e
| 5
|
private static boolean canPushOpponentOutOfSuperRegion(BotState state, SuperRegion superRegion) {
boolean out = true;
List<Region> subRegions = superRegion.getSubRegions();
for (Region subRegion : subRegions) {
if (subRegion.getPlayerName().equals("unknown")
&& HeuristicMapModel.getGuessedOpponentRegions().contains(subRegion)) {
out = false;
}
}
if (superRegion.isOwnedByMyself(state)) {
out = false;
}
if (canSuperRegionBeTaken(state, superRegion)) {
out = false;
}
return out;
}
|
9689be48-6353-4e75-8133-aad0342a6561
| 8
|
public static boolean isNumeric(Object value)
{
if (value == null) return false;
else
{
if (value instanceof Byte ||
value instanceof Integer ||
value instanceof Long ||
value instanceof Double ||
value instanceof Float ||
value instanceof Short) return true;
else
{
NumberFormat _formatter = NumberFormat.getInstance();
try
{
_formatter.parse(value.toString());
return true;
}
catch (ParseException ex)
{
ex.toString(); return false;
}
}
}
}
|
89a20a69-ee27-48bc-a296-0406d3ebbdb6
| 5
|
protected void startup() {
// Get the native look and feel class name
String nativeLF = UIManager.getSystemLookAndFeelClassName();
// Install the look and feel
try {
UIManager.setLookAndFeel(nativeLF);
} catch (InstantiationException e) {
} catch (ClassNotFoundException e) {
} catch (UnsupportedLookAndFeelException e) {
} catch (IllegalAccessException e) {
}
contactsToPanelMap = new HashMap<Integer, Integer>();
contactsui = new ContactsWindow();
contactsui.setVisible(true);
chats = new LinkedList<ChatPanel>();
chatWindow = new ChatWindow();
chatWindow.setVisible(true);
try {
connection = new ChatNetwork();
connected = true;
} catch(NoConnectionException e) {
contactsui.alert("Connection error", "No connection found. Could not start tchat.");
connected = false;
}
}
|
613c34c6-3473-47e7-a64d-f1cf8ff2dc2a
| 1
|
public static Faixada getInstance(){
if(faixada == null){
faixada = new Faixada();
}
return faixada;
}
|
2bc458a7-559e-46ca-8442-343434c03c4a
| 2
|
private void searchContact() {
final JDialog dialog = new JDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("Kontakt suchen");
dialog.setResizable(false);
dialog.setBounds(this.getLocationOnScreen().x + 350,
this.getLocationOnScreen().y - 40, 250, 110);
dialog.getContentPane().setLayout(new BorderLayout());
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
dialog.getContentPane().add(contentPanel, BorderLayout.CENTER);
JLabel lblKontaktid = new JLabel("Kontaktnummer");
contentPanel.add(lblKontaktid);
final JTextField textField = new JTextField();
contentPanel.add(textField);
textField.setColumns(3);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
dialog.getContentPane().add(buttonPane, BorderLayout.SOUTH);
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
refresh(ekd.select(Integer.parseInt(textField.getText()
.trim())));
} catch (NumberFormatException ex) {
ex.printStackTrace();
} catch (NoEmailKontaktFoundException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
e1.printStackTrace();
}
}
});
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
buttonPane.add(cancelButton);
dialog.setVisible(true);
}
|
2c469d79-218b-4283-ac04-a1acac51905b
| 1
|
public static void copyDirectory(String srcDir, String destDir, boolean keepDate) throws UtilException {
try {
FileUtils.copyDirectory(new File(srcDir), new File(destDir), keepDate);
} catch (IOException e) {
throw new UtilException("拷贝目录失败", e);
}
}
|
c5a105be-cd0e-42f0-8373-769fd865fe5d
| 2
|
public boolean existNode(GraphNode<T> pgraphNode) {
for (int i = 0; i < graph_nodes.getLength(); i++) {
if (pgraphNode.equals(graph_nodes.get(i))) {//if param is equal to node in list.
return true;
}
}
return false;
}
|
69fdde88-554c-4346-826c-12592bc92e10
| 3
|
public Integer getStart()
{
if (start != null)
if (start < 0 || start > 100)
throw new RuntimeException("start取值范围0~100!");
return start;
}
|
957b8913-f547-4373-9377-80cf72b6232a
| 7
|
public boolean degradeCompletly(Item item) {
int defaultCharges = ItemConstants.getItemDefaultCharges(item.getId());
if (defaultCharges == -1)
return false;
while (true) {
if (ItemConstants.itemDegradesWhileWearing(item.getId())
|| ItemConstants.itemDegradesWhileCombating(item.getId())) {
charges.remove(item.getId());
int newId = ItemConstants.getItemDegrade(item.getId());
if (newId == -1)
return ItemConstants.getItemDefaultCharges(item.getId()) == -1 ? false
: true;
item.setId(newId);
} else {
int newId = ItemConstants.getItemDegrade(item.getId());
if (newId != -1) {
charges.remove(item.getId());
item.setId(newId);
}
break;
}
}
return false;
}
|
5c765648-8f81-4106-a6c3-23b66c35af3f
| 7
|
public void movepass ()
{ if (!Started || Ended) return;
if (B.maincolor()!=Col) return;
if (Timer.isAlive()) alarm();
if (Col>0) { if (BlackMoves>0) BlackMoves--; }
else { if (WhiteMoves>0) WhiteMoves--; }
PF.pass(BlackTime-BlackRun,BlackMoves,
WhiteTime-WhiteRun,WhiteMoves);
}
|
2c10f782-5c61-49eb-be78-72f134dd4aee
| 2
|
private static double doubleHighPart(double d) {
if (d > -SAFE_MIN && d < SAFE_MIN){
return d; // These are un-normalised - don't try to convert
}
long xl = Double.doubleToLongBits(d);
xl = xl & MASK_30BITS; // Drop low order bits
return Double.longBitsToDouble(xl);
}
|
784a7a09-4831-474c-ada4-9612570c8f1b
| 1
|
public Users checkRegistered(String login, String password) throws SQLException {
Users user = null;
//Подключаемся к базе
PreparedStatement statement = getConnection().prepareStatement(isRegisteredQuery);
statement.setString(1, login);
statement.setString(2, password);
ResultSet result = statement.executeQuery();
if (result.next()) {
//Получаем пользователя
user = fetchObject(result);
//Устанавливаем Id пользователя
curUserId = result.getInt("ID");
}
return user;
}
|
0897962b-5741-4449-80fa-9571d9eab786
| 8
|
@Override
public void run() {
ObjectInputStream in = null;
ObjectOutputStream out = null;
// System.out.println("Accepted Client Address - "
// + clientSocket.getInetAddress().getHostName());
try {
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
while (clientRun) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
Object inputObject = null;
Command clientCommand;
try {
inputObject = in.readObject();
} catch (Exception e) {
// clientCommand = new Command(CommandType.QUIT, null);
}
if (inputObject instanceof Command) {
clientCommand = (Command) inputObject;
} else {
clientCommand = new Command(CommandType.QUIT, null);
}
if (!clientsThread.ServerOn) {
System.out.print("Server stopped");
clientRun = false;
}
if (clientCommand.getCommandName().equals(CommandType.QUIT)) {
clientRun = false;
// System.out.print("Stopping client thread for client : ");
} else {
// System.out.println("Cleint command RUN ex");
out.writeObject(new CommandExecuter(clientCommand).execute());
// System.out.println("Cleint command FINISH ex");
out.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close client thread
try {
in.close();
out.close();
clientSocket.close();
//System.out.println("Server isStopped");
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
|
8b1848b1-a3a4-464b-aa10-7427dceb54d5
| 0
|
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
}
|
45d004e3-24a0-4f3e-ad81-bc02d9865432
| 5
|
private void parseFile(String filePath)
{
currentFile = filePath;
File file = new File(filePath);
if (file.exists())
{
try
{
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(file);
Node root = document.getFirstChild();
if (root != null)
parseNode(root);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
e069e3c8-e48d-4367-ab10-e973c56cab74
| 2
|
public Iterator getChilds() {
final Iterator fieldIter = fieldIdents.iterator();
final Iterator methodIter = methodIdents.iterator();
return new Iterator() {
boolean fieldsNext = fieldIter.hasNext();
public boolean hasNext() {
return fieldsNext ? true : methodIter.hasNext();
}
public Object next() {
if (fieldsNext) {
Object result = fieldIter.next();
fieldsNext = fieldIter.hasNext();
return result;
}
return methodIter.next();
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
|
94928a4e-a338-4e1c-af34-c91359674af8
| 2
|
public static Location getLocationFromName(String thename)
{
int index = -1;
for(int i=0; i<Parasite.location.listOfLocations.length;i++)
{
String tempplace = Parasite.location.listOfLocations[i].room;
if(tempplace.equalsIgnoreCase(thename))
{
index = i;
break;
}
}
return Parasite.location.listOfLocations[index];
}
|
7abf75e0-7a44-4b8d-8725-9d600efb2715
| 4
|
public void loadCheques(){
chequeDataAccessor dataAccessorCheque=new chequeDataAccessor();
List<cheque> chequeList=new ArrayList();
DefaultTableModel orderDataTable=new DefaultTableModel();
Object[ ] columnNames=new Object[4];
Object[ ] fieldValues=new Object[4];
//Patient myPatient=null;
try{
chequeList=dataAccessorCheque.retriveChequeinfo();
}
catch(SQLException e){
System.out.println(e.getMessage());
}
if(chequeList.isEmpty()){
JOptionPane.showMessageDialog(null,"No cheques ","Information",JOptionPane.WARNING_MESSAGE);
}
columnNames[0]="Cheque ID";
columnNames[1]="Bank Name";
columnNames[2]="Cheque Date";
columnNames[3]="Cheque Amount";
orderDataTable.setColumnIdentifiers(columnNames);
if(chequeList.size()>0){
for (cheque newCheque : chequeList) {
tempCheque = newCheque;
fieldValues[0]=tempCheque.getChequeID();
fieldValues[1]=tempCheque.getBankName();
fieldValues[2]=tempCheque.getInputDate();
fieldValues[3]=tempCheque.getChequeAmount();
orderDataTable.addRow(fieldValues);
}
this.chequeDetailTable.setModel(orderDataTable);
}
}
|
83e34409-80b8-47e9-9579-144ed7238b67
| 2
|
private void removeNextAction() {
if (actions != null && actions.size() > 0) {
actions.remove(0);
}
}
|
52f88af0-f30f-4db2-956b-2e1c0cf7730f
| 6
|
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(frmLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new frmLogin().setVisible(true);
}
});
}
|
3c638152-9a33-4504-87ff-ee365a1e5525
| 2
|
public void visitStoreExpr(final StoreExpr node) {
nodes.add(node);
if (checkValueNumbers) {
Assert.isTrue(node.valueNumber() != -1, node
+ ".valueNumber() = -1");
}
Assert.isTrue(node.block() == block, node + ".block() = "
+ node.block() + " != block = " + block);
Assert.isTrue(node.parent() == parent, node + ".parent() = "
+ node.parent() + " != parent = " + parent);
// Visit the MemExpr into which node stores.
parent = node;
node.target().visit(this);
// Visit the expression whose value is being stored by node
parent = node;
node.expr().visit(this);
parent = node.parent();
if (node.type().isVoid()) {
Assert.isTrue(parent instanceof ExprStmt, "parent of " + node
+ " = " + parent + " is not an ExprStmt");
}
}
|
c53414fc-5fcf-4382-b864-f00b649e242a
| 9
|
static public void quickSort(int[] array, int left, int right){
int p = (left + right)/2;
int pivot = array[p];
int i = left;
int j = right;
while(i < j){
while(i < p && pivot >= array[i]){
++i;
}
if(i < p){
array[p] = array[i];
p = i;
}
while(j > p && pivot <= array[j]){
--j;
}
if(j > p){
array[p] = array[j];
p = j;
}
}
array[p] = pivot;
if(p - left > 1){
quickSort(array, left, p - 1);
}
if(right - p > 1){
quickSort(array, p + 1, right);
}
}
|
38eca767-57b2-48b3-a34e-4040ad75c587
| 3
|
public void getUserData(String data) {
String begin = "<!--udatab ";
String end = " udatae-->";
String _tmp = data;
StringTokenizer tokenizer;
client.userdata.clear();
while (_tmp.indexOf(begin) != -1) {
int i = _tmp.indexOf(begin)+11;
int k = _tmp.indexOf(end);
int m = k+10;
String udata = _tmp.substring(i,k).trim();
if (Client.debug) {
System.out.println("udata: "+udata);
}
tokenizer = new StringTokenizer(udata, ":");
try {
String username = tokenizer.nextToken();
String userid = tokenizer.nextToken();
String isaway = tokenizer.nextToken();
client.userdata.put(username.toLowerCase(), username+":"+userid+":"+isaway);
} catch (Exception e) {
e.printStackTrace();
}
_tmp = _tmp.substring(m);
tokenizer = null;
}
}
|
79a86ccd-6595-4a2a-838c-9c21294ff6cf
| 7
|
void playStep() {
tick++;
// move the player dogs
if (tick % 10 == 0 && tick !=0){
calculateres();
//updatemap();
}
for (int d=0; d<4; d++) {
try {
ArrayList<movePair> nextlist = new ArrayList<movePair>();
nextlist = players[d].move(king_outpostlist, noutpost[d], grid);
for (int i=0; i<nextlist.size(); i++) {
movePair next = new movePair();
next = nextlist.get(i);
//next = players[d].move(king_outpostlist, noutpost[d], grid);
//System.out.printf("Player %d is moving (%d, %d) to (%d, %d)\n", d, king_outpostlist.get(d).get(next.id).x, king_outpostlist.get(d).get(next.id).y, next.pr.x, next.pr.y);
// validate player move
// if (validateMove(next, d)) {
validateMove(nextlist, d);
/*if (next.delete) {
king_outpostlist.get(d).remove(next.id);
}
else {
Pair tmp = new Pair(next.pr.x, next.pr.y);
king_outpostlist.get(d).set((next.id), tmp);
}*/
updatemap();
// }
// else {
// System.out.println("valid didn't pass...");
//}
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("[ERROR] Player throws exception!!!!");
//next[d] = pipers[d]; // let the dog stay
}
/* if (verbose) {
System.err.format("Piper %d moves from (%.2f,%.2f) to (%.2f,%.2f)\n",
d+1, pipers[d].x, pipers[d].y, next.pr.x, next.pr.y);
}
*/
}
if (tick == nrounds) {
calculateres();
for (int i=0; i<4; i++) {
System.err.printf("Player %d control water %f, land %f\n", water[i], soil[i]);
}
}
}
|
0ec06f9b-42c9-4c67-8c2a-f0f856060c8f
| 5
|
public static void
dnf (String[] vals, StringClassifier classifier)
{
/*
* Sort the array using some tactics we learned during our binary search
* class discussion.
*
*
* As i increases, we can put reds to the front and leave all whites in the
* center. Therefore, the "r" invariant from our class discussion is
* redundant.
*
* Invariants: the unknown level, i, is always lower than our upper bound,
* until we have solved the sort.
*/
int i = 0; // this is our "unknown" level
int lowerBound = 0;
int upperBound = vals.length - 1;
try
{
while (i <= upperBound)
{
int color = classifier.classify (vals[i]);
switch (color)
{
// Now we just need to figure out how to switch them.
case 0: // white; stays in middle.
i++;
break;
case -1: // red; goes to beginning.
// Take the value at the beginning, and switch it with this
// one.
switchValues (vals, i, lowerBound);
// Increment the appropriate values
lowerBound++;
i++;
break;
case 1: // blue; goes to end.
switchValues (vals, i, upperBound);
// Decrement and increment the appropriate values
upperBound--;
break;
} // switch (String)
} // while (i <= upperBound)
} // try
catch (Exception e)
{
// One of the values was unknown!
System.err.println ("An unknown color was given as input.");
}
} // dnf(String[], StringClassifier)
|
8e7a7a67-9f18-4f25-b295-849b17162113
| 4
|
public void dataDeque(){
dataQue = new LinkedBlockingQueue<Packet>();
Thread dataHandling = new Thread() {
public void run(){
while(true){
Packet packet = (Packet) dataQue.poll();
if(packet != null) {
if(packet.channel != null){
for(int handlers = 0; handlers < Server.packetHandels.size(); handlers++){
Server.packetHandels.get(handlers).packetIncoming(packet);
}
}
}
}
}
};
dataHandling.setDaemon(true);
dataHandling.start();
}
|
6dfd8eb8-b28e-4958-9e9b-70e710120e05
| 2
|
public void setStandardButtonBorderthickness(int[] border) {
if ((border == null) || (border.length != 4)) {
this.buttonStd_Borderthickness = UIBorderthicknessInits.STD_BTN.getBorderthickness();
} else {
this.buttonStd_Borderthickness = border;
}
somethingChanged();
}
|
3aa8bc4c-e548-42a5-b8a0-faab3dcbe2a5
| 0
|
@Test
public void testIsBrowser() {
assertTrue(Browser.SAFARI.isInUserAgentString("Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3"));
}
|
e4a0939a-6d7b-483f-9de7-ff8da2614666
| 7
|
public void draw (SpriteBatch batch, float parentAlpha) {
BitmapFont font = style.font;
Drawable selectedDrawable = style.selection;
Color fontColorSelected = style.fontColorSelected;
Color fontColorUnselected = style.fontColorUnselected;
Color color = getColor();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
float x = getX();
float y = getY();
font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a * parentAlpha);
float itemY = getHeight();
float padding = selectedDrawable.getLeftWidth() + selectedDrawable.getRightWidth();
for (int i = 0; i < items.size; i++) {
if (cullingArea == null || (itemY - itemHeight <= cullingArea.y + cullingArea.height && itemY >= cullingArea.y)) {
if (selectedIndex == i) {
selectedDrawable.draw(batch, x, y + itemY - itemHeight, Math.max(prefWidth, getWidth() + padding), itemHeight);
font.setColor(fontColorSelected.r, fontColorSelected.g, fontColorSelected.b, fontColorSelected.a * parentAlpha);
}
font.draw(batch, items.get(i).toString(), x + textOffsetX, y + itemY - textOffsetY);
if (selectedIndex == i) {
font.setColor(fontColorUnselected.r, fontColorUnselected.g, fontColorUnselected.b, fontColorUnselected.a
* parentAlpha);
}
} else if (itemY < cullingArea.y) {
break;
}
itemY -= itemHeight;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.