method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
982ebc7c-217a-4f55-b437-1c79377505eb | 8 | public void updateLed(double rpm) {
if (rpm >= rpmForPin1 && rpm < rpmForPin2) {
stopBlinking();
pin1.high();
pin2.low();
pin3.low();
} else if (rpm >= rpmForPin2 && rpm < rpmForPin3) {
stopBlinking();
pin1.high();
pin2.high();
pin3.low();
} else if (rpm >= rpmForPin3 && rpm < rpmForBlinking) {
stopBlinking();
pin1.high();
pin2.high();
pin3.high();
} else if (rpm >= rpmForBlinking) {
if (!ledBlinking.isAlive()) {
ledBlinking.startThread();
}
} else {
stopBlinking();
pin1.low();
pin2.low();
pin3.low();
}
} |
ca20f6fe-43ba-4106-9eb9-d14ff33d1fea | 6 | public static String getPK3MapNames(String pathToFile) {
ZipFile zip;
try {
zip = new ZipFile(pathToFile);
} catch (IOException e2) {
e2.printStackTrace();
return null;
}
Enumeration<? extends ZipEntry> e = zip.entries();
String mapNames = "";
while (e.hasMoreElements()) {
ZipEntry ze = (ZipEntry)e.nextElement();
String temp = "";
if ((!ze.isDirectory()) && (ze.getName().toLowerCase().startsWith("maps/"))) {
temp = ze.getName().substring(5);
mapNames += "+addmap " + temp.substring(0, temp.length() - 4) + " ";
}
}
try {
zip.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return mapNames;
} |
70429007-0d40-4e75-9dc2-c787f998e130 | 8 | private void PageRedirect(String itemID, String itemType, String query, boolean DisplayGO, boolean organismdependentquery) {
if (applet == null || configuration == null)
return;
String wholeredirectionString = getRedirectionString(itemID, itemType, query, DisplayGO, organismdependentquery);
Boolean rightClickQueryingEnabled = (Boolean) configuration.get("rightClickQueryingEnabled");
try {
final URL redirectURL = new URL(wholeredirectionString);
// if (checkAppletContext()) {
if (rightClickQueryingEnabled) {
pool.submit(new Thread() {
public void run() {
while (true) {
System.out.println("Trying to redirect to: " + redirectURL);
if (applet != null && applet.getAppletContext() != null) {
applet.getAppletContext().showDocument(redirectURL);
System.out.println("Redirection is done");
break;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
});
//JSObject win = JSObject.getWindow(redirectorApplet);
//win.setMember("location", redirectURL);
} else {
applet.getAppletContext().showDocument(redirectURL, "_blank");
}
//}
}
catch (MalformedURLException murle) {
System.out.println("Could not recognise redirect URL");
}
} |
6ef05e9d-8f84-44f6-a4be-07e3b6c6f461 | 5 | public void setNeighbors( int[] truckdrivin){
//System.out.println(truckdrivin.length);
//System.out.println(neighborstate.length);
for(int g = 0; g <= truckdrivin.length-1; g++){
switch(inmode){
case 0: neighborstate[g] = 0; break;
case 1: if(truckdrivin[g] > 0){neighborstate[g] = 1;}
else{neighborstate[g] = 0;} break;
case 2: neighborstate[g] = truckdrivin[g]; break;
default: neighborstate[g] = truckdrivin[g]; break;
}
}
} |
c601842c-1adc-47ca-9d4f-b0c77df05f2b | 1 | public String toString()
{
if (titulo != null)
return titulo.toString();
return id + "";
} |
dc46e7b4-e5b4-4a7e-b268-f48a76f2dd77 | 0 | public static void main(String[] args) throws Exception
{
CalendarProject myCalendar = new CalendarProject (2013,2);//'0' indicates the first day of the year is a sunday;
} |
d606b09f-56a6-4a1d-83a2-e6b47cc22885 | 5 | public double sin(int a){
//normalizing
if(a>360){
a %= 360;
}else if(a<0){
a %= 360;
a += 360;
}
//return
if(a <= 90){
return sin[a];
}else if(a <= 180){
return sin[180 - a];
}else if(a <= 270){
return -sin[a - 180];
}else{
return -sin[360 - a];
}
} |
2aec77b6-fff8-42d4-8bb1-7325b895cd50 | 1 | @Override
public AState breakTie(AState state1, AState state2)
{
if(state1.getG() > state2.getG())
return state1;
else
return state2;
} |
e4cd578c-6e42-49f1-a55a-a1d6b0eb0175 | 0 | public static ComponentUI createUI(JComponent c) {
return new BasicScrollBarUI();
} |
137b6eac-ec16-46ab-9930-2931d0e2f6f4 | 0 | @Override
public Set<String> getGroups() {
return getList("groups");
} |
3ee6b178-169c-4e3c-9cec-2678cf7014c3 | 5 | private static String encode_base64(byte d[], int len)
throws IllegalArgumentException {
int off = 0;
StringBuffer rs = new StringBuffer();
int c1, c2;
if (len <= 0 || len > d.length)
throw new IllegalArgumentException ("Invalid len");
while (off < len) {
c1 = d[off++] & 0xff;
rs.append(base64_code[(c1 >> 2) & 0x3f]);
c1 = (c1 & 0x03) << 4;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 4) & 0x0f;
rs.append(base64_code[c1 & 0x3f]);
c1 = (c2 & 0x0f) << 2;
if (off >= len) {
rs.append(base64_code[c1 & 0x3f]);
break;
}
c2 = d[off++] & 0xff;
c1 |= (c2 >> 6) & 0x03;
rs.append(base64_code[c1 & 0x3f]);
rs.append(base64_code[c2 & 0x3f]);
}
return rs.toString();
} |
64a000cb-63a3-492e-a41d-d01c7ac269ab | 3 | public JTextComponent getReplacementArea() {
if(replacementArea == null) {
replacementArea = new JTextArea();
replacementArea.setLineWrap(true);
replacementArea.setFont(textAreaFont);
replacementArea.setEditable(false);
replacementArea.setBackground(Color.LIGHT_GRAY);
// Updates to the input area change both the matching area's text and highlighting.
DocumentListener docListener = new DocumentChangeAdapter() {
public void anyUpdate(DocumentEvent e) {
replacementArea.setText(getInputArea().getText());
String replaceWithText = getReplaceWithField().getText();
if(!"".equals(replaceWithText)) {
applyReplacementHighlighting(replacementArea, getRegexArea().getPattern(), replaceWithText);
}
}
};
getInputArea().getDocument().addDocumentListener(docListener);
getReplaceWithField().getDocument().addDocumentListener(docListener);
// Updates to the regex area change the matching area's highlighting.
RegexListener regexListener = new RegexListener() {
public void regexUpdate(RegexEvent e) {
replacementArea.setText(getInputArea().getText());
String replaceWithText = getReplaceWithField().getText();
if(!"".equals(replaceWithText)) {
applyReplacementHighlighting(replacementArea, getRegexArea().getPattern(), replaceWithText);
}
}
};
getRegexArea().addRegexListener(regexListener);
}
return replacementArea;
} |
ff32cd5f-dec1-4060-a941-6b91fd01697b | 0 | public void start() {
closeDoors();
closeWindows();
} |
b8c7881e-8d8e-4cd2-98d4-8b6286f6fcea | 9 | public AdjacencyList getMinBranching(Node root, AdjacencyList list) {
AdjacencyList reverse = list.getReversedList();
// remove all edges entering the root
if (reverse.getAdjacent(root) != null) {
reverse.getAdjacent(root).clear();
}
AdjacencyList outEdges = new AdjacencyList();
// for each node, select the edge entering it with smallest weight
for (Node n : reverse.getSourceNodeSet()) {
List<Edge> inEdges = reverse.getAdjacent(n);
if (inEdges.isEmpty()) {
continue;
}
Edge min = inEdges.get(0);
for (Edge e : inEdges) {
if (e.getWeight() < min.getWeight()) {
min = e;
}
}
outEdges.addEdge(min.getTo(), min.getFrom(), min.getBond());
}
// detect cycles
List<List<Node>> cycles = new ArrayList<List<Node>>();
cycle = new ArrayList<Node>();
getCycle(root, outEdges);
cycles.add(cycle);
for (Node n : outEdges.getSourceNodeSet()) {
if (!n.isVisited()) {
cycle = new ArrayList<Node>();
getCycle(n, outEdges);
cycles.add(cycle);
}
}
// for each cycle formed, modify the path to merge it into another part of the graph
AdjacencyList outEdgesReverse = outEdges.getReversedList();
for (List<Node> x : cycles) {
if (x.contains(root)) {
continue;
}
mergeCycles(x, list, reverse, outEdges, outEdgesReverse);
}
return outEdges;
} |
28aebc57-2dca-4569-9021-06c7b54c1f78 | 6 | public static int result(String[] token){
Stack<String> stack = new Stack<String>();
String oprator ="+-*/";
for(String str : token){
if(!oprator.contains(str)){
stack.push(str);
}else{
int a = Integer.valueOf(stack.pop());
int b = Integer.valueOf(stack.pop());
int c = 0;
switch(str){
case "+": c=b+a; break;
case "-": c=b-a; break;
case "*": c=b*a; break;
case "/": c=b/a; break;
}
stack.push(String.valueOf(c));
}
}
return Integer.valueOf(stack.pop());
} |
39af1014-9dff-4087-9c52-08b216e96ebc | 5 | public synchronized void plot(double[][] xyValues, Color color) {
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
g.setColor(color);
line.moveTo(xyValues[0][0], xyValues[1][0]);
for(int i = 0; i < xImageLength; i++){
if(xyValues[1][i] != Double.MAX_EXPONENT && xyValues[1][i] != Double.MIN_EXPONENT){
line.lineTo(xyValues[0][i], xyValues[1][i]);
}else{
if(xyValues[1][i] == Double.MAX_EXPONENT){
line.lineTo(xyValues[0][i], Double.MIN_EXPONENT);
}else if(xyValues[1][i] == Double.MIN_EXPONENT){
line.lineTo(xyValues[0][i], Double.MAX_EXPONENT);
}
g.draw(line);
line.reset();
line.moveTo(xyValues[0][i], xyValues[1][i]);
}
}
g.draw(line);
line.reset();
} |
6317678b-b9e7-4495-8bf8-6686fb10414f | 2 | @Override
public void update(Updater u) {
// a monster has gravity too, as a everything on earth (except light, but light doesn't have mass. Or has it ?
this.speedY += LivingEntity.GRAVITY;
// and he moves in one direction
if (this.direction)
this.speedX = LivingEntity.WALKSPEED;
else
this.speedX = -LivingEntity.WALKSPEED;
// we know update positions
this.posY += this.speedY;
this.posX += this.speedX;
// but we hate monster walking threw walls, so let's check collisions !
if (levelCollision())
this.speedY = 0;
} |
eb93cafd-2dec-4f08-b8de-6d01113f2115 | 1 | static void shared() {
int oldVal;
lock.lock();
try {
oldVal = x;
x ++;
} finally {
lock.unlock();
}
System.out.println(Thread.currentThread().getName() + ":" + oldVal);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// if (lock.tryLock()) {
// System.out.println("got lock!");
// }
} |
b026ee2a-82d3-4d6a-99e1-1b60ceb52952 | 6 | double[][] findEdges(double[][] smoothedGray) {
double[][] edges = new double[smoothedGray.length][smoothedGray[0].length];
for(int x = 0; x < edges.length; ++x) {
for(int y = 0; y < edges[x].length; ++y) {
if(x < 1 || x >= edges.length - 1 || y < 1 || y >= edges[x].length - 1) {
edges[x][y] = 0;
continue;
}
edges[x][y] = Math.hypot(edgeX(x, y, smoothedGray), edgeY(x, y, smoothedGray));
}
}
return edges;
} |
7d4a2d45-75f8-42e6-b8f6-3d6584e755bb | 1 | @Test
public void clientIdIsMax23Characters() {
// This should work
new ConnectMessage("12345678901234567890123", false, 10);
try {
// This should not work;
new ConnectMessage("123456789012345678901234", false, 10);
fail();
} catch (IllegalArgumentException e) {
}
} |
4853c218-92e8-47bb-a53b-219f57497d3e | 1 | protected Integer calcBPB_RootEntCnt() throws UnsupportedEncodingException {
byte[] bTemp = new byte[2];
for (int i = 17;i < 19; i++) {
bTemp[i-17] = imageBytes[i];
}
BPB_RootEntCnt = byteArrayToInt(bTemp);
System.out.println(BPB_RootEntCnt);
return BPB_RootEntCnt;
} |
c09e2c81-04c8-49e4-abd0-8f1ac7b9bc78 | 4 | private boolean output(int regNum)
{
boolean found = false;
int index = 0;
//searching for an available output card
while(!found && index < outputCards.registers.length)
{
if(outputCards.registers[index].text.getText().equals(""))
{
found = true;
}
else
{
index++;
}
}
if(found)
{
outputCards.registers[index].setValue
(memory.registers[regNum].getValue());
return true;
}
else
{
JOptionPane.showMessageDialog(null, "No available output card.");
return false;
}
} |
a39b5308-223b-4556-8d9c-b29399f9d00d | 5 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final XMLElement other = (XMLElement) obj;
if (this.element != other.element && (this.element == null || !this.element.equals(other.element))) {
return false;
}
return true;
} |
29e399d7-b5e9-4916-8b95-ad111a58e563 | 2 | public void clear() {
count = 0;
for (int n=0; n < this.cap; n++) {
keys[n] = null;
}
int cap2 = cap << 2;
for (int n=0; n < cap2; n++) {
hopidx[n] = 0;
}
} |
82d684d1-368b-45a7-b12d-70556719eda5 | 0 | @Test
public void canGetWord_whenWordExist() {
trie.add("abc");
assertTrue(trie.contains("abc"));
} |
da056239-7268-4d49-a0ec-dfdda5b08a41 | 8 | * @param outputLocation - location to extract to
*/
public static void extractZipTo (String zipLocation, String outputLocation) {
ZipInputStream zipinputstream = null;
try {
byte[] buf = new byte[1024];
zipinputstream = new ZipInputStream(new FileInputStream(zipLocation));
ZipEntry zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
String entryName = zipentry.getName();
int n;
if (!zipentry.isDirectory() && !entryName.equalsIgnoreCase("minecraft") && !entryName.equalsIgnoreCase(".minecraft") && !entryName.equalsIgnoreCase("instMods")) {
new File(outputLocation + File.separator + entryName).getParentFile().mkdirs();
FileOutputStream fileoutputstream = new FileOutputStream(outputLocation + File.separator + entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
}
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}
} catch (Exception e) {
Logger.logError("Error while extracting zip", e);
backupExtract(zipLocation, outputLocation);
} finally {
try {
zipinputstream.close();
} catch (IOException e) {
}
}
} |
e749aba3-27d5-4692-8ed2-56e787568b08 | 0 | @Basic
@Column(name = "username")
public String getUsername() {
return username;
} |
1f47d7c4-9578-4aa4-8c2f-8b7e2be489dc | 5 | public static void LSDsort(String[] a, int W) {
int N = a.length;
int R = 256;
String[] aux = new String[N];
// key indexed counting for each digit from right to left
for (int d = W - 1; d >= 0; d--) {
int[] count = new int[R + 1];
// count frequencies
for (int i = 0; i < N; i++)
count[a[i].charAt(d) + 1]++;
for (int r = 0; r < R; r++)
count[r + 1] += count[r];
for (int i = 0; i < N; i++)
aux[count[a[i].charAt(d)]++] = a[i];
for (int i = 0; i < N; i++)
a[i] = aux[i];
}
} |
39aceb98-bef8-4ccb-a4cc-e6cfe36be407 | 0 | @Override
public void fatalError(JoeException someException) {
System.out.println(someException.getMessage()) ;
this.errorOccurred = true;
} // end method fatalError |
faa01f3b-e979-477e-91fb-ae8b1fd549d4 | 4 | public void run() {
init();
this.requestFocus();
long startTime = System.nanoTime();
long previousTime = System.nanoTime();
long tempTime = System.nanoTime();
long currentTime;
double updateRate = 60.0;
long ns = 1000000000;
double delta = 0;
int updates = 0;
int frames = 0;
while (running) {
runningTime = (System.nanoTime() - startTime) / ns;
currentTime = System.nanoTime();
delta += ((currentTime - previousTime) * updateRate) / ns;
previousTime = currentTime;
// Makes the game update 60 times per second
while (delta >= 1) {
tick();
updates++;
delta--;
}
// Update as fast as possible
render();
frames++;
// Info printed to console each second
if ((currentTime - tempTime) >= ns) {
fps = frames;
System.out.println("FPS: " + fps + " TICKS: " + updates
+ " TIME: " + runningTime + " STATE: " + Game.state);
if (state == STATE.GAME) {
System.out.println(handler.playerObject.getX() + " | " + handler.playerObject.getY());
}
frames = 0;
updates = 0;
tempTime = currentTime;
}
}
} |
60edce65-7e37-4aba-9d9c-63069cc71661 | 1 | public boolean login(String userID, String password) {
// TODO Auto-generated method stub
if (getFact.login(userID, password)) {
return true;
}
else
return false;
} |
12044e44-83d9-4f8e-84f0-f80bc4977339 | 9 | public BookReader(String filename)
{
super(filename); //does nothing
//read in book - set book to "" if not found
Scanner input;
book = new ArrayList<String>();
try
{
input = new Scanner(new File(filename));
System.out.println("Loaded book.");
}
catch (Exception e)
{
System.out.println("Book \"" + filename + "\" not found.");
book.add("");
return;
}
StringBuilder currentChapter = new StringBuilder();
while (input.hasNext())
{
String next = input.nextLine();
if (next.length() > 0)
{
if (next.startsWith("CHAPTER") && !currentChapter.equals(""))
{
System.out.println(book.size() + ": " + currentChapter.length());
book.add(currentChapter.toString());
currentChapter = new StringBuilder();
}
next = next.toLowerCase();
for (int i = 0; i < next.length(); i++)
if ((next.charAt(i) >= 'a' && next.charAt(i) <= 'z') || next.charAt(i) == ' ')
currentChapter.append(next.charAt(i));
currentChapter.append(" ");
}
}
input.close();
} |
8e2aaf1d-8571-4464-a076-747ad9b6fefb | 9 | public void run() {
while (listen) {
try {
int encryptedSize = inStream.readInt();
int rawSize = inStream.readInt();
byte[] message = new byte[encryptedSize];
int readSoFar = 0;
while (readSoFar < encryptedSize)
readSoFar += inStream.read(message, readSoFar,
message.length - readSoFar);
message = ClientManager.encryptionLayer.decrypt(message);
if (rawSize != -1) {
message = ClientManager.compressionLayer.decompress(
message, rawSize);
}
if (message[0] == 0x10 || message[0] == 0x00)
ClientManager.textQueue.addMessage(message);
else
ClientManager.sysQueue.addMessage(message);
} catch (EOFException e) {
System.out.println("User " + ClientManager.userName
+ " is logging off");
break;
} catch (DataFormatException e) {
System.out.println("Server message corrupted!");
} catch (IOException e) {
System.out.println(e);
if (!listen)
return;
listen = false;
JOptionPane.showMessageDialog(null, "Server is down!");
ClientManager.logoff();
}
}
} |
624b32dd-0ff4-43b4-a8cf-86b768c448b4 | 1 | public void setSecondElement(T newSecond) {
if (newSecond == null) {
throw new NullPointerException();
}
this.secondElement = newSecond;
} |
3b90b5f9-5420-4a69-967b-7feb25989037 | 4 | public static String toString(JSONObject jo) throws JSONException {
StringBuffer sb = new StringBuffer();
sb.append(escape(jo.getString("name")));
sb.append("=");
sb.append(escape(jo.getString("value")));
if (jo.has("expires")) {
sb.append(";expires=");
sb.append(jo.getString("expires"));
}
if (jo.has("domain")) {
sb.append(";domain=");
sb.append(escape(jo.getString("domain")));
}
if (jo.has("path")) {
sb.append(";path=");
sb.append(escape(jo.getString("path")));
}
if (jo.optBoolean("secure")) {
sb.append(";secure");
}
return sb.toString();
} |
77479ffa-bc6a-49a7-9440-ed5f2be42ad9 | 9 | public int getPoints() {
int points = 0;
for (Card c : myCards) {
points += c.getFaceValue();
}
if (points > 21 && (this.numberOfAces() >= 1))
points -= 10;
if (points > 21 && (this.numberOfAces() >= 2))
points -= 10;
if (points > 21 && (this.numberOfAces() >= 3))
points -= 10;
if (points > 21 && (this.numberOfAces() == 4))
points -= 10;
return points;
} |
9c5bf7ad-f9c2-4015-8d45-bc36f93ee4d6 | 4 | @Override
public WorkSheetHandle[] getWorkSheets()
{
try
{
if( myfactory != null )
{
int numsheets = mybook.getNumWorkSheets();
if( numsheets == 0 )
{
throw new WorkSheetNotFoundException( "WorkBook has No Sheets." );
}
WorkSheetHandle[] sheets = new WorkSheetHandle[numsheets];
for( int i = 0; i < numsheets; i++ )
{
Boundsheet bs = mybook.getWorkSheetByNumber( i );
bs.setWorkBook( mybook );
sheets[i] = new WorkSheetHandle( bs, this );
}
return sheets;
}
return null;
}
catch( WorkSheetNotFoundException a )
{
log.warn( "getWorkSheets() failed: " + a );
return null;
}
} |
8c5b68f8-0bfd-4bbf-9325-e8c8c4192c7a | 3 | private ControlLogCaptureTypeMessage getLevel() {
if (verbose.isSelected()) {
return ControlLogCaptureTypeMessage.VERBOSE;
} else if (info.isSelected()) {
return ControlLogCaptureTypeMessage.INFO;
} else if (warning.isSelected()) {
return ControlLogCaptureTypeMessage.WARN;
} else {
return ControlLogCaptureTypeMessage.ERROR;
}
} |
3040244c-a24b-4903-8beb-b3cf87c21c0c | 4 | @Override
protected void onNotice(String sourceNick, String sourceLogin, String sourceHostname, String target, String notice)
{
super.onNotice(sourceNick, sourceLogin, sourceHostname, target, notice);
int i = 0;
Main.debug("Check! " + sourceNick + ", " + target + ", " + notice);
while(true)
{
Main.debug("Notice check: " + serverid + " - " + Main.gui.tabs.get(i).serverid, false);
if(Main.gui.tabs.get(i).serverid == serverid && Main.gui.tabs.get(i).title.equalsIgnoreCase(serverip))
{
Main.gui.tabs.get(i).addMessage(sourceNick + ": " + target + ", " + notice);
break;
}
else
{
if(i > Main.gui.tabs.size())
{
break;
}
i++;
}
}
} |
04db91b4-d8bb-4859-bc3c-e72e1504a62d | 2 | private void drawCurrentLocation(Graphics2D g2)
{
if ("hide".equals(System.getProperty("info.gridworld.gui.selection")))
return;
if (currentLocation != null)
{
Point p = pointForLocation(currentLocation);
g2.drawRect(p.x - cellSize / 2 - 2, p.y - cellSize / 2 - 2,
cellSize + 3, cellSize + 3);
}
} |
fab8d1d2-100f-4a5f-9375-3a214fd049ec | 5 | private void loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loginActionPerformed
try {
// TODO add your handling code here:
//System.out.println(username.getText());
//System.out.println(password.getText());
String name=username.getText();
String pass=password.getText();
String checkname = null;
String checkpass;
MyCon = new SQLConnection();
c = MyCon.getConnection("journal");
stmt = c.createStatement();
SQL = "SELECT * FROM journal.profile;";
rs = stmt.executeQuery(SQL);
while(rs.next()){
checkname = rs.getString("username");
checkpass = rs.getString("password");
if(checkname.toUpperCase().equals(name.toUpperCase()) && checkpass.equals(pass)){
found = 1;
break;
}
}
if(found == 1){
MyCon.useUsername(checkname);
new ShowProfile().show();
System.out.println("Login Ok");
this.dispose();
}
else{
System.out.println("Login Fail");
loginError.setVisible(true);
}
} catch (SQLException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_loginActionPerformed |
2b55ef57-907c-41d6-9629-d89aa991921d | 8 | public Object getFontSmoothingValue()
{
switch(font_smoothing_value)
{
default:
case 0:
return RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT;
case 1:
return RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;
case 2:
return RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
case 3:
return RenderingHints.VALUE_TEXT_ANTIALIAS_GASP;
case 4:
return RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HBGR;
case 5:
return RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB;
case 6:
return RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VBGR;
case 7:
return RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_VRGB;
}
} |
f73b3527-1adf-48ee-86a2-0d3eb8ae5b00 | 0 | public String getServiceEmployeeId() {
return serviceEmployeeId;
} |
04445201-cba7-40cd-82a4-147b5a35b047 | 1 | private void prepareFiguresChain(FiguresChain figuresChain) {
if (Objects.isNull(Chessboard.this.figureChain)) {
Chessboard.this.figureChain = figuresChain;
previousFiguresChain = figuresChain;
} else {
previousFiguresChain.setNextFigure(figuresChain);
previousFiguresChain = figuresChain;
}
} |
85cd7854-9b78-4c5f-9311-b88a38c19a23 | 1 | public List<AlbumType> getAlbum() {
if (album == null) {
album = new ArrayList<AlbumType>();
}
return this.album;
} |
422d6271-f09f-4fd7-8c8d-c09a4c95b827 | 2 | private boolean checkLeft(int x, int y, int z){
int dz = z + 1;
if(dz > CHUNK_WIDTH - 1){
return false;
}else if(chunk[x][y][dz] != 0){
return true;
}else{
return false;
}
} |
facdb2ca-12b0-4a7c-9972-07017db62b88 | 6 | public Stencils()
{
super("Stencils");
try
{
String filename = Stencils.class.getResource(
"/com/mxgraph/examples/swing/shapes.xml").getPath();
Document doc = mxXmlUtils.parseXml(mxUtils.readFile(filename));
Element shapes = doc.getDocumentElement();
NodeList list = shapes.getElementsByTagName("shape");
for (int i = 0; i < list.getLength(); i++)
{
Element shape = (Element) list.item(i);
mxStencilRegistry.addStencil(shape.getAttribute("name"),
new mxStencil(shape)
{
@Override
protected mxGraphicsCanvas2D createCanvas(
final mxGraphics2DCanvas gc)
{
// Redirects image loading to graphics canvas
return new mxGraphicsCanvas2D(gc.getGraphics())
{
@Override
protected Image loadImage(String src)
{
// Adds image base path to relative image URLs
if (!src.startsWith("/")
&& !src.startsWith("http://")
&& !src.startsWith("https://")
&& !src.startsWith("file:"))
{
src = gc.getImageBasePath() + src;
}
// Call is cached
return gc.loadImage(src);
}
};
}
});
}
mxGraph graph = new mxGraph();
Object parent = graph.getDefaultParent();
graph.getModel().beginUpdate();
try
{
Object v1 = graph
.insertVertex(parent, null, "Hello", 20, 20, 80, 30,
"shape=and;fillColor=#ff0000;gradientColor=#ffffff;shadow=1");
Object v2 = graph.insertVertex(parent, null, "World!", 240,
150, 80, 30, "shape=xor;shadow=1");
graph.insertEdge(parent, null, "Edge", v1, v2);
}
finally
{
graph.getModel().endUpdate();
}
mxGraphComponent graphComponent = new mxGraphComponent(graph)
{
// Sets global image base path
@Override
public mxInteractiveCanvas createCanvas()
{
mxInteractiveCanvas canvas = super.createCanvas();
canvas.setImageBasePath("/com/mxgraph/examples/swing/");
return canvas;
}
};
getContentPane().add(graphComponent);
}
catch (Exception e)
{
e.printStackTrace();
}
} |
8a01e97b-f3b3-4bed-9574-97d57428e3c5 | 6 | public static int minDepthOf(Node root) {
if(root == null)
return -1;
if(root.left == null && root.right == null)
return 0;
else if(root.left == null)
return 1+minDepthOf(root.right);
else if(root.right == null)
return 1+minDepthOf(root.left);
else
return (minDepthOf(root.left)>minDepthOf(root.right)) ? (1+minDepthOf(root.right)) : (1+minDepthOf(root.left));
} |
cdbc66c9-4567-4d1d-9b10-0aa2c5f0c366 | 5 | @Override
public boolean runsIntoBidimensional(Individual otherI) {
return (super.getX()==otherI.getX() || this.x1==otherI.getX() || super.getX()==otherI.getX1()) &&
(super.getY()==otherI.getY() || this.y1==otherI.getY() || super.getY()==otherI.getY1());
} |
ad2c9ad9-3d8f-4025-a1b2-85f798d6d142 | 3 | public static File resolve(String file, File out) {
File f = new File(file);
if (!(f.isAbsolute() && f.exists())) {
f = new File(out, file);
}
if (!f.exists()) {
throw new IllegalArgumentException("File not found: " + file);
}
return f;
} |
3b7aa137-8b49-415f-b053-6ea5a48c8b9b | 9 | public static void main(String[] args) throws IOException {
path = "c:\\Users\\Djordje\\Dropbox\\Matlab\\H-GCRF_HCUP_v2.1_yearly\\pctdata\\grid_sid_yearly\\";
loadProperties(path + "\\size.properties");
Runtime rt = Runtime.getRuntime();
long totalMem = rt.totalMemory();
long maxMem = rt.maxMemory();
long freeMem = rt.freeMemory();
double megs = 1048576.0;
System.err.println("Total Memory: " + totalMem + " (" + (totalMem / megs) + " MiB)");
System.err.println("Max Memory: " + maxMem + " (" + (maxMem / megs) + " MiB)");
System.err.println("Free Memory: " + freeMem + " (" + (freeMem / megs) + " MiB)");
//za edge
dataPath = path + "/podaci_ts1";
int Mrd = M;
int Nrd = N_malo;
int Mtest = M;
int Ntest = N;
testDataPath = path + "/podaci_tsall.csv";
outputFilePath = path + "/podaci_tsall_clusters.csv";
variancesOutput = path + "/podaci_ts1_variances.csv";
splitter = " ";
numberOfClusters = 2;
boolean treeIsBuilt = false;
// za prediktore zakomentarisi
//////// ArrayList<ArrayList<String>> predictors = new ArrayList<>();
//////// for (int i = 1; i <= numberOfPredictors; i++) {
//////// ArrayList<String> ithPredoctor = new ArrayList<>();
//////// ithPredoctor.add(path + "/podaci_predictor_" + i + "_ts1");
//////// ithPredoctor.add(path + "/podaci_predictor_" + i + "_tsall.csv");
//////// predictors.add(ithPredoctor);
//////// }
////////
//////// Mtest = Mpred;
//////// Ntest = N_pred_all;
//////// for (int p = 0; p < predictors.size(); p++) { //todo finish
//////// System.out.println("Training data on: " + predictors.get(p).get(0));
//////// dataPath = predictors.get(p).get(0);
//////// testDataPath = predictors.get(p).get(1);
//////// Mrd = Mpred;
//////// Nrd = Npred_malo;
//////// outputFilePath = path + "/podaci_tsall_precitor_" + (p + 1) + "_clusters.csv";
//////// variancesOutput = path + "/podaci_ts1_precitor_" + (p + 1) + "_variances.csv";
// za prediktore zakomentarisi iznad
BuildPCT buildPCT = new BuildPCT(numberOfClusters);
System.out.println("Training data is being loaded...");
readdata.ReadData.readData(dataPath, splitter, buildPCT, Mrd, Nrd);
buildPCT.setRootNode(null);
PCTNode rootnode;
try {
rootnode = buildPCT.inducePredictiveClusteringTree();
} catch (Exception ex) {
System.out.println(ex.getMessage());
return;
}
PredictiveClusteringTreeSingleton.getInstance().setPredictiveClusteringTree(rootnode);
System.out.println("We are now building the tree to fit the wanted number of clusters...");
ArrayList<PCTNode> leafs = new ArrayList<>();
int currentNumberOfClusters = numberOfLeafs(PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree());
GetAllLeafs(leafs, PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree());
System.out.println("Current number of clusters is " + currentNumberOfClusters);
while (currentNumberOfClusters < numberOfClusters) {
double minRegressionError = leafs.get(0).getRegressionError();
int position = 0;
for (int i = 0; i < leafs.size(); i++) {
if (minRegressionError > leafs.get(i).getRegressionError()) {
if (leafs.get(i).getDataset().length >= 2) {
minRegressionError = leafs.get(i).getRegressionError();
position = i;
}
}
}
if (position == 0 && leafs.get(position).getDataset().length < 2) {
System.out.println("Tree cannot generate more clusters with this data!");
leafs.clear();
GetAllLeafs(leafs, PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree());
break;
}
System.err.println(leafs.get(position));
buildPCT.setDataset(leafs.get(position).getDataset());
buildPCT.setTargetVariables(leafs.get(position).getTargetVariables());
buildPCT.setRootNode(leafs.get(position));
try {
buildPCT.inducePredictiveClusteringTree();
} catch (Exception ex) {
System.out.println(ex.getMessage());
break;
}
leafs.clear();
GetAllLeafs(leafs, PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree());
currentNumberOfClusters = numberOfLeafs(PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree());
System.out.println("Current number of clusters is " + currentNumberOfClusters);
////// i odavde
//////// if (numberOfClusters % numberOfLeafs(PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree()) == 2) {
//////// for (PCTNode pCTNode : leafs) {
//////// buildPCT.setRootNode(pCTNode);
//////// try {
//////// buildPCT.inducePredictiveClusteringTree();
//////// } catch (Exception ex) {
//////// System.out.println(ex.getMessage());
//////// break;
//////// }
//////// }
//////// } else if (numberOfClusters % numberOfLeafs(PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree()) == 2) {
//////// if (numberOfLeafs(PredictiveClusteringTreeSingleton.getInstance().getPredictiveClusteringTree()) == numberOfClusters) {
//////// treeIsBuilt = true;
//////// }
//////// }
// //////do ovde
}
PrintWriter writer = new PrintWriter(variancesOutput, "UTF-8");
for (int i = 0; i < leafs.size(); i++) {
leafs.get(i).setClusterName(i + 1);
writer.println(leafs.get(i).getClusterName() + ", " + leafs.get(i).getTargetVariance());
}
writer.close();
System.out.println("Predictive Clustering Tree has been built.");
System.out.println("\n INFERENCE TIME \n");
ReadTestData.readDataAndInfer(testDataPath, splitter, outputFilePath, Mtest, Ntest);
} |
9898a6a5-037a-4dc8-bffb-1b76fa6c2447 | 2 | public ResultSet selectAll()
{
ResultSet results=null;
if(conn!=null){
try
{
stmt = conn.createStatement();
results = stmt.executeQuery("select * from " + table_name);
results.close();
stmt.close();
}
catch (SQLException sqlExcept)
{
sqlExcept.printStackTrace();
}
}
return results;
} |
574bd92d-a9e3-4ed0-8af5-eb82c11d685c | 3 | @Override
public void ParseIn(Connection Main, Server Environment)
{
Room Room = Environment.RoomManager.GetRoom(Main.Data.CurrentRoom);
if (Room == null)
{
return;
}
String NewMotto = Main.DecodeString();
if(Main.Data.Motto.equals(NewMotto))
{
return;
}
Main.Data.Motto = NewMotto;
ServerMessage Message = new ServerMessage();
Environment.InitPacket(266, Message);
Environment.Append(Main.Data.RoomUser.VirtualId, Message);
Environment.Append(Main.Data.Look, Message);
Environment.Append(Main.Data.Sex==1 ? "M" : "F", Message);
Environment.Append(Main.Data.Motto, Message);
Environment.Append(Main.Data.AchievementsScore, Message);
Room.SendMessage(Message);
} |
a2bbefef-3f1f-41bc-a635-15f3ddbf3ac3 | 5 | public static LDAPUser getUserInfo(String crsid){
LDAPUser result = new LDAPUser();
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.lookup.cam.ac.uk:389");
Attributes a = null;
try{
DirContext ctx = new InitialDirContext(env);
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
SearchResult searchResult = ctx.search("ou=people,o=University of Cambridge,dc=cam,dc=ac,dc=uk", "(uid="+crsid+")", controls).next();
a = searchResult.getAttributes();
}catch(Exception e){
log.error(e.getMessage());
return null;
}
try {
log.debug("Trying to obtain data for user " + crsid);
result.setId(crsid);
log.debug("Trying to obtain displayName for user " + crsid);
result.setDisplayName(a.get("displayName").get().toString());
log.debug("Trying to obtain email address for user " + crsid);
result.setEmail(a.get("mail").get().toString());
log.debug("Trying to obtain Institutions for user " + crsid);
result.setInstitutions(toList(a.get("ou")));
log.debug("Trying to obtain roles for user " + crsid);
result.setRoles(toList(a.get("title")));
log.debug("Trying to obtain misAffiliation for user " + crsid);
try{
if(a.get("misAffiliation").get().toString().equals("staff")) {
result.setStudent(false);
}
log.debug("Successfully got misAffiliation");
} catch(NullPointerException e){
log.warn("Couldn't get misAffiliation! Probably returned null. User set to role student by default.");
}
log.debug("Trying to get the image for user" + crsid);
try{
byte[] x = (byte[])a.get("jpegPhoto").get();
result.setImage(new String(Base64.encodeBase64(x)));
}catch(NullPointerException e){
result.setImage(defaultImg());
}
} catch (NamingException e) {
log.error(e.getMessage());
return result;
}
log.debug("Returning user info for " + crsid);
return result;
} |
fb4558b2-696f-4eff-9e62-62c8fee56399 | 1 | protected void jump() {
if (!airborne)
jumping = true;
} |
0af50973-7859-4aaa-aa33-bcd8639efaac | 4 | private void refreshInformation() {
for (final File fileEntry : folder.listFiles()) {
StringBuffer content = new StringBuffer();
try {
FileReader fr = new FileReader(fileEntry.getAbsolutePath());
BufferedReader br = new BufferedReader(fr);
String line ="";
while ((line = br.readLine()) != null) {
line = (line.startsWith(".")) ? "."+line : line;
content.append(line + '\r' + '\n');
}
br.close();
mails.add(content.toString());
names.add(fileEntry.getName().substring(0,fileEntry.getName().length() - ".txt".length()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(mails.toString());
} |
35479905-b2a7-4a28-938a-0da0b29ee550 | 8 | private void parseStatus(UserState status, Map<String, Object> pageVariables) {
switch (status) {
case EMPTY_DATA:
case FAILED_AUTH:
case NO_SUCH_USER_FOUND:
case SQL_ERROR:
case USER_ALREADY_EXISTS:
pageVariables.put("errorMsg", status.getMessage());
break;
case WAIT_AUTH:
case WAIT_USER_REG:
case USER_ADDED:
pageVariables.put("infoMsg", status.getMessage());
break;
default:
pageVariables.put("userStatus", status.getMessage());
break;
}
} |
67ccd967-7fa3-4497-9deb-88fca63d6274 | 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 ("GTK+".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(SubscriberView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(SubscriberView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(SubscriberView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(SubscriberView.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 SubscriberView().setVisible(true);
}
});
} |
89a3e196-29cb-431e-a6ce-a20136479f45 | 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(GamePreferencesFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GamePreferencesFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GamePreferencesFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GamePreferencesFrame.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 GamePreferencesFrame().setVisible(true);
}
});
} |
288a7394-e529-4bdf-8704-46d3f99edb16 | 3 | public List<Case> getLiberte(){
Set<Case> libSet = new HashSet<>();
for (Case c1 : pierres){
for(Case c : (ArrayList<Case>)this.g.getCasesAutourDe(c1)){
if (c.caseLibre()){
libSet.add(c);
}
}
}
return new ArrayList<>(libSet);
} |
eb18bb1c-bbc6-4a94-b7db-d9d00402bf62 | 0 | public String getName() {
return name;
} |
514d0a18-b379-4b3b-a44c-f75e75c9ebc5 | 5 | int test2( ) throws MiniDB_Exception{
MiniDB db, db2;
BPlusTree bpt;
int points = 0, maxPoints = 5;
Random rng = new Random();
db = makeNewDB("test2.1" );
//
int recSize = 50;
String indexingFile = "file2.";
String indexedField = "field2.";
BPlusTree bpt50 = db.createNewBPlusTreeIndex( indexingFile, indexedField, 50 );
BPlusTreeLeafNode root50 = (BPlusTreeLeafNode)bpt50.getRootNode();
if( root50.hasRoomForAnotherRecord() ){ System.out.println( "a) +1" ); points++; }
else{ System.out.println( "a) -1" ); }
root50.setCurrNumRecordsOnBlock(1);
if( root50.hasRoomForAnotherRecord() ){ System.out.println( "b) +1" ); points++; }
else{ System.out.println( "b) -1" );}
root50.setCurrNumRecordsOnBlock(2);
if( !root50.hasRoomForAnotherRecord() ){ System.out.println( "c) +1" ); points++; }
else{ System.out.println( "c) -1" );}
db2 = makeNewDB("test2.2" );
BPlusTree bpt70 = db2.createNewBPlusTreeIndex( indexingFile, indexedField, 70 );
BPlusTreeLeafNode root70 = (BPlusTreeLeafNode)bpt70.getRootNode();
if( root70.hasRoomForAnotherRecord() ){ System.out.println( "d) +1" ); points++; }
else{ System.out.println( "d) -1" );}
root70.setCurrNumRecordsOnBlock(1);
if( !root70.hasRoomForAnotherRecord() ){ System.out.println( "e) +1" ); points++; }
else{ System.out.println( "e) -1" );}
System.out.println( "test 2: " + points + " of " + maxPoints );
return points;
} |
5a9c7a92-5d67-47f0-b49a-284aad8c133a | 2 | public User login(String username, String password, String forumId) {
for (int i = 0; i < forums.size(); i++) {
if (forums.get(i).getId().equals(forumId))
return forums.get(i).login(username, password);
}
return null;
} |
f90443d0-a565-4907-95f9-c6427323e562 | 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(ReporteHecho.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ReporteHecho.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ReporteHecho.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ReporteHecho.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 ReporteHecho().setVisible(true);
}
});
} |
07718997-a332-40e9-b570-3a65d013fc05 | 2 | public int getCard(int id) {
for (int i = 0; i < cards.length; i++) {
if (id == cards[i]) {
return i + 1;
}
}
return 0;
} |
4b010ada-0799-492b-8f6e-912f96797b23 | 5 | private void buttonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonSearchActionPerformed
String searchQuery = textSearch.getText().toUpperCase();
String agcoopCompany = "maininterface.ViewCompany";
String agcoopMember = "maininterface.ViewMember";
String agcoopSupplier = "maininterface.ViewSupplier";
String agcoopNonMember = "maininterface.ViewNonMember";
try{
if(viewTab.getSelectedComponent().getClass().getName().equals(agcoopCompany))
{
vC.getList(1, searchQuery);
}
else if(viewTab.getSelectedComponent().getClass().getName().equals(agcoopMember))
{
vM.getList(1, searchQuery);
}
else if(viewTab.getSelectedComponent().getClass().getName().equals(agcoopSupplier))
{
vS.getList(1, searchQuery);
}
else if(viewTab.getSelectedComponent().getClass().getName().equals(agcoopNonMember))
{
vNM.getList(1, searchQuery);
}
}
catch(Exception e) { }
// TODO add your handling code here:
}//GEN-LAST:event_buttonSearchActionPerformed |
4bb788c2-b087-4d0e-b93a-24f19b0708f9 | 2 | public Integer[] getParticipantsCount (Date d) {
Integer pc[] = {0, 0, 0, 0, 0, 0};
for (Trip t: getAllTrips(d)) {
River r = t.getRiver();
if (r != null) {
int ww = t.getRiver().getWwTopLevel()-1;
pc[ww] = pc[ww]+t.getGroupSize();
}
}
return pc;
} |
0dfe5c82-6322-403e-be6c-00a5b558253c | 2 | private void initPotential() {
for (int i = 0; i < MicromouseRun.BOARD_MAX; i++) {
for (int j = 0; j < MicromouseRun.BOARD_MAX; j++) {
potential[i][j] = MicromouseRun.BOARD_MAX * MicromouseRun.BOARD_MAX + 1;
}
}
} |
c26ecdbd-63c7-4be1-b96a-0a52f91a5189 | 5 | private void initDragAndDrop() {
smartFolderTree.setDropTarget(new DropTarget() {
@Override
public synchronized void drop(DropTargetDropEvent dtde) {
try {
Transferable transfer = dtde.getTransferable();
if (transfer.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
List objects = (List) transfer.getTransferData(DataFlavor.javaFileListFlavor);
for (Object object : objects) {
if (object instanceof File) {
File source = (File) object;
if (source.isDirectory()) {
DirectoryMonitor.registerDirectory(source);
}
}
}
}
} catch (IOException | UnsupportedFlavorException e) {
} finally {
dtde.dropComplete(true);
}
}
});
} |
51500e6d-2bf3-4a48-8bd5-f648b7bc43a5 | 9 | private void init(ForecastIO fio){
if(fio.hasFlags()){
if(fio.getFlags().names().contains("darksky-unavailable"))
this.flags.put("darksky-unavailable", toStringArray(fio.getFlags().get("darksky-unavailable").asArray()));
if(fio.getFlags().names().contains("darksky-stations"))
this.flags.put("darksky-stations", toStringArray(fio.getFlags().get("darksky-stations").asArray()));
if(fio.getFlags().names().contains("datapoint-stations"))
this.flags.put("datapoint-stations", toStringArray(fio.getFlags().get("datapoint-stations").asArray()));
if(fio.getFlags().names().contains("isd-stations"))
this.flags.put("isd-stations", toStringArray(fio.getFlags().get("isd-stations").asArray()));
if(fio.getFlags().names().contains("lamp-stations"))
this.flags.put("lamp-stations", toStringArray(fio.getFlags().get("lamp-stations").asArray()));
if(fio.getFlags().names().contains("metar-stations"))
this.flags.put("metar-stations", toStringArray(fio.getFlags().get("metar-stations").asArray()));
//TODO metno-licenses
if(fio.getFlags().names().contains("sources"))
this.flags.put("sources", toStringArray(fio.getFlags().get("sources").asArray()));
try {
this.units = fio.getFlags().get("units").asString();
}
catch (NullPointerException npe) {
this.units = "no data";
}
}
} |
dd944649-8935-4c53-b612-cddf3aa7ec03 | 9 | @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof User))
return false;
User other = (User) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (surname == null) {
if (other.surname != null)
return false;
} else if (!surname.equals(other.surname))
return false;
return true;
} |
3efafebd-444d-4bed-997f-bd1d9b799712 | 9 | @Override
public void setAmmoRemaining(int amount)
{
final int oldAmount=ammunitionRemaining();
if(amount==Integer.MAX_VALUE)
amount=20;
setUsesRemaining(amount);
if((oldAmount>0)
&&(amount==0)
&&(ammunitionCapacity()>0))
{
boolean recover=false;
for(final Enumeration<Ability> a=effects();a.hasMoreElements();)
{
final Ability A=a.nextElement();
if((A!=null)&&(!A.isSavable())&&(A.invoker()==null))
{
recover=true;
delEffect(A);
}
}
if(recover)
recoverOwner();
}
} |
fe359d69-93a3-46c0-8689-01452b3219e6 | 5 | @Override
public void store() {
Map<Class<? extends Material>, List<Map<String, Object>>> description
= new HashMap<Class<? extends Material>, List<Map<String, Object>>>();
for (Material m : this.stockToList()) {
Class<? extends Material> c = m.getClass();
if (description.containsKey(c)) {
description.get(c).add(m.getDescription());
} else {
List<Map<String, Object>> newList = new ArrayList<Map<String, Object>>();
newList.add(m.getDescription());
description.put(c, newList);
}
}
ConfigXML.store(description, KEY_STOCK_FILE, KEY_STOCK_VERSION);
} |
3cece7e3-76bc-414e-884d-19ab4bd5d2b1 | 0 | public Clock getClockForGroup() {
return clockForGroup;
} |
e422be35-c70f-4585-becb-4617e5408b5f | 9 | public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String player = "x";
TicTacToe game = new TicTacToe();
boolean done = false;
while(!done)
{
System.out.println(game.toString());
System.out.println("Row for " + player + " (-1 to exit): ");
int row = in.nextInt() - 1;
if(row < 0) done = true;
else
{
System.out.println("Column for " + player + ": ");
int column = in.nextInt() - 1;
game.set(row, column, player);
if(player.equals("x")) player = "o";
else player = "x";
}
int i = 0, j = 0;
if(game.getPlayer(i, j).equals(player) && game.getPlayer((i++), j).equals(player)
&& game.getPlayer((i + 2), j).equals(player) || game.getPlayer(i, j).equals(player)
&& game.getPlayer(i, (j++)).equals(player) && game.getPlayer(i, (j + 2)).equals(player))
System.out.println(player + "won the game!");
else
System.out.println("shiet");
}
} |
8ce67f84-b0c1-46df-bba1-bb109d7abefc | 4 | public void paintComponent( java.awt.Graphics g )
{
if ( !(drawStripes = isOpaque( )) )
{
super.paintComponent( g );
return;
}
// Paint zebra background stripes
updateZebraColors( );
final java.awt.Insets insets = getInsets( );
final int w = getWidth( ) - insets.left - insets.right;
final int h = getHeight( ) - insets.top - insets.bottom;
final int x = insets.left;
int y = insets.top;
int rowHeight = 16; // A default for empty tables
final int nItems = getRowCount( );
for ( int i = 0; i < nItems; i++, y+=rowHeight )
{
rowHeight = getRowHeight( i );
g.setColor( rowColors[i&1] );
g.fillRect( x, y, w, rowHeight );
}
// Use last row height for remainder of table area
final int nRows = nItems + (insets.top + h - y) / rowHeight;
for ( int i = nItems; i < nRows; i++, y+=rowHeight )
{
g.setColor( rowColors[i&1] );
g.fillRect( x, y, w, rowHeight );
}
final int remainder = insets.top + h - y;
if ( remainder > 0 )
{
g.setColor( rowColors[nRows&1] );
g.fillRect( x, y, w, remainder );
}
// Paint component
setOpaque( false );
super.paintComponent( g );
setOpaque( true );
} |
2c5e4246-4285-4e80-8587-10f0143bd9de | 9 | @Override
public Object getValueAt(int rowIndex, int columnIndex) {
ContaPagar ContaPagar = filtrados.get(rowIndex);
switch (columnIndex) {
// "ID","Cliente","Data","Vencimento","Observação","Valor","Pago"};
case 0:
return ContaPagar.getId();
case 1:
if (ContaPagar.getParceiro().isFisica()) {
return ContaPagar.getParceiro().getNome();
}
return ContaPagar.getParceiro().getRazaoSocial();
case 2:
return Formatar.formatarData(ContaPagar.getData());
case 3:
return Formatar.formatarData(ContaPagar.getVencimento());
case 4:
return ContaPagar.getObs();
case 5:
return Formatar.formatarNumero(ContaPagar.getValor());
case 6:
if(ContaPagar.isPago())
return "SIM";
return "NÃO";
default:
throw new IndexOutOfBoundsException("columnIndex out of bounds");
}
} |
8ca3a3dd-d4d9-4210-a617-25a0f1be764c | 6 | * @return Whether, given the two undo patches, they should be merged
* instead of pushing the new one.
* @note It is immaterial which UndoPatch is newer.
*/
private static boolean undoCompatible(UndoPatch up1, UndoPatch up2) {
if ((up1.opTag != up2.opTag && up2.opTag != OPT.SPACE) || up1.startRow != up2.startRow) {
return false;
}
if (up1.oldText.length != up1.patchText.length || up1.oldText.length != up2.oldText.length
|| up2.patchText.length != up2.patchText.length) {
return false;
}
return true;
} |
082630d6-1694-4af0-a8c1-3b9eeb5e8487 | 5 | public static boolean isBalanced(String brackets) {
if (brackets == null || brackets.isEmpty()) {
return true;
}
if (brackets.contains("()")) {
return isBalanced(brackets.replaceFirst("\\(\\)", ""));
}
if (brackets.contains("[]")) {
return isBalanced(brackets.replaceFirst("\\[\\]", ""));
}
if (brackets.contains("{}")) {
return isBalanced(brackets.replaceFirst("\\{\\}", ""));
}
return false;
} |
f309ca36-e464-471b-924c-8c9093f9cb6a | 6 | private Integer pickItemInList(Collection<BorrowableStock> list) {
String input = null;
Boolean valid = false;
while (!valid) {
System.out.println("Select an item in the following list :");
for (BorrowableStock b : list) {
String borrowableName = b.getName();
System.out.println(" " + b.getId() + ". " + borrowableName);
}
System.out.println(" b. Go back");
try {
input = br.readLine();
} catch (IOException e) {
// do nothing
}
for (BorrowableStock b : list) {
Integer id = b.getId();
if (input.equals(Integer.toString(id))) {
return id;
}
}
if (input.equalsIgnoreCase("b")) {
return -1;
}
}
return -1;
} |
5abe83fe-e1c9-4221-91f4-bd374114cd2c | 2 | public boolean isValidType() {
return ifaces.length == 0 || (clazz == null && ifaces.length == 1);
} |
0cb0f069-ca28-48ea-9081-aba1e2f72279 | 9 | static int swap(int x, int k){
int pos = 0;
while((x/pow[pos])%10>0){
pos++;
}
int tp = 0;
if(k==0){
if(pos+4>7)return 0;
tp = pos+4;
}
else if(k==1){
if((pos+1)%4==0)return 0;
tp = pos+1;
}
else if(k==2){
if(pos-4<0)return 0;
tp = pos-4;
}
else if(k==3){
if(pos%4==0)return 0;
tp = pos-1;
}
int d = x/pow[tp]%10;
return x - d*pow[tp] + d*pow[pos];
} |
e90e0839-2156-40ed-82a5-55004d9015ed | 3 | public static String selectListPageParam(Map<String, Object> paramMap) throws SQLException{
@SuppressWarnings("unchecked")
java.util.Map<String,Object> sqlWhereMap = (Map<String, Object>) (paramMap.get("sqlWhereMap")==null ? "": paramMap.get("sqlWhereMap"));
BEGIN();
SELECT(Permission.COLUMNS);
FROM(Permission.TABLE_NAME);
if (sqlWhereMap != null && !"".equals(sqlWhereMap)) {
//拼接查询条件
WHERE(BaseModel.getSqlWhereWithValues(sqlWhereMap));
}
return SQL();
} |
fe464ea6-0137-42cd-a2d5-637d15287d4d | 8 | @Override
public void keyReleased(int keyCode, char keyChar) {
if(keyCode == 200) {
if(!player.isMoving) {
player.isMoving = false;
}
}
if(keyCode == 203) {
if(!player.isMoving) {
player.isMoving = false;
}
}
if(keyCode == 205) {
if(!player.isMoving) {
player.isMoving = false;
}
}
if(keyCode == 208) {
if(!player.isMoving) {
player.isMoving = false;
}
}
} |
3a98c8d8-d10d-4aca-b004-2a59608ae439 | 1 | private boolean jj_2_53(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_53(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(52, xla); }
} |
1476903b-750e-4a3d-8736-cafb280696fe | 2 | public String toSQL() {
if (this.hasParameters()) {
throw new RuntimeException("parameters in SQL not set");
} else {
if (this.sqlCache == null) {
this.sqlCache = builder.toString();
}
return sqlCache;
}
} |
08192cb7-f260-4f43-bc3f-4de570a809ee | 5 | public void print() {
System.out.println();
System.out
.println("Number \t Head \t Tail \t Type \t Dest \t Value \t Ready \t");
System.out
.println("----------------------------------------------------------------------- ");
for (int i = 0; i < tuples.length; i++) {
ROBTuple tuple = tuples[i];
System.out.println(" ");
System.out.print(i + 1);
System.out.print("\t");
if (head == i) {
System.out.print(" YES");
}
System.out.print("\t");
if (tail == i) {
System.out.print(" YES");
}
if (tuple != null) {
System.out.print("\t " + tuple.getType() + "\t "
+ tuple.getDest() + "\t ");
if (tuple.getValue() != "") {
System.out
.print(tuple.getValue() + " " + tuple.isReady());
} else {
System.out.print("\t " + tuple.isReady());
}
}
}
} |
2003a2fb-c9b2-453e-b748-99aa0704fdf0 | 6 | public static Cons cppGetParameterizedMemberVariableDefinitions(Stella_Class renamed_Class) {
{ Cons membervardefs = Stella.NIL;
{ Slot slot = null;
Cons iter000 = renamed_Class.classLocalSlots.theConsList;
Cons collect000 = null;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
slot = ((Slot)(iter000.value));
if (Stella_Object.storageSlotP(slot) &&
(StorageSlot.nativeSlotP(((StorageSlot)(slot))) &&
StorageSlot.slotHasClassParameterTypeP(((StorageSlot)(slot)), renamed_Class))) {
if (collect000 == null) {
{
collect000 = Cons.cons(StorageSlot.cppYieldParameterizedMemberVarTree(((StorageSlot)(slot)), renamed_Class), Stella.NIL);
if (membervardefs == Stella.NIL) {
membervardefs = collect000;
}
else {
Cons.addConsToEndOfConsList(membervardefs, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(StorageSlot.cppYieldParameterizedMemberVarTree(((StorageSlot)(slot)), renamed_Class), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
}
return (membervardefs);
}
} |
ef6a632d-7f78-4116-a484-de9ad663239d | 7 | public ArrayList<Guest> searchForGuestDB(String status, Connection con, String... names) {
Guest guest = null;
String SQLString = "";
ArrayList<Guest> guestList = new ArrayList<>();
if (status.equals("both")) {
SQLString = "SELECT * "
+ "FROM guests "
+ "WHERE UPPER(first_name) LIKE UPPER(?) AND UPPER(last_name) LIKE UPPER(?)";
}
if (status.equals("firstName")) {
SQLString = "SELECT * "
+ "FROM guests "
+ "WHERE UPPER(first_name) LIKE UPPER(?)";
}
if (status.equals("lastName")) {
SQLString = "SELECT * "
+ "FROM guests "
+ "WHERE UPPER(last_name) LIKE UPPER(?)";
}
PreparedStatement statement = null;
try {
statement = con.prepareStatement(SQLString);
if (status.equals("both")) {
statement.setString(1, "%" + names[0] + "%"); // Her indsættes "%navn%" på "?", for at opnå den ønskede søgning "WHERE first_name LIKE '%navn%'".
statement.setString(2, "%" + names[1] + "%");
}
else {
statement.setString(1, "%" + names[0] + "%");
}
ResultSet rs = statement.executeQuery();
while (rs.next()) {
guest = new Guest(rs);
guestList.add(guest);
}
}
catch (SQLException e) {
System.out.println("Fail in GuestMapper.searchForGuestDB()");
System.out.println(e.getMessage());
}
finally
{
try {
statement.close();
}
catch (SQLException e) {
System.out.println("Fail in GuestMapper.searchForGuestDB()");
System.out.println(e.getMessage());
}
}
return guestList;
} |
348df66c-d6b9-4f40-ad92-7c9245845c44 | 9 | @SuppressWarnings("unchecked")
public <D extends AbstractDAO> D findDAO(Class<D> clazz)
throws DBException
{
if (null == jdbc)
throw new DBException("Cannot attach DAO to " + this + ": database not open");
D dao = (D)daoMap.get(clazz);
if (null == dao)
{
try
{
Constructor<?> ctr = clazz.getDeclaredConstructor(this.getClass());
ctr.setAccessible(true);
dao = (D) ctr.newInstance(this);
for (Class<? extends AbstractDAO> dep : dao.dependencies())
findDAO(dep);
dao.updateSchema();
daoMap.put(clazz, dao);
} catch (NoSuchMethodException e)
{
throw new ExceptionInInitializerError("DAO " + clazz
+ " does not have a single argument constructor that accepts a "
+ getClass().getName());
} catch (InstantiationException e)
{
throw new ExceptionInInitializerError("DAO " + clazz + " is abstract");
} catch (IllegalAccessException e)
{
throw (Error) new ExceptionInInitializerError("No access to DAO " + clazz
+ " constructor").initCause(e);
} catch (InvocationTargetException e)
{
throw (Error) new ExceptionInInitializerError(
"Exception in constructor of DAO " + clazz).initCause(e
.getTargetException());
}
}
return dao;
} |
f4dad2c7-7ade-48f2-bdb4-3e61f0f28907 | 1 | @Override
protected PlayerStartPositionCTF createPlayerStartPosition(Player player) {
if (player == null)
throw new IllegalArgumentException("The given arguments are invalid!");
return new PlayerStartPositionCTF(grid, player);
} |
9db9187a-833d-46c5-a33a-cfa6d2b145cc | 9 | public static void main(String[] args) throws IOException {
try {
/* parse the command line arguments */
// create the command line parser
CommandLineParser parser = new PosixParser();
// create the Options
Options options = new Options();
options.addOption("h", "help", false, "");
options.addOption("o", "output", true, "File to write list of tiles to (required)");
options.addOption("H", "host", true, "osm2pgsql db host");
options.addOption("P", "port", true, "osm2pgsql db port");
options.addOption("D", "db", true, "osm2pgsql db name");
options.addOption("U", "user", true, "osm2pgsql db user");
options.addOption("W", "password", true, "osm2pgsql db password");
// parse the command line arguments
CommandLine line = parser.parse( options, args );
if (line.hasOption("help"))
printUsage(options);
String outputFileName = null;
if (line.hasOption("output"))
outputFileName = line.getOptionValue("output");
String dbHost;
if (!line.hasOption("host"))
dbHost = "localhost";
else
dbHost = line.getOptionValue("host");
String dbPort;
if (!line.hasOption("port"))
dbPort = "5432";
else
dbPort = line.getOptionValue("port");
String dbName;
if (!line.hasOption("db"))
dbName = "osm";
else
dbName = line.getOptionValue("db");
String dbUser;
if (!line.hasOption("user"))
dbUser = "osm";
else
dbUser = line.getOptionValue("user");
String dbPassword;
if (!line.hasOption("password"))
dbPassword = "osm";
else
dbPassword = line.getOptionValue("password");
// setup the FileWriter
// use STDOUT if no filename was given
FileWriter tileListFileWriter;
if (outputFileName == null)
tileListFileWriter = new FileWriter(FileDescriptor.out);
else
tileListFileWriter = new FileWriter(outputFileName);
tileListWriter = new BufferedWriter(tileListFileWriter);
gf = new GeometryFactory();
// define an arbitary area to generate tiles within (this one is NSW, Australia)
ArrayList<Geometry> nsw = new ArrayList<Geometry>();
nsw.add(gf.toGeometry(new Envelope(15676317.2673864,17701592.7270857, -4444354.61727114,-3338769.41530374)));
// everything worldwide -- bluemarble
imageryBoundaries = nsw;
renderAllTiles(0,0,0, 0, 8);
// landsat
imageryBoundaries = nsw;
renderAllTiles(0,0,0, 9, 12);
// nearmap
// connect to a local postgresql
Class.forName("org.postgresql.Driver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:postgresql://" + dbHost + ":" + dbPort + "/" + dbName, dbUser, dbPassword);
imageryBoundaries = grabBoundaryPolygonsFromPostgres(conn, "nearmap");
renderAllTiles(0,0,0, 13, 17); // start at 0,0,0 to get up to z13 quickly, but just start printing from z13 up
// finish up
tileListWriter.close();
// print tile summary
System.out.println("");
System.out.println("###");
int totalTiles = totalTiles(0, 15);
System.out.println(tileCount + " of " + totalTiles + " tiles (" + String.format("%.4f", (float)(tileCount * 100) / totalTiles) + "%)");
} catch (Exception e) {
e.printStackTrace();
}
} |
0e2fc963-9660-47d0-b1de-cbca89afb9c9 | 9 | public static void main(String[] args) {
Map<String, Integer> tempMap = new HashMap<String, Integer>();
tempMap.put("a", 1);
tempMap.put("b", 2);
tempMap.put("c", 3);
// JDK1.4中
// 遍历方法一 hashmap entrySet() 遍历
System.out.println("方法一");
Iterator<Entry<String, Integer>> it = tempMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
Object value = entry.getValue();
System.out.println("key=" + key + " value=" + value);
}
System.out.println("");
// JDK1.5中,应用新特性For-Each循环
// 遍历方法二
System.out.println("方法二");
for (Map.Entry<String, Integer> entry : tempMap.entrySet()) {
String key = entry.getKey().toString();
String value = entry.getValue().toString();
System.out.println("key=" + key + " value=" + value);
}
System.out.println("");
// 遍历方法三 hashmap keySet() 遍历
System.out.println("方法三");
for (Iterator i = tempMap.keySet().iterator(); i.hasNext();) {
Object obj = i.next();
System.out.println(obj);// 循环输出key
System.out.println("key=" + obj + " value=" + tempMap.get(obj));
}
for (Iterator i = tempMap.values().iterator(); i.hasNext();) {
Object obj = i.next();
System.out.println(obj);// 循环输出value
}
System.out.println("");
// 遍历方法四 treemap keySet()遍历
System.out.println("方法四");
for (Object o : tempMap.keySet()) {
System.out.println("key=" + o + " value=" + tempMap.get(o));
}
System.out.println("11111");
// java如何遍历Map <String, ArrayList> map = new HashMap <String,
// ArrayList>();
System.out.println("java 遍历Map <String, ArrayList> map = new HashMap <String, ArrayList>();");
Map<String, ArrayList> map = new HashMap<String, ArrayList>();
Set<String> keys = map.keySet();
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
String key = iterator.next();
ArrayList arrayList = map.get(key);
for (Object o : arrayList) {
System.out.println(o + "遍历过程");
}
}
System.out.println("2222");
Map<String, List> mapList = new HashMap<String, List>();
for (Map.Entry entry : mapList.entrySet()) {
String key = entry.getKey().toString();
List<String> values = (List) entry.getValue();
for (String value : values) {
System.out.println(key + " --> " + value);
}
}
} |
5edffd94-36d1-498f-a22f-f0e9a5ed2344 | 2 | public static void main(String[] args) {
ReadByteFile reader = new ReadByteFile("punches.png");
try {
punches = reader.openFile();
} catch (IOException ex) {
Logger.getLogger(PunchFormatter.class.getName()).log(Level.SEVERE, null, ex);
}
WriteByteFile writer = new WriteByteFile("punches.txt");
try {
writer.writeToFile(punches);
} catch (IOException ex) {
Logger.getLogger(PunchFormatter.class.getName()).log(Level.SEVERE, null, ex);
}
} |
38794207-d8ab-4c9e-b4ce-1621e2e41c44 | 9 | private boolean searchWord(TrieNode _root, String _word) {
if(null == _root || null == _word || "".equals(_word))
return false;
char[] cs = _word.toCharArray();//将字符串转化为字符数组
for(int i = 0; i < cs.length; i++){
int index;
if(cs[i] >= 'A' && cs[i] <= 'Z'){
index = cs[i]-'A';
}
else if(cs[i] >= 'a' && cs[i] <= 'z')
index = cs[i] - 'a';
else
return false;
TrieNode child_node = _root._children[index];
if(child_node == null) {
return false;
}
else {
_root = child_node;
}
}
return _root.isWord();
} |
aa9166e6-bee3-4766-b418-195f3dde9185 | 1 | public void addFlyUp(String message) {
flyups.add(new FlyUp(message));
while(flyups.size() > 5) {
flyups.remove(0);
}
repositionFlyUps();
} |
5a799877-195f-47b1-a6f2-68dae583a5b1 | 5 | private void createNodes(DefaultMutableTreeNode top) {
DefaultMutableTreeNode generalForums = null;
DefaultMutableTreeNode category = null;
DefaultMutableTreeNode subCategory = null;
DefaultMutableTreeNode question = null;
generalForums = new DefaultMutableTreeNode("General Forums");
top.add(generalForums);
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.connectToDB();
// Query for total Forum topics
// Gets all topics in the forums.
String sql = "SELECT * FROM `ForumCategories`";
ResultSet rs = db.getResults(conn, sql);
int categoryID = 0;
int subCategoryID = 0;
try {
while (rs.next())
{
category = new DefaultMutableTreeNode(rs.getString("Name"));
generalForums.add(category); //Adds Category to General Forums
//Queries for all the subCategories inside the main generalForums
//IE: Math is a category of the Category "Queries"
categoryID = rs.getInt("CategoryID");
String subSQL = "SELECT * FROM `ForumSubCategories` WHERE CategoryID = '"+categoryID+"'";
ResultSet subRS = db.getResults(conn, subSQL);
while (subRS.next())
{
subCategory = new DefaultMutableTreeNode(subRS.getString("Name"));
category.add(subCategory); //Adds subCategory "math" to Category "queries"
//Queries for all questions inside subcategory
subCategoryID = subRS.getInt("SubCategoryID");
String questionSQL = "SELECT * FROM `ForumQuestions` "
+ "WHERE SubCategoryID = '"+subCategoryID+"'";
if (userType == 1)
{
questionSQL += " and (Visibility = 0 or Author='"+ userID + "')";
}
ResultSet questionRS = db.getResults(conn, questionSQL);
while(questionRS.next())
{
String questionTitle = questionRS.getString("QuestionTitle");
String questionContent = questionRS.getString("Question");
int questionID = questionRS.getInt("QuestionID");
question = new DefaultMutableTreeNode(new BookInfo(questionTitle, questionContent, questionID, 1));
subCategory.add(question); //Adds question Pythag to subCategory Math
getAnswers(db, conn, question, questionID); //Gets answers for question
}
}
}
} catch (SQLException ex) {
Logger.getLogger(HelpDeskMainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} |
a7facab6-ac9f-4ea4-be9e-240d7b0c05ea | 2 | public Communication(){
try{
socket = new Socket("localhost", 5555);
transmit = new PrintWriter(socket.getOutputStream(), true);
receive = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
socket.setSoTimeout(60); //TODO Is that reasonable?
}catch(UnknownHostException | SocketException ex){
System.out.println("Error : Cannot initialize socket connection.");
System.exit(0);
}catch(IOException ex){
ex.printStackTrace();
System.exit(0);
}
} |
61768943-bc2f-4687-80e9-0e2e8c1d05ec | 6 | private boolean checkSquare(int check_index) {
HashMap<Integer, ServerThread> players_threads = Server.getPlayersThreads();
Element element = Server.board.getElement(check_index);
if (element != null && element.isActive()) {
if (!element.isBreakable()) {
return false;
}
if (element instanceof Bomb) {
element.burn();
} else {
this.burning_list.add(element);
this.fire.add(check_index);
return false;
}
}
this.fire.add(check_index);
for (ServerThread thread : players_threads.values()) {
if (thread.getBoardIndex() == check_index) {
Server.killPlayer(thread.getClientId());
}
}
return true;
} |
d1c41562-fac7-4e5b-9772-cbb3b608d1e0 | 2 | public static String encrypt(String string, String algo) {
if (!c.getID().equalsIgnoreCase(algo)) {
updateC(algo);
}
try {
c.setKey(key);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "This key is not valid.", "Invalid Key", JOptionPane.ERROR_MESSAGE);
}
return c.encrypt(string);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.