method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
76b9ef7b-9e56-44ee-b39b-639f88ed33d5 | 5 | public void actionPerformed(ActionEvent e) {
if (aliens.size()==0)
{
ingame = false;
}
ArrayList ms = prometheus.getMissiles();
for (int i = 0; i < ms.size(); i++)
{
Missile m = (Missile) ms.get(i);
if (m.getIsVisible())
m.move();
else ms.remove(i);
}
for (int i = 0; i < aliens.size(); i++)
{
Alien a = (Alien) aliens.get(i);
if (a.getIsVisible())
a.move();
else aliens.remove(i);
}
prometheus.move();
checkCollisions();
repaint();
} |
87a143d4-76b7-4620-8c33-273588a022c7 | 3 | public boolean findAtEast(int piece, int x, int y){
if(y==7 || b.get(x,y+1)==EMPTY_PIECE) return false;
else if(b.get(x,y+1)==piece) return true;
else return findAtEast(piece,x,y+1); // there is an opponent
} // end findAtEast |
9c6c88f0-dbf7-4e63-a2cb-79947fd2bcb8 | 4 | public boolean isFuelBlock(int itemID)
{
boolean res = false;
if((fuelBlocksGroupIDlist_Wool.contains(itemID)) ||
(fuelBlocksGroupIDlist_CraftedWood.contains(itemID)) ||
(fuelBlocksGroupIDlist_Log.contains(itemID)) ||
(fuelBlocksGroupIDlist_CoalOre.contains(itemID)))
{
res = true;
}
return (res);
} |
cde87aed-a449-4467-adee-9614af49a663 | 3 | @Override
public Node getNodeAtIndex(int index) {
// TODO Auto-generated method stub
assert !isEmpty() && (1<=index && index<=size);
Node currentNode=firstNode;
for (int count=0;count<index;count++){
currentNode=currentNode.getNext();
}
assert currentNode!=null;
return currentNode;
} |
f393eb19-cd18-46b6-87b4-09afad048f6e | 1 | protected void shift() throws IOException {
int bit = (int)(low >>> (STATE_SIZE - 1));
output.write((byte)bit);
// Write out saved underflow bits
for (; underflow > 0; underflow--)
output.write((byte)(bit ^ 1));
} |
9bc14c54-5461-4ada-8986-d166fa3d67ae | 2 | protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String url = "/";
PurchaseViewHelper purchaseViewHelper =
ViewHelperFactory.getInstance().getPurchaseViewHelper(req);
Customer customer = (Customer) req.getSession().getAttribute("loggedInCustomer");
if (purchaseViewHelper.checkEnoughFunds()) {
if (purchaseViewHelper.checkEnoughStock()) {
purchaseViewHelper.decreaseStock();
purchaseViewHelper.decreaseCustomerBalance();
purchaseViewHelper.emptyBasket();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.add(Calendar.DATE, 3);
String deliveryDate = df.format(cal.getTime());
req.setAttribute("msg", "" + customer.getForename()
+ ", your order has been successful. "
+ "Your item(s) will be delivered by " + deliveryDate);
req.setAttribute("link", "back to "
+ "<a href=\"/GAMER/shop?action=home\">shopping</a>");
url += "UserMsg.jsp";
}
else {
purchaseViewHelper.updateBasketStock();
req.setAttribute("purchaseStockIssue", "notEnoughStock");
url += "Basket.jsp";
}
}
else {
req.setAttribute("msg", "You have insufficient funds to complete this transaction. Please contact your bank.");
req.setAttribute("link", "return to "
+ "<a href=\"shop?action=basket\">basket</a>");
url += "UserMsg.jsp";
}
getServletContext().getRequestDispatcher(url).forward(req, res);
} |
30cb6fee-cbe7-4840-902c-61ae895f5e94 | 4 | public void setPriority(byte byte0, int i, int j) {
if (clientInstance.caches[0] == null)
return;
if (versions[i][j] == 0)
return;
byte abyte0[] = clientInstance.caches[i + 1].decompress(j);
if (crcMatches(versions[i][j], crcs[i][j], abyte0))
return;
filePriorities[i][j] = byte0;
if (byte0 > highestPriority)
highestPriority = byte0;
totalFiles++;
} |
7d94d5c5-087a-4a18-96f6-99a417d5e80f | 0 | public boolean isRunning(){
return running;
} |
0c4ffc36-ee8c-4321-b365-c4a5a34d39b8 | 9 | public String[] getClaims()
{
if(claims!=null)
return claims;
String s=getParmsNoTicks();
if(s.length()==0)
{ claims=defclaims; return claims;}
final char c=';';
int x=s.indexOf(c);
if(x<0) { claims=defclaims; return claims;}
s=s.substring(x+1).trim();
x=s.indexOf(c);
if(x<0) { claims=defclaims; return claims;}
s=s.substring(x+1).trim();
if(s.length()==0)
{ claims=defclaims; return claims;}
final Vector<String> V=new Vector<String>();
x=s.indexOf(c);
while(x>=0)
{
final String str=s.substring(0,x).trim();
s=s.substring(x+1).trim();
if(str.length()>0)
V.addElement(str);
x=s.indexOf(c);
}
if(s.length()>0)
V.addElement(s);
claims=new String[V.size()];
for(int i=0;i<V.size();i++)
claims[i]=V.elementAt(i);
return claims;
} |
a5f01b0b-b7b7-41ae-94b5-b377a1456587 | 8 | private void choosePrefixes() {
if (options.defaultNamespace != null) {
if (defaultNamespace != null && !defaultNamespace.equals(options.defaultNamespace))
warning("default_namespace_conflict");
defaultNamespace = options.defaultNamespace;
}
else if (defaultNamespace == null)
defaultNamespace = SchemaBuilder.INHERIT_NS;
for (Map.Entry<String, String> entry : options.prefixMap.entrySet()) {
String prefix = entry.getKey();
String ns = entry.getValue();
String s = prefixTable.get(prefix);
if (s == null)
warning("irrelevant_prefix", prefix);
else {
if (!s.equals("") && !s.equals(ns))
warning("prefix_conflict", prefix);
prefixTable.put(prefix, ns);
}
}
} |
5150111f-bee0-4239-b435-7fa4284558b0 | 7 | @Override
protected void run()
{
Set<UUID> objectsWithComponent = objectManager.getAllObjectsWithComponent(HCKeyMotion.class);
if (objectsWithComponent.isEmpty()) {
return;
}
keyboard.update();
if (keyboard.esc) System.exit(0);
for (UUID o : objectsWithComponent) {
HCVelocity velocity = objectManager.getComponent(o, HCVelocity.class);
if (keyboard.up) {
velocity.y = -3.0;
} else if (keyboard.down) {
velocity.y = 3.0;
} else {
velocity.y = 0.0;
}
if (keyboard.left) {
velocity.x = -3.0;
} else if (keyboard.right) {
velocity.x = 3.0;
} else {
velocity.x = 0.0;
}
}
} |
0ee17bea-6b6b-4741-848d-eeda7ccbabb0 | 2 | public boolean lootSpice() {
GroundItem spice = Util.getSpice();
if (spice != null && spice.isOnScreen()) {
Mouse.move(spice.getCentralPoint(), 30, 50);
return (spice.interact("Take", spice.getGroundItem().getName()));
} else {
Camera.setPitch(Random.nextInt(40, 90));
Camera.setAngle(Camera.getMobileAngle(spice) + Random.nextInt(-90, 90));
}
return false;
} |
4e45a4f7-e846-45d9-a636-044e4e3f2b26 | 9 | public void scrollCellToView(JTable table, int rowIndex, int vColIndex) {
if (!(table.getParent() instanceof JViewport)) {
return;
}
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, vColIndex, true);
Rectangle viewRect = viewport.getViewRect();
int x = viewRect.x;
int y = viewRect.y;
if (rect.x >= viewRect.x && rect.x <= (viewRect.x + viewRect.width - rect.width)){
} else if (rect.x < viewRect.x){
x = rect.x;
} else if (rect.x > (viewRect.x + viewRect.width - rect.width)) {
x = rect.x - viewRect.width + rect.width;
}
if (rect.y >= viewRect.y && rect.y <= (viewRect.y + viewRect.height - rect.height)){
} else if (rect.y < viewRect.y){
y = rect.y;
} else if (rect.y > (viewRect.y + viewRect.height - rect.height)){
y = rect.y - viewRect.height + rect.height;
}
viewport.setViewPosition(new Point(x,y));
} |
ac47cf51-237c-4ff7-8002-2c1639485648 | 8 | public static void main(String[] args) throws Exception
{
BufferedReader reader = new BufferedReader(new FileReader(new File(
ConfigReader.getMbqcDir() + File.separator + "dropbox" + File.separator +
"raw_design_matrix.txt")));
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(
ConfigReader.getMbqcDir() + File.separator + "dropbox" + File.separator +
"huttenhower_raw_design_matrixPhylaAsColumns.txt")));
String firstLine = reader.readLine();
List<String> list = getPhylaHeaders(firstLine);
writer.write("sample");
for(String s : list)
if( s != null)
writer.write("\t" + s);
writer.write("\n");
int lastIndex =0;
for( int x=0; x < list.size(); x++)
if( list.get(x) != null)
lastIndex = x;
for(String s= reader.readLine(); s != null; s= reader.readLine())
{
if( s.startsWith("chuttenhower"))
{
String[] splits = s.split("\t");
writer.write(splits[0]);
for( int x=0; x <= lastIndex; x++)
if( list.get(x) != null)
writer.write("\t" + splits[x] );
writer.write("\n");
}
}
writer.flush(); writer.close();
} |
7db50656-1682-4a49-939c-40f9fc81135c | 0 | @Override
public CarType[] getCarTypes() {
return this._carTypes;
} |
8a301648-2c71-4752-9025-72550ee61369 | 1 | public void add(InstrInfo info) {
if (info.nextTodo == null) {
/* only enqueue if not already on queue */
info.nextTodo = first;
first = info;
}
} |
0c961e71-03c3-47d1-9d3f-fb45ee4ba7a2 | 1 | public void render(Graphics g) {
if (image != null) {
int xPos = particleEmitter.mapToPanelX((int)mapX);
int yPos = particleEmitter.mapToPanelY((int)mapY);
//flip the yPos since drawing happens top down versus bottom up
yPos = particleEmitter.getPHeight() - yPos;
//subtract the block height since points are bottom left and drawing starts from top left
yPos -= height;
g.drawImage(image, xPos, yPos, null);
}
} |
ed1b48b8-6317-4e7d-a96c-55b747d9b004 | 6 | public static String numberToString(Number number)
throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} |
0654671a-83fb-49b7-94cf-074a8c0eb67c | 4 | public void setJSONList (JSONObject obj) {
try {
JSONArray fileList = obj.getJSONArray("files");
if (fileList.length() > 0) {
for (int i = 0; i < fileList.length(); i++) {
JSONObject single = fileList.getJSONObject(i);
/**
* JSONObject omzetten naar gewenste types
*/
String filename = (String) single.get("filename");
Integer size = (Integer) single.getInt("size");
String last_update = (String) single.get("last_update"); // 2013-10-27 22:24:02
try {
Date update = new SimpleDateFormat("Y-M-D h:m:s").parse(last_update);
this.files.add(new AppFile(filename, size, update));
} catch (ParseException p) {
System.out.println("Date: " + p);
}
}
}
} catch (JSONException jse) {
System.out.println("jse: " + jse);
}
} |
af180c20-9868-4413-a55d-129f669c8a87 | 9 | static boolean isPDConstructor(Statement stmt) {
Object target = stmt.getTarget();
String methodName = stmt.getMethodName();
Object[] args = stmt.getArguments();
String[] sig = new String[pdConstructorSignatures[0].length];
if (target == null || methodName == null || args == null
|| args.length == 0) {
// not a constructor for sure
return false;
}
sig[0] = target.getClass().getName();
sig[1] = methodName;
for (int i = 2; i < sig.length; i++) {
if (args.length > i - 2) {
sig[i] = args[i - 2] != null ? args[i - 2].getClass().getName()
: "null"; //$NON-NLS-1$
} else {
sig[i] = ""; //$NON-NLS-1$
}
}
for (String[] element : pdConstructorSignatures) {
if (Arrays.equals(sig, element)) {
return true;
}
}
return false;
} |
f7cab6e4-a968-4875-972d-39183f332e94 | 3 | public char skipTo(char to) throws JSONException {
char c;
try {
long startIndex = this.index;
long startCharacter = this.character;
long startLine = this.line;
this.reader.mark(1000000);
do {
c = this.next();
if (c == 0) {
this.reader.reset();
this.index = startIndex;
this.character = startCharacter;
this.line = startLine;
return c;
}
} while (c != to);
} catch (IOException exc) {
throw new JSONException(exc);
}
this.back();
return c;
} |
fd4589a5-ad62-4b44-b211-8b71ab686f4f | 3 | public static void clearEditable(Node currentNode, JoeTree tree, OutlineLayoutManager layout) {
CompoundUndoablePropertyChange undoable = new CompoundUndoablePropertyChange(tree);
JoeNodeList nodeList = tree.getSelectedNodes();
for (int i = 0, limit = nodeList.size(); i < limit; i++) {
clearEditableForSingleNode(nodeList.get(i), undoable);
}
if (!undoable.isEmpty()) {
if (undoable.getPrimitiveCount() == 1) {
undoable.setName("Clear Editability for Node");
} else {
undoable.setName(new StringBuffer().append("Clear Editability for ").append(undoable.getPrimitiveCount()).append(" Nodes").toString());
}
tree.getDocument().getUndoQueue().add(undoable);
}
tree.getDocument().attPanel.update();
layout.draw(currentNode, OutlineLayoutManager.ICON);
} |
3316a084-167a-4954-b872-c6cabc33921a | 9 | public static void main(String[] args) {
try {
if(args.length == 2){
String xpath=args[0];
String path =args[1];
FileInputStream file = new FileInputStream(new File(path));
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(file);
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = xpath;
String xml = xPath.compile(expression).evaluate(xmlDocument);
String outfile="";
if(path.toLowerCase().contains(".xml")){
outfile= path.substring(0,path.indexOf(".xml"))+".out.xml";
}
else {
outfile= path+".out.xml";
}
System.out.println(xml);
// Document document = builder.parse(new InputSource(new StringReader(xml)));
// writeNode(document,outfile);
try {
File out = new File(outfile);
// if file doesnt exists, then create it
if (!out.exists()) {
out.createNewFile();
}
FileWriter fw = new FileWriter(out.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(xml);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
} |
e103b3f6-4376-4ddf-ac29-6350ee14b1bc | 4 | private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
/*Metodo que muestra los datos de los clientes almacenados al ingresar su rut, si este no está registrado,
* permite la adicion de sus datos, además muestra el valor total de la venta
*/
boolean a=false;
for(int i=0;i<registroCli.getRowCount();i++){
if(jTextField1.getText().equals((String)registroCli.getValueAt(i, 0))){
a=true;
jTextField2.setText((String)registroCli.getValueAt(i, 1));
jTextField3.setText((String)registroCli.getValueAt(i, 2));
jTextField4.setText((String)registroCli.getValueAt(i, 3));
jTextField5.setText((String)registroCli.getValueAt(i, 4));
jTextField6.setText((String)registroCli.getValueAt(i, 5));
}
}
if(a==false){
jButton2.setVisible(true);
jTextField2.setText(null);
jTextField3.setText(null);
jTextField4.setText(null);
jTextField5.setText(null);
jTextField6.setText(null);
}
int total=0;
for(int i=0;i<jTable2.getRowCount();i++){
total=total+(int)jTable2.getValueAt(i, 4);
}
jLabel12.setText(" $ "+total*1.19);
jLabel16.setText(String.valueOf(total));
jLabel19.setText(String.valueOf(total*0.19));
jLabel18.setText(String.valueOf(total*1.19));
}//GEN-LAST:event_jButton1ActionPerformed |
1324906d-e059-466b-a971-d4e825b71b88 | 5 | public void verifyDeadEnd() {
int deadCount = 0;
if(this.checkerObject.getUp()==0) {
deadCount++;
}
if(this.checkerObject.getLeft()==0) {
deadCount++;
}
if(this.checkerObject.getDown()==0) {
deadCount++;
}
if(this.checkerObject.getRight()==0) {
deadCount++;
}
if(deadCount==3) {
backTrack();
}
} |
c0a49268-5f5d-4e5a-9b7a-29de535846b3 | 5 | private boolean testSymmetry(int ks, int bs) {
try {
IMode mode = (IMode) this.clone();
byte[] iv = new byte[cipherBlockSize]; // all zeroes
byte[] k = new byte[ks];
int i;
for (i = 0; i < ks; i++) {
k[i] = (byte) i;
}
int blockCount = 5;
int limit = blockCount * bs;
byte[] pt = new byte[limit];
for (i = 0; i < limit; i++) {
pt[i] = (byte) i;
}
byte[] ct = new byte[limit];
byte[] cpt = new byte[limit];
Map map = new HashMap();
map.put(KEY_MATERIAL, k);
map.put(CIPHER_BLOCK_SIZE, new Integer(bs));
map.put(STATE, new Integer(ENCRYPTION));
map.put(IV, iv);
map.put(MODE_BLOCK_SIZE, new Integer(bs));
mode.reset();
mode.init(map);
for (i = 0; i < blockCount; i++) {
mode.update(pt, i * bs, ct, i * bs);
}
mode.reset();
map.put(STATE, new Integer(DECRYPTION));
mode.init(map);
for (i = 0; i < blockCount; i++) {
mode.update(ct, i * bs, cpt, i * bs);
}
return Arrays.equals(pt, cpt);
} catch (Exception x) {
x.printStackTrace(System.err);
return false;
}
} |
d0b0cde3-3923-454d-8ac6-4a35cf0537e6 | 7 | public static void main(String args[])
{
final History history = new History();
if (Constants.DEBUG)
{
System.out.println("History: " + history.toString());
}
final ProbabilityGenerator probabilityGen = new ProbabilityGenerator(history);
final Random random = new Random(System.currentTimeMillis());
final RandomCandidateGenerator candidateGenerator = new RandomCandidateGenerator(
probabilityGen, random);
/* 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(DisplayJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
catch (InstantiationException ex)
{
java.util.logging.Logger.getLogger(DisplayJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
catch (IllegalAccessException ex)
{
java.util.logging.Logger.getLogger(DisplayJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
catch (javax.swing.UnsupportedLookAndFeelException ex)
{
java.util.logging.Logger.getLogger(DisplayJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null,
ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new DisplayJFrame(candidateGenerator, random).setVisible(true);
}
});
} |
bfc4f359-e165-443d-b105-9ee0f84ee5e4 | 2 | public Rectangle getBounds() {
if(width == 0 || height ==0) return new Rectangle(-100, -100, 1, 1);
return new Rectangle((int)drawX, (int)drawY, width, height);
} |
c4e0a2d8-d888-4946-b258-642beb2cca2e | 3 | private int jjMoveStringLiteralDfa1_2(long active0)
{
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
return 1;
}
switch(curChar)
{
case 47:
if ((active0 & 0x100L) != 0L)
return jjStopAtPos(1, 8);
break;
default :
return 2;
}
return 2;
} |
c0a59bb2-2232-43bf-a9c9-abaae6775e32 | 4 | public void untapAll(int player) {
for (Object e : table.getComponents()) {
if ((e.getClass().equals(TCard.class)
|| e.getClass().equals(Token.class))
&&((TCard) e).getID().charAt(0) == 'A' + player) {
((TCard) e).untap();
}
}
} |
6ffcd1b1-9642-4cea-a065-c425cff94a2a | 3 | public Matrix multSlow(Matrix m) {
Matrix n = new Matrix();
for (int c = 0; c != 4; c++) {
for (int r = 0; r != 4; r++) {
float v = 0;
for (int k = 0; k != 4; k++)
v += get(k, r) * m.get(c, k);
n.set(c, r, v);
}
}
return n;
} |
f3b949be-cdec-4405-87fa-dc3e7de9c107 | 0 | public List findAll() {
//return (List) getEntityManager().createQuery("FROM " + getObjectType().getSimpleName()).setHint("org.hibernate.cacheable", true).getResultList();
return (List) getEntityManager().createQuery("FROM " + getObjectType().getSimpleName()).getResultList();
} |
f692f855-393a-4b74-b027-6c88510f6bdc | 2 | private boolean canServeUri(String uri, File homeDir) {
boolean canServeUri;
File f = new File(homeDir, uri);
canServeUri = f.exists();
if (!canServeUri) {
String mimeTypeForFile = getMimeTypeForFile(uri);
WebServerPlugin plugin = mimeTypeHandlers.get(mimeTypeForFile);
if (plugin != null) {
canServeUri = plugin.canServeUri(uri, homeDir);
}
}
return canServeUri;
} |
e2d1a965-87a8-48e4-a655-7f5142a7de5d | 3 | protected Value getElementValue(final Value objectArrayValue)
throws AnalyzerException {
Type arrayType = ((BasicValue) objectArrayValue).getType();
if (arrayType != null) {
if (arrayType.getSort() == Type.ARRAY) {
return newValue(Type.getType(arrayType.getDescriptor()
.substring(1)));
} else if ("Lnull;".equals(arrayType.getDescriptor())) {
return objectArrayValue;
}
}
throw new Error("Internal error");
} |
6ec45b60-aa13-47cd-9124-2def5c6d6932 | 9 | public Pattern simplify(ExpressionVisitor visitor) throws XPathException {
// detect the simple cases: no parent or ancestor pattern, no predicates
if (parentPattern == null &&
ancestorPattern == null &&
filters == null &&
!firstElementPattern &&
!lastElementPattern) {
NodeTestPattern ntp = new NodeTestPattern(nodeTest);
ntp.setSystemId(getSystemId());
ntp.setLineNumber(getLineNumber());
return ntp;
}
// simplify each component of the pattern
if (parentPattern != null) {
parentPattern = parentPattern.simplify(visitor);
} else if (ancestorPattern != null) {
ancestorPattern = ancestorPattern.simplify(visitor);
}
if (filters != null) {
for (int i = numberOfFilters - 1; i >= 0; i--) {
Expression filter = filters[i];
filter = visitor.simplify(filter);
filters[i] = filter;
}
}
return this;
} |
01a4a7b0-b4a6-4c91-917b-42d5ba977478 | 3 | public int length()
{
int total = 0;
for ( int i=0;i<rows.size();i++ )
{
Row r = rows.get( i );
for ( int j=0;j<r.cells.size();j++ )
{
FragList fl = r.cells.get( j );
for ( int k=0;k<fl.fragments.size();k++ )
{
Atom a = fl.fragments.get( k );
total += a.length();
}
}
}
return total;
} |
d18b2c19-7db4-479b-97ce-0527962b779f | 2 | @Override
public String toString () {
StringBuilder sb = new StringBuilder(TrackerResponse.class.getSimpleName());
sb.append("{");
if (failed) {
sb.append("FailureReason=\"");
sb.append(failureReason);
sb.append("\"");
} else {
sb.append("Warning=\"");
sb.append(warning);
sb.append("\"; Interval=");
sb.append(interval);
sb.append("; MinInterval=");
sb.append(minInterval);
sb.append("; TrackerId=[");
sb.append((trackerId == null) ? null : new String(trackerId, Charset.forName("ISO-8859-1")));
sb.append("]; Complete=");
sb.append(complete);
sb.append("; Incomplete=");
sb.append(incomplete);
sb.append("; Peers=");
sb.append(peers);
}
return sb.append("}").toString();
} |
fff224a1-6c12-44d4-902c-fbfa9f3e3f61 | 3 | public double infoX(Integer featureId) {
double result = 0D;
for (String fValue : Feature.possibleFeatures.get(featureId).getPossibleValues()) {
double positive = 0.0;
double negative = 0.0;
for (ClassifiableObject co : partitionedObjects.get(fValue)) {
if (co.isAcceptable()) {
positive++;
} else {
negative++;
}
}
/*
double groupSize = partitionedObjects.get(fValue).size();
double a = groupSize/trainingSet.size();
double b = (positive/groupSize)*log2(positive/groupSize);
double c = (negative/groupSize)*log2(negative/groupSize);
/*result += groupSize/trainingSet.size() *
(-positive/groupSize*log2(positive/groupSize)
-negative/groupSize*log2(negative/groupSize));
*/
double groupSize = (double) partitionedObjects.get(fValue).size();
result += groupSize / (double) trainingSet.size()
* entropy(positive / groupSize, negative / groupSize);
}
return result;
} |
5d119b1c-05fc-4793-87b3-df00ee326a0b | 8 | public boolean uniformCostSearch(int root_id,int value){
rootNode=g.all_nodes.get(root_id);
frontier.insert(rootNode,1);
rootNode.is_discovered=true;
rootNode.totalcost=0;
while(!frontier.isEmpty()){
Node n = (Node)frontier.getItem();
if(n.node_id==value){
output.append("found it!\n");
backtrace(n);
cost_label.setText("total cost is :" + n.totalcost + "\n");
output.append("Cost :"+ n.totalcost+"\n");
return true;
} // end of if
explored.add(n); // add seen nodes
output.append("total cost for n :" + n.totalcost+"\n");
for(Node adj : n.visible_nodes){
if(frontier.seachItem(adj)==true && adj.is_discovered==false){
if(adj.totalcost>=(n.totalcost+g.getDistance(n.node_id,adj.node_id))){ // current total cost less than before total cost
output.append("current root of "+ (adj.node_id+1) + "is "+(adj.root_node.node_id+1) + " going to be "+(n.node_id+1)+"\n");
adj.root_node=n;
adj.totalcost= (float) (n.totalcost+ adj.getDistance(n.node_id,adj.node_id));
output.append("neighbour "+(adj.node_id+1) + " going to be discovered\n");
adj.is_discovered=true;
}
}// if
else if(frontier.seachItem(adj)==false && adj.is_discovered==false){
output.append("from "+ (n.node_id+1)+"\n");
adj.root_node=n;
adj.totalcost= (float) (n.totalcost+ g.getDistance(n.node_id,adj.node_id));
output.append("total cost for "+(adj.node_id+1) +" is:"+adj.totalcost+"\n");
frontier.insert(adj,1);
n.is_discovered=true;
}
} // end of for
output.append((n.node_id+1) +" going to be ignored\n");
output.append("\nmy frontier que is :");
output.append(frontier.array.toString()+"\n");
}//while
return false ;
}//end of method |
c33bab8d-7b17-4fc1-ab9c-c53f6a8cb9b3 | 6 | @Override
public void sendDeath(Entity source) {
final NPCCombatDefinitions defs = getCombatDefinitions();
final NPC npc = (NPC) source;
resetWalkSteps();
getCombat().removeTarget();
setNextAnimation(null);
// deathEffects(npc);
WorldTasksManager.schedule(new WorldTask() {
int loop;
@Override
public void run() {
if (loop == 0) {
if (!(npc.getId() == 6142) || (npc.getId() == 6144)
|| (npc.getId() == 6145) || (npc.getId() == 6143)) // Portals
setNextAnimation(new Animation(defs.getDeathEmote()));
} else if (loop >= defs.getDeathDelay()) {
drop();
reset();
finish();
stop();
}
loop++;
}
}, 0, 1);
} |
75f40376-45d3-450c-a567-85ef6f0feed6 | 2 | private void processMoveResult(String result, CardMove move) {
if (result.isEmpty()) {
game.getHistory().push(move);
} else if (!result.equals("ONTO_SELF")) {
storeError(result);
}
} |
93c6b681-a2f3-4abd-a26e-40f98ddaec90 | 9 | public void viewAccepted(View v) {
member_size=v.size();
if(mainFrame != null)
setTitle();
members.clear();
members.addAll(v.getMembers());
if(v instanceof MergeView) {
System.out.println("** " + v);
// This is an example of a simple merge function, which fetches the state from the coordinator
// on a merge and overwrites all of its own state
if(use_state && !members.isEmpty()) {
Address coord=members.get(0);
Address local_addr=channel.getAddress();
if(local_addr != null && !local_addr.equals(coord)) {
try {
// make a copy of our state first
Map<Point,Color> copy=null;
if(send_own_state_on_merge) {
synchronized(panel.state) {
copy=new LinkedHashMap<>(panel.state);
}
}
System.out.println("fetching state from " + coord);
channel.getState(coord, 5000);
if(copy != null)
sendOwnState(copy); // multicast my own state so everybody else has it too
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}
else
System.out.println("** View=" + v);
} |
e03d39f2-b504-4ec6-a314-c163ada0502f | 8 | private Quest getQuest(String named)
{
if((defaultQuestName.length()>0)&&(named.equals("*")||named.equalsIgnoreCase(defaultQuestName)))
return defaultQuest();
Quest Q=null;
for(int i=0;i<CMLib.quests().numQuests();i++)
{
try
{
Q = CMLib.quests().fetchQuest(i);
}
catch (final Exception e)
{
}
if(Q!=null)
{
if(Q.name().equalsIgnoreCase(named))
{
if(Q.running())
return Q;
}
}
}
return CMLib.quests().fetchQuest(named);
} |
53f3ab18-ad66-4483-b588-8a4efc31d7f0 | 7 | private Face getTurn(Face direction){
int leftAmount = 0;
switch (playerDirection){
case NORTHERN:
//no need compute anything else here
return direction;
case WESTERN:
leftAmount = 1;
break;
case SOUTHERN:
leftAmount = 2;
break;
case EASTERN:
leftAmount = 3;
default:
break;
}
switch (leftAmount){
case 1:
return Face.getLeft(direction);
case 2:
return Face.getLeft(Face.getLeft(direction));
case 3:
return Face.getLeft(Face.getLeft(Face.getLeft(direction)));
}
return direction;
} |
f59b9401-949c-4a9f-a804-9f55d459fdd5 | 4 | public void calculateGPA(Scanner a_scan)
{
System.out.println("Please Select Method to Choose Student(1 or 2): "+"\n1)Search student by Name,\n2)Search Student by techID)");
Student s1;
switch (getMenuChoiceNameOrId(a_scan))
{
case 1:
{
s1 = findStudent(inputStudentName(a_scan));
if (s1 == null)
{
System.out.println("Student may not be in record, or was entered incorrectly.");
}
else
{
System.out.println(s1.getName()+"'s GPA: "+s1.calculateGPA());
}
}
break;
case 2:
{
s1 = findStudent(scanInId(a_scan));
if (s1 == null)
{
System.out.println("Student may not be in record, or was entered incorrectly.");
}
else
{
System.out.println(s1.getName()+"'s GPA: "+s1.calculateGPA());
//Found in Student Class
}
}
break;
}
} |
d9f6ff3e-8306-47e1-8197-0a09b812830d | 8 | public void update1(float time){//@override Entity
Vector2 tempForce;
LinkedList<MyPoint> temp = new LinkedList<MyPoint>();
for (Link l : neighbors){
tempForce = Vector2.vecSubt(l.other.getPos(), this.pos);
if (tempForce.length() > l.len * breakLength){
temp.add(l.other);
}
}
for (MyPoint p : temp){
p.removeNeighbor(this);
this.removeNeighbor(p);
}
boolean existing = false;
for (MyPoint p : MyPoint.getNodesWithin(connectRange * 0.75,this.getPos())){
if(p.equals(this))break;
existing = false;
for (Link l : neighbors){
if(l.other.equals(p)){
existing = true;
break;
}
}
if (!existing){
addLink(p);
p.addLink(this);
}
}
super.update1(time);
} |
162aa43f-400c-484c-82be-977bb4630722 | 4 | public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
} |
ddc126e0-4d8b-4c49-a595-781c6c36f755 | 5 | @Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Policeofficer)) {
return false;
}
Policeofficer other = (Policeofficer) object;
if ((this.policeOfficerID == null && other.policeOfficerID != null) || (this.policeOfficerID != null && !this.policeOfficerID.equals(other.policeOfficerID))) {
return false;
}
return true;
} |
384a5489-b6ba-41a2-ac44-197ced5a3d2a | 9 | private void writeSubStreamsInfo(
List<Folder> folders,
List<Integer> numUnpackStreamsInFolders,
List<Long> unpackSizes,
List<Boolean> digestsDefined,
List<Integer> digests) throws IOException {
writeByte((byte) Header.NID.kSubStreamsInfo);
for (int i = 0; i < numUnpackStreamsInFolders.size(); i++) {
if (numUnpackStreamsInFolders.get(i) != 1) {
writeByte((byte) Header.NID.kNumUnPackStream);
for (i = 0; i < numUnpackStreamsInFolders.size(); i++)
writeNumber(numUnpackStreamsInFolders.get(i));
break;
}
}
boolean needFlag = true;
int index = 0;
for (Integer numUnpackStreamsInFolder : numUnpackStreamsInFolders)
for (int j = 0; j < numUnpackStreamsInFolder; j++) {
if (j + 1 != numUnpackStreamsInFolder) {
if (needFlag)
writeByte((byte) Header.NID.kSize);
needFlag = false;
writeNumber(unpackSizes.get(index));
}
index++;
}
List<Boolean> digestsDefined2 = new ArrayList<>();
List<Integer> digests2 = new ArrayList<>();
int digestIndex = 0;
for (int i = 0; i < folders.size(); i++) {
int numSubStreams = numUnpackStreamsInFolders.get(i);
for (int j = 0; j < numSubStreams; j++, digestIndex++) {
digestsDefined2.add(digestsDefined.get(digestIndex));
digests2.add(digests.get(digestIndex));
}
}
writeHashDigests(digestsDefined2, digests2);
writeByte((byte) Header.NID.kEnd);
} |
70d030db-6eff-43d3-9bb0-83cec778f3d1 | 9 | public static void undefineModule(Module oldmodule, Module newmodule) {
System.out.println("Redefining the module `" + oldmodule.contextName() + "'");
if (Stella.$SUBCONTEXT_REVISION_POLICY$ == Stella.KWD_DESTROY) {
oldmodule.destroyContext();
return;
}
else if (Stella.$SUBCONTEXT_REVISION_POLICY$ == Stella.KWD_PRESERVE) {
}
else if (Stella.$SUBCONTEXT_REVISION_POLICY$ == Stella.KWD_CLEAR) {
{ Context c = null;
AllPurposeIterator iter000 = Context.allSubcontexts(oldmodule, Stella.KWD_PREORDER);
while (iter000.nextP()) {
c = ((Context)(iter000.value));
Context.clearContext(c);
}
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + Stella.$SUBCONTEXT_REVISION_POLICY$ + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
if (Module.cardinalModuleP(oldmodule)) {
Stella.$ROOT_MODULE$.childContexts.remove(oldmodule);
}
else {
{ Module p = null;
Cons iter001 = oldmodule.parentModules.theConsList;
for (;!(iter001 == Stella.NIL); iter001 = iter001.rest) {
p = ((Module)(iter001.value));
p.childContexts.remove(oldmodule);
}
}
}
{ Context c = null;
Cons iter002 = oldmodule.childContexts.theConsList;
for (;!(iter002 == Stella.NIL); iter002 = iter002.rest) {
c = ((Context)(iter002.value));
{ Surrogate testValue000 = Stella_Object.safePrimaryType(c);
if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_MODULE)) {
{ Module c000 = ((Module)(c));
c000.parentModules.theConsList.substitute(newmodule, oldmodule);
}
}
else if (Surrogate.subtypeOfP(testValue000, Stella.SGT_STELLA_WORLD)) {
{ World c000 = ((World)(c));
c000.parentContext = newmodule;
}
}
else {
{ OutputStringStream stream001 = OutputStringStream.newOutputStringStream();
stream001.nativeStream.print("`" + testValue000 + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream001.theStringReader()).fillInStackTrace()));
}
}
}
}
}
newmodule.childContexts.theConsList = oldmodule.childContexts.theConsList;
oldmodule.childContexts.theConsList = Stella.NIL;
oldmodule.surrogateValueInverse = null;
oldmodule.unfinalizeModule();
oldmodule.free();
} |
9e14088a-7543-4ddc-9935-1db22527949f | 5 | public String diff_prettyHtml(LinkedList<Diff> diffs) {
StringBuilder html = new StringBuilder();
int i = 0;
for (Diff aDiff : diffs) {
String text = aDiff.text.replace("&", "&").replace("<", "<")
.replace(">", ">").replace("\n", "¶<br>");
switch (aDiff.operation) {
case INSERT:
html.append("<ins style=\"background:#e6ffe6;\">").append(text)
.append("</ins>");
break;
case DELETE:
html.append("<del style=\"background:#ffe6e6;\">").append(text)
.append("</del>");
break;
case EQUAL:
html.append("<span>").append(text).append("</span>");
break;
}
if (aDiff.operation != Operation.DELETE) {
i += aDiff.text.length();
}
}
return html.toString();
} |
ff09ff26-9345-44e9-b9e3-5dacb31684ac | 6 | public Card(int theValue, int theSuit) {
if(theSuit != SPADES && theSuit != HEARTS && theSuit != DIAMONDS &&
theSuit != CLUBS )
throw new IllegalArgumentException("Illegal playing card suit");
if(theValue <1 || theValue >13)
throw new IllegalArgumentException("Illegal playing card value");
value = theValue;
suit = theSuit;
} |
7081232b-1275-438b-9c73-4b6a6811562e | 0 | public DocumentRepositoryEvent(Document doc) {
setDocument(doc);
} |
c35a1485-4bd3-467b-8c32-405c9ed45248 | 7 | @SuppressWarnings("resource")
public Class<?>[] getClassesFromThisJar(Object object)
{
final List<Class<?>> classes = new ArrayList<Class<?>>();
ClassLoader classLoader = null;
URI uri = null;
try
{
uri = object.getClass().getProtectionDomain().getCodeSource().getLocation().toURI();
classLoader = new URLClassLoader(
new URL[]{uri.toURL()},
ClassEnumerator.class.getClassLoader());
}
catch (URISyntaxException e)
{
e.printStackTrace();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
if (uri == null)
{
throw new RuntimeException(
"No uri for " + this.getClass().getProtectionDomain().getCodeSource().getLocation());
}
if(classLoader == null)
{
throw new RuntimeException(
"No classLoader for " + this.getClass().getProtectionDomain().getCodeSource().getLocation());
}
File file = new File(uri);
classes.addAll(getClassesFromLocation(file));
return classes.toArray(new Class[classes.size()]);
} |
bb4a6d11-5b35-4a7f-853a-e14493c199d0 | 2 | @Override
public boolean equals(Object object) {
if (this == object)
return true;
if (!(object instanceof AlgoChecksumType))
return false;
AlgoChecksumType other = (AlgoChecksumType)object;
return this.name.equalsIgnoreCase(other.toString());
} |
25e191f1-59eb-43e5-a64c-6c401f94e868 | 4 | public static void main(String[] args)
{
HashMap<Integer,GameData> g=new HashMap<Integer,GameData>();
Vector<Integer> index=new Vector<Integer>();
CalculatingConsole c = new CalculatingConsole();
HashMap<String,PlayerData> p =new HashMap<String,PlayerData>();
for(File f: new File("./").listFiles())
{
String s=f.getName();
if(s.endsWith("detail.txt"))
{
int i = new Integer(s.substring(s.indexOf("detail.txt")-13, s.indexOf("detail.txt")).replace("-", ""));
System.out.println(i);
index.add(i);
g.put(i, new GameData(s));
}
if(s.endsWith(".csv")&& !(new File(s.substring(0, s.indexOf(".csv"))+"detail.txt").exists()))
{
p.put(s.substring(0, s.indexOf(".csv")), new PlayerData(s));
}
}
//at this point, all the data should be in the appropriate places
Collections.sort(index);
c.dostuff(g,index,c,p);
} |
09891752-0d1d-49db-bafb-3adfbe438f39 | 6 | public Point makeAIMove(OthelloBoard board) {
/** < store the maximum number of the pieces that are flipped */
int m_MaximumFlips = 0;
/** < store all the computer hard move point with the maximum piece flip number */
ArrayList<Point> m_BestFlips = new ArrayList<Point>();
/** < scan the whole board and find the maximum number of the flipped pieces (m_MaximumFlips) */
for (int i = 0; i < BOARD_HEIGHT; i++) {
for (int j = 0; j < BOARD_WIDTH; j++) {
if (getFlipsForPosition(i,j, board) > m_MaximumFlips) {
m_MaximumFlips = getFlipsForPosition(i,j,board);
}
}
}
/** < scan the whole board store the point with the maximum flipped piece number
* to the m_BestFlips ArrayList */
for (int i = 0; i < BOARD_HEIGHT; i++) {
for (int j = 0; j < BOARD_WIDTH; j++) {
if (getFlipsForPosition(i,j, board) == m_MaximumFlips) {
m_BestFlips.add(new Point(i,j));
}
}
}
/** < choose a point from the m_BestFlips ArrayList randomly */
Random r = new Random();
int m_ArrayPosition = r.nextInt(m_BestFlips.size());
return m_BestFlips.get(m_ArrayPosition);
} |
9c07b29a-0f41-43ab-a4a3-ce249e034e56 | 2 | private void addProgram(String text, int type){
int shader = glCreateShader(type);
if (shader == 0){
System.err.println("Shader creation failed, could not find valid memory location when adding shader");
System.exit(1);
}
glShaderSource(shader,text);
glCompileShader(shader);
if (glGetShaderi(shader, GL_COMPILE_STATUS) == 0){
System.err.println(glGetShaderInfoLog(shader,1024));
System.exit(1);
}
glAttachShader(program,shader);
} |
92981011-ade5-40cf-bc2a-21af5b75f3af | 4 | public static BufferedImage stamp(BufferedImage input) {
int stamp[][] = new int[][]{
{0, 1, 0},
{-1, 0, 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 += stamp[s + 1][k + 1] * c.getRed();
newGreen += stamp[s + 1][k + 1] * c.getGreen();
newBlue += stamp[s + 1][k + 1] * c.getBlue();
}
}
result.setRGB(i, j, normColor(newRed + 128, newGreen + 128, newBlue + 128).getRGB());
}
return result;
} |
47013475-6049-4998-af55-1eeb5092e612 | 1 | public void setTileAt(int tx, int ty, Tile ti) {
if (bounds.contains(tx, ty)) {
map[ty - bounds.y][tx - bounds.x] = ti;
}
} |
c1178f94-bc01-479d-b73f-c4b30945942b | 1 | private double RD2lng(double x2, double y2) {
// TODO Auto-generated method stub
double a=0;
double dX=1E-5*(x2-X0);
double dY=1E-5*(y2-Y0);
for(int i = 1; 13 > i; i++)
a+=lngpqK[i].K*Math.pow(dX,lngpqK[i].p)*Math.pow(dY,lngpqK[i].q);
return lng0 + a / 3600;
} |
ababad4e-cdb5-44cc-9a18-9b4dd0b7028d | 0 | public static void main(String[] args) {
List<Integer> numberList = new ArrayList<Integer>();
numberList.add(5);
numberList.add(6);
numberList.add(7);
//sum of all numbers
// sumWithCondition(numbers, n -> true);
//sum of all even numbers
sumWithCondition(numberList, i -> i % 2 == 0);
//sum of all numbers greater than 5
// sumWithCondition(numbers, i -> i>5);
numberList.forEach(n -> System.out.println(n));
} |
23919420-d7eb-4eea-a3a5-f7f2294e78e5 | 1 | public static void spawnFoodFight (Location loc, int amount) {
int i = 0;
while (i < amount) {
Skeleton FoodFight = (Skeleton) loc.getWorld().spawnEntity(loc,
EntityType.SKELETON);
LeatherArmorMeta meta;
LeatherArmorMeta legMeta;
ItemStack FFLeg = new ItemStack(Material.LEATHER_LEGGINGS, 1);
legMeta = (LeatherArmorMeta) FFLeg.getItemMeta();
legMeta.setColor(Color.fromRGB(48, 206, 0));
FFLeg.setItemMeta(legMeta);
LeatherArmorMeta chestMeta;
ItemStack FFChest = new ItemStack(Material.LEATHER_CHESTPLATE, 1,
(short) - 98789);
chestMeta = (LeatherArmorMeta) FFChest.getItemMeta();
chestMeta.setColor(Color.fromRGB(48, 206, 0));
FFChest.setItemMeta(chestMeta);
LeatherArmorMeta bootsMeta;
ItemStack FFBoots = new ItemStack(Material.LEATHER_BOOTS, 1);
bootsMeta = (LeatherArmorMeta) FFBoots.getItemMeta();
bootsMeta.setColor(Color.fromRGB(48, 206, 0));
FFBoots.setItemMeta(bootsMeta);
LeatherArmorMeta HelmetMeta;
ItemStack FFHelm = new ItemStack(Material.LEATHER_HELMET, 1);
HelmetMeta = (LeatherArmorMeta) FFHelm.getItemMeta();
HelmetMeta.setColor(Color.fromRGB(48, 206, 0));
FFHelm.setItemMeta(HelmetMeta);
FoodFight.getEquipment().setItemInHand(
new ItemStack(Material.PORK, 1));
FoodFight.getEquipment().setChestplate(FFChest);
FoodFight.getEquipment().setLeggings(FFLeg);
FoodFight.getEquipment().setBoots(FFBoots);
FoodFight.getEquipment().setChestplateDropChance(0.30F);
FoodFight.getEquipment().setLeggingsDropChance(0.30F);
FoodFight.getEquipment().setBootsDropChance(0.40F);
FoodFight.addPotionEffect(new PotionEffect(PotionEffectType.SPEED,
2147483647, 1));
FoodFight.addPotionEffect(new PotionEffect(
PotionEffectType.INVISIBILITY, 2147483647, 10));
FoodFight.addPotionEffect(new PotionEffect(
PotionEffectType.INCREASE_DAMAGE, 2147483647, 1));
FoodFight.addPotionEffect(new PotionEffect(
PotionEffectType.WATER_BREATHING, 2147483647, 1));
FoodFight.setCanPickupItems(false);
i++;
}
} |
fc368695-d58f-4f87-b25e-065efe4d5fc9 | 3 | private EnumMap<JobType, Long> totalTimesForJobs(){
EnumMap<JobType, Long> out = new EnumMap<JobType, Long>(JobType.class);
out.put(JobType.COMBINE, 0l);
out.put(JobType.COMPRESS, 0l);
out.put(JobType.DOWNLOAD, 0l);
out.put(JobType.FORWARD, 0l);
out.put(JobType.UNKNOWN, 0l);
out.put(JobType.WAITING, 0l);
out.put(JobType.WAITRESULT, 0l);
for (JobMetaData job : finishedJobs.values()) {
EnumMap<JobType,Long> jobTimes = job.getJobTimes();
List<Long> values = new ArrayList<Long>();
values.addAll(jobTimes.values());
Collections.sort(values);
for (Entry<JobType, Long> entry : jobTimes.entrySet()){
int ourTimeIndex = Collections.binarySearch(values, entry.getValue());
long time = ourTimeIndex == values.size()-1 ? job.getEndtime() - entry.getValue() :
values.get(ourTimeIndex+1) - entry.getValue();
out.put(entry.getKey(), out.get(entry.getKey()) + time);
}
}
return out;
} |
6c99379e-040d-4f3f-9d12-7b4d36b577c0 | 9 | public synchronized void save() {
if (image == null) return;
if (fc == null) {
String[] paths = {
System.getProperty("user.home") + File.separator + "Pictures",
System.getProperty("user.home") + File.separator + "My Pictures",
System.getProperty("user.home") + File.separator + "Documents" + File.separator + "Pictures",
System.getProperty("user.home") + File.separator + "My Documents" + File.separator + "My Pictures",
System.getProperty("user.home") + File.separator + "Desktop",
"."
};
File pics = null;
for (String path : paths) {
pics = new File(path);
if (pics.exists())
break;
}
fc = new JFileChooser(pics);
}
int approve = fc.showSaveDialog(this);
if (approve != JFileChooser.APPROVE_OPTION)
return;
File f = fc.getSelectedFile();
if (!f.getName().toLowerCase().endsWith(".png"))
f = new File(f.getAbsolutePath() + ".png");
if (f.exists()) {
int overwrite = JOptionPane.showConfirmDialog(this,
"The file \"" + f.getName() + "\" already exists. Would you like to overwrite it?",
"Confirm Overwrite", JOptionPane.YES_NO_OPTION);
if (overwrite != JOptionPane.YES_OPTION)
return;
}
try {
ImageIO.write(image, "png", f);
} catch (Exception e) {
JOptionPane.showMessageDialog(this,
"Error writing file: " + e,
"Oops", JOptionPane.ERROR_MESSAGE);
}
} |
87ac99c5-81df-4960-b02b-64d544624140 | 3 | public static int loadGame(){
// Get user input
Object[] options = {"1", "2", "3"};
int slot = JOptionPane.showOptionDialog(null, "Select your save slot", "Save Slot", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
slot++;
// Find appropriate save directory for OS
String directory_str = System.getProperty("user.home") + "/.Empous/saves";
// Load saved game
System.out.println("Loading save slot " + slot + "...");
File loadFile = new File(directory_str + "/savedata"+slot+".dat");
try{
FileInputStream fstream = new FileInputStream (loadFile);
ObjectInputStream in = new ObjectInputStream(fstream);
Empous.empireName = (String) in.readObject();
Empous.Com=(Commercial) in.readObject();
Empous.Res=(Residential) in.readObject();
Empous.Ind=(Industrial) in.readObject();
Empous.LM=(LumberMill) in.readObject();
Empous.Inf=(Infrastructure) in.readObject();
Empous.Gov=(Government) in.readObject();
in.close();
}
catch(FileNotFoundException e){
System.out.println("Your save files got screwed up! >:[");
}
catch(IOException e){
System.out.println("Couldn't load from file!");
System.exit(2);
}
catch (ClassNotFoundException e) {
System.out.println("Couldn't load from file!");
System.exit(2);
}
return slot;
} |
1dd22dbc-4d3b-494d-af61-f23fc4de3d6b | 1 | public Block domParent(final Block block) {
if (domEdgeModCount != edgeModCount) {
computeDominators();
}
return block.domParent();
} |
db1f9622-7b27-4b90-b840-9eccb6c259bf | 1 | public void emptyField(){
for(int i = 0; i < fieldSize; i++) {
araseLine(i);
}
} |
060cbd24-1da6-446e-bf4d-6d4af2b1cf0c | 4 | @Override
boolean isColliding(int p_X, int p_Y){
//Do something
if(p_X > (posX-10) && p_X < (posX+width+10))
{
if(p_Y > (posY-10) && p_Y < (posY+height+10))
{
return true;
}
}
return false;
} |
583df319-18d8-410a-a0fe-fc25723c268a | 0 | public boolean contains(Component component) {
return tabbed.indexOfComponent(component) != -1;
} |
b23d2226-ce35-4553-a01a-f225cae67fbc | 9 | private static List<Integer> parseRange(String range, int max) {
List<Integer> idx = new ArrayList<Integer>();
String[] n = range.split(",");
for (String s : n) {
String[] d = s.split("-");
int mi = Integer.parseInt(d[0]);
if (mi < 0 || mi >= max) {
throw new IllegalArgumentException(range);
}
if (d.length == 2) {
if (d[1].equals("*")) {
d[1] = Integer.toString(max - 1);
}
int ma = Integer.parseInt(d[1]);
if (ma <= mi || ma >= max || ma < 0) {
throw new IllegalArgumentException(range);
}
for (int i = mi; i <= ma; i++) {
idx.add(i);
}
} else {
idx.add(mi);
}
}
return idx;
} |
389750dd-d792-4fd5-a90a-8b411467812b | 2 | public int getBeingByPosition(double x, double y){
for (int i = 0; i < beings.size(); i++){
if ( sqrt( (x - beings.get(i).getX())*(x - beings.get(i).getX()) + (y - beings.get(i).getY())*(y - beings.get(i).getY())) < RADIUS_TOUCH_DETECT ){
return i;
}
}
return -1;
} |
58eb7825-f415-4061-96fc-6dd3a3b7631c | 6 | public String isOne(String[] words) {
if(words.length<=1)
return "Yes";
for(int i=0;i<words.length;i++){
for(int j=0;j<words.length;j++){
if (words[j].startsWith(words[i]) && !words[j].equals(words[i])) treeMap.put(words[i], i);
}
if(treeMap.size()>=1){
Iterator<Integer> integerIterator = treeMap.values().iterator();
int temp = integerIterator.next();
System.out.println(temp);
return "No, "+temp;
}
}
return "Yes";
} |
62e08ed1-9b39-4138-af08-5cfbb8f7ca06 | 5 | static final void method887(Widget class46, int i, int i_5_, int i_6_) {
if (i_6_ == 2147483647) {
anInt1589++;
if (Class289.aClass46_3701 == null && !Class5_Sub1.aBoolean8335
&& (class46 != null
&& (ToolkitException.method141(class46, (byte) -79)
!= null))) {
Class289.aClass46_3701 = class46;
Class331.aClass46_4130
= ToolkitException.method141(class46, (byte) -117);
Class318_Sub1.anInt6392 = 0;
Class219.anInt2872 = i_5_;
Class318_Sub4.anInt6411 = i;
Class300.aBoolean3819 = false;
}
}
} |
b254ef5b-3507-400a-b20e-ee43a0e82af7 | 9 | private boolean flipHorizontal(long binPosition, boolean goesRight){
boolean hasFlippableDisk = false;
long searchPosition = binPosition;
if(goesRight && (binPosition & 0x0101010101010101l) == 0)
searchPosition = binPosition >> 1;
else if( !goesRight && (binPosition & 0x8080808080808080l) == 0 )
searchPosition = binPosition << 1;
else
return false;
while(!isHorizontalEndOfBoard(searchPosition)){
// if disk does not exist at search position,
// we can't flip disk. Therefore return false.
if( !isPlaced(searchPosition) )
return false;
// if search position's disk is mine and we've already found flippable disks(disk which is not mine),
// return true.
if( isSameDisk(searchPosition) ){
if(hasFlippableDisk)
return true;
else
return false;
}
else{
this.binIsBlack = binFlippedDiskOf(searchPosition);
hasFlippableDisk = true;
}
if(goesRight)
searchPosition = ( searchPosition >> 1 );
else
searchPosition = ( searchPosition << 1 );
}
return false;
} |
8a7e7445-e841-4d4c-a965-1c8ea33dbdaa | 2 | boolean isValidReportDirectory(File dir) {
File jsonFile = new File(dir, "jscoverage.json");
File srcDir = new File(dir, Main.reportSrcSubDir);
return isValidDirectory(dir) && isValidFile(jsonFile) && isValidDirectory(srcDir);
} |
afa3054a-c4d9-41c3-bf48-a37ea4bc16fb | 5 | private void writeHql(ArrayList<String> colName, ArrayList<String> colType, ArrayList<String> colRemark, String tabComments) {
StringBuffer content=new StringBuffer();
content.append("USE "+data_db_name.toUpperCase()+";\n");
content.append("DROP TABLE "+tn.toUpperCase()+";\n");
content.append("CREATE TABLE "+tn.toUpperCase()+"(\n");
for(int i=0; i<colName.size(); ++i){
content.append(" "+String.format("%-33s", colName.get(i).replaceAll("[#|(|)]", ""))+" "+(colType.get(i).equalsIgnoreCase("ROWID")?"STRING":colType.get(i))+" COMMENT '"+colRemark.get(i).replaceAll(";","")+"'");
if(i!=colName.size()-1)
content.append(",\n");
else
content.append("\n");
}
if(unreptWay.equals("no")){
content.append(")comment '"+tabComments.replaceAll(";","")+"' row format delimited fields terminated by '\\001' stored as rcfile;\n");
}else if(unreptWay.equals("increment")){
content.append(")comment '"+tabComments.replaceAll(";","")+"' partitioned by (CHANNEL STRING,OP_MONTH STRING) row format delimited fields terminated by '\\001' stored as rcfile;\n");
}
String initPath=System.getProperty("user.dir")+File.separator+projectName+"-ods"+ File.separator+"hql";
wfa.mkdirs(initPath);
wfa.writeFromStringBuffer(initPath+File.separator+index+"_create_"+tn+".hql","UTF-8",content);
} |
185fee07-9bd2-4a72-91bb-02d3fe02f521 | 2 | public ArrayList<ArrayList<Integer>> permute(int[] num) {
LinkedList<TailStack<Integer>> mappers = search(num.length);
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
for (TailStack<Integer> mapper : mappers){
ArrayList<Integer> tmp = new ArrayList<Integer>();
for(Integer i : mapper){
tmp.add(num[i]);
}
result.add(tmp);
}
return result;
} |
d4bcf338-652d-47b0-b623-d8528bc4df63 | 0 | public void setLSmsOverTime(int second){
this.pconnect.setLSmsOverTime(second);
} |
9885031b-0138-41b5-b85e-981b160d9900 | 0 | public String getRawMessage(){ return RawMessage; } |
b469ef9e-4fe6-41c5-bcfd-c01aaec464bc | 9 | private void reDraw()
{
hitCount = 0;
p.removeAll();
for(int i = 0; i < nums.length; i++)
{
for(int j = 0; j < nums[0].length; j++ )
{
if( nums[i][j] == 0)
p.add( dots[i][j] == 0 ? (new JLabel (ground)) : (new JLabel (groundDot)));
else if( nums[i][j] == 1)
p.add( new JLabel(wall));
else if( nums[i][j] == 2)
{
if(dots[i][j] == 0)
p.add( new JLabel(box ));
else
{
p.add( new JLabel(boxDot));
hitCount++;
}
}
else
p.add( dots[i][j] == 0 ? (new JLabel(guy)) : (new JLabel(guyDot)));
}
//Player wins
if(hitCount == numBoxes)
{
isGameOver = true;
t.stop();
setEarnedPercentage();
resultLabel.setText("You won!");
experience.setText("Exp: "+earnedPercentage);
exit.setVisible(true);
resultLabel.setVisible(true);
}
// Enables to go to the next level
// if(hitCount == numBoxes)
// {
// welldone.setVisible(true);
// }
}
p.repaint();
p.validate();
levelLabel.setText("Level: " + currentLevel);
countLabel.setText("Moves: " + moveCount);
controlPanel.repaint();
controlPanel.validate();
} |
04248a13-d1ef-4086-879a-d708753881e1 | 1 | public void setCapacidade(int capacidade) {
this.capacidade = (capacidade >= 0) ? capacidade : 0;
} |
649aceb8-2c6b-4fb0-8f0f-c8663af59aa9 | 2 | @Override
public void registerDirty(IDomainObject domainObject) {
assert domainObject.getId() != null : "id not null";
assert !removedObjects.contains(domainObject) : "object not removed";
if (!dirtyObjects.contains(domainObject) && !newObjects.contains(domainObject)) {
dirtyObjects.add(domainObject);
}
} |
95be17f7-05d8-4b24-a300-c543a46ed4d8 | 6 | @Override
public void characters(char[] ch, int start, int length) throws SAXException {
try {
int end = start + length;
while ((start < end) && (ch[start] <= ' ')) {
start++;
}
while ((start < end) && (ch[end - 1] <= ' ')) {
end--;
}
if(end != start)
wrtr.writeText(ch, start, end-start);
} catch (IOException e) {
throw new RuntimeException(e);
}
} |
27a44c63-845c-4383-8855-6a74cf067336 | 0 | public ProjectWizardView() {
setSize(500, 500);
setVisible(true);
} |
ce0cc626-4f85-4c3d-b255-f79b5779a4f1 | 3 | public void crossFold10(String fileLoc){
Instances data = null;
BufferedReader reader = null;
System.out.println("---------------Running Crossfold10 Testing Using Random Forrest On Data---------------");
// Need to build data to fit into evaluation
try {
//Read in data from the .arff file
reader = new BufferedReader(new FileReader(fileLoc));
data = new Instances(reader);
reader.close();
//Sets the class index (what to classify on) to the last value in the data file, this case {healthy,unhealthy}
data.setClassIndex(data.numAttributes() - 1);
} catch (IOException e) {
System.err.println("Buffered reader for Random Forest input could not be created: " + e);
}
try {
//evaluate the data
Evaluation evalu = new Evaluation(data);
int folds = 10;
//runs crossfold validation on the randomforest
evalu.crossValidateModel(rf, data, folds, new Random(1));
//Output for crossfold 10
System.out.println("CrossFold10 classification details: " + evalu.toClassDetailsString());
System.out.println("CrossFold10 Stats:" + evalu.toSummaryString(true));
System.out.println("Crossfold10 confusion matrix: " + evalu.toMatrixString());
System.out.println("number of correctly classified images: " +evalu.correct());
System.out.println("number of incorrectly classified images: " +evalu.incorrect());
System.out.println("percent of images correctly classified: " + evalu.pctCorrect());
for(int i = 0; i < rf.getOptions().length; i++){
System.out.println("Maximum depth of trees " + rf.getOptions()[i]);
}
} catch (Exception e) {
System.err.println("Could not build Random forrest from data: " + e);
}
} |
d0aa4b74-00ac-4ed1-a558-d840147c5b3b | 9 | public View render(View convertView, final Context context, FeedView feedView) {
// Set up the view holder
if(convertView == null) {
convertView = super.render(convertView, context, feedView);
holder = new ViewHolder();
holder.achievementIconView = (ImageView) convertView.findViewById(Rzap.id("achievement_icon"));
holder.achievementNameView = (TextView) convertView.findViewById(Rzap.id("achievement_name"));
holder.achievementDescriptionView = (TextView) convertView.findViewById(Rzap.id("achievement_description"));
holder.achievementNewBadgeView = (ImageView) convertView.findViewById(Rzap.id("new_badge_icon"));;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.feedlette = this;
holder.achievementIconView.setImageResource(Rzap.drawable("icon_default_badge"));
// Fill in the views
String iconUrl = achievement.getIconUrl();
if (iconUrl != null && !iconUrl.equals("") && !iconUrl.equals("null")) {
if (!downloadingAchievementImage) {
downloadingAchievementImage = true;
new DownloadImageTask(new DownloadImageListener() {
@Override
public void onImageDownloaded(Bitmap bitmap) {
downloadedAchievementImage = bitmap;
if (holder.feedlette == AchievementFeedlette.this) {
holder.achievementIconView.setImageBitmap(downloadedAchievementImage);
}
}
}).execute(iconUrl);
}
if (downloadedAchievementImage != null) {
holder.achievementIconView.setImageBitmap(downloadedAchievementImage);
} else {
holder.achievementIconView.setImageDrawable(null);
}
} else {
holder.achievementIconView.setImageDrawable(null);
}
if (achievement.hasJustUnlocked()) {
holder.achievementNewBadgeView.setVisibility(View.VISIBLE);
} else {
holder.achievementNewBadgeView.setVisibility(View.GONE);
}
if (achievement.hasUnlocked()) {
holder.achievementNameView.setTextColor(0xff000000);
} else {
holder.achievementNameView.setTextColor(0xff999999);
}
holder.achievementNameView.setText(achievement.getName());
holder.achievementDescriptionView.setText(achievement.getDescription());
return convertView;
} |
00716bbd-21d1-4435-8fce-41512e13c451 | 4 | @Override
public String toString() {
StringBuilder theString = new StringBuilder();
theString.append("[");
for (int i = 0; i < this.length; i++) {
theString.append("[");
for (int j = 0; j < this.width; j++) {
theString.append(this.cells[i][j].toBit());
if (j < this.width - 1)
theString.append(", ");
}
theString.append("]");
if (i < this.length)
theString.append(", ");
}
theString.append("]");
return theString.toString();
} |
d9af1e50-db61-4a6e-8ab5-17331db772e7 | 2 | public boolean Salvar(Estoque obj , int idPessoa){
try{
boolean retorno= false;
if(obj.getId() == 0){
PreparedStatement comando = conexao
.getConexao().prepareStatement("INSERT INTO estoques (id,quantidade) VALUES (?,?)");
comando.setInt(1, idPessoa);
comando.setInt(2, obj.getQuantidade());
comando.executeUpdate();
comando.getConnection().commit();
retorno = true;
}else{
PreparedStatement comando = conexao
.getConexao().prepareStatement("UPDATE estoques SET id = ?,quantidade =? WHERE id = ?");
comando.setInt(1, idPessoa);
comando.setInt(2, obj.getQuantidade());
comando.setInt(3, idPessoa);
comando.executeUpdate();
comando.getConnection().commit();
retorno = true;
}
return retorno;
}catch(SQLException ex){
ex.printStackTrace();
return false;
}
} |
0c7c20fe-80d5-4f15-aacd-077d69c72721 | 6 | public boolean checkPassword(String pass){
boolean band = true;
int i=0;
for(int x=0;x<4;x++){
if(pass.charAt(x)<48 || pass.charAt(x)>57)
return false;
}
while(band == true && i <= numClientes){
if(pass.equals(clientes[i].getPassword()))
band = false;
else
i++;
}
return band;
} |
e810f0f0-f74a-410c-beff-505aefb214c0 | 2 | private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
String[] options = {"Minimize", "Cancel", "Exit"};
int rsp = JOptionPane.showOptionDialog(null, "Are u making the right decision?", "Message", 0,
JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
if (rsp == 2) {
System.exit(1);
} else if (rsp == 0) {
this.setState(UserGui.ICONIFIED);
} else {
this.setState(UserGui.DO_NOTHING_ON_CLOSE);
}
}//GEN-LAST:event_formWindowClosing |
8974529c-e0a6-40da-8b92-743f2f4d06a6 | 9 | private void checkFirstOrder(){
SVA_Sketch sketch = sketchQueue[(tail-1) % MAX_QUEUE_SIZE];
Timestamp currentTime = sketch.time;
System.out.println("Checking..." + currentTime);
{
double s = sketch.s.zeroOrder.getValue(currentTime, 0);
for(int h = 0; h < H; h ++){
double C = 0;
for(int i = 0; i < N; i ++){
C += sketch.s.firstOrder[h][i].getValue(currentTime, 0);
}
if(C != s) System.out.println("S Error!" + h + " " + Math.abs(C - s) + " " + s);
}
}
{
double v = sketch.v.zeroOrder.getValue(currentTime, smoothLength1 * oneMinute);
for(int h = 0; h < H; h ++){
double C = 0;
for(int i = 0; i < N; i ++){
C += sketch.v.firstOrder[h][i].getValue(currentTime, smoothLength1 * oneMinute);
}
if(C != v) System.out.println("V Error!" + h + " " + Math.abs(C - v) + " " + v);
}
}
{
double a = sketch.a.zeroOrder.getValue(currentTime, smoothLength2 * oneMinute);
for(int h = 0; h < H; h ++){
double C = 0;
for(int i = 0; i < N; i ++){
C += sketch.a.firstOrder[h][i].getValue(currentTime, smoothLength2 * oneMinute);
}
if(C != a) System.out.println("A Error!" + h + " " + (C - a) + " " + a);
}
}
} |
20a66bbb-b7a3-439a-92c8-d789189ecfbc | 3 | public void showPanTip()
{
String tipText = null;
Point upperLeft = new Point(0, 0);
JViewport vp = getEnclosingViewport();
if (!isPannableUnbounded() && vp != null)
upperLeft = vp.getViewPosition();
Location loc = locationForPoint(upperLeft);
if (loc != null)
tipText = getToolTipText(loc);
//showTip(tipText, getLocation());
} |
38e755c3-c532-45df-a020-eeeb1b76a7cc | 8 | public int countCoins(String state) {
int coins = state.length();
if ((coins == 0) || (coins == 1)) {
return 0;
}
char[] coinsArray = state.toCharArray();
if (coinsArray[0] != coinsArray[1]) {
return 2;
}
int count = 0;
if (coinsArray[0] != coinsArray[1]) {
count = 2;
}
for (int i = 1; i < coinsArray.length - 1; i++) {
if ((coinsArray[i - 1] != coinsArray[i]) || (coinsArray[i] != coinsArray[i + 1]))
count++;
}
if (coinsArray[coins - 2] != coinsArray[coins - 1]) {
count++;
}
return count;
} |
5d73901b-4ab2-47f8-8e7b-774126ba322d | 2 | public void draw(Graphics2D g2d) {
if (x != -1 && y != -1) {
g2d.drawImage(img_cannon, x, y, null);
missile.draw(g2d);
}
} |
95290ef4-f745-4998-bcb3-1bf7523c4093 | 3 | @Override
public void onPlayerJoin(PlayerJoinEvent event) {
tellUpdate = this.config.yml.getBoolean("Update.Notifications", true);
Player player = event.getPlayer();
if ((!player.isOp() && !player.hasPermission("bcs.admin")) || !tellUpdate) {
return;
}
this.plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new BCSUpdater(this.plugin, player, false));
return;
} |
4c1393b3-0e7d-42b0-8a6b-812ea9aa84c1 | 0 | public String getId() {
return delegate.getId();
} |
c2709ace-aa3b-4023-88b7-11be31335850 | 6 | public JSONObject getAnswersTag(int USER_ID,int QUESTION_ID)
{
try {
Class.forName(JDBC_DRIVER);
conn=DriverManager.getConnection(DB_URL,USER,PASS);
stmt=conn.createStatement();
json=new JSONObject();
String SQL="Select * from ANSWERS where QUESTION_ID="+QUESTION_ID;
rs=stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
json.put(SUCCESS, 1);
json.put(MESSAGE, "Answers Fetched");
JSONArray Answers=new JSONArray();
JSONObject answer;
while(rs.next())
{
answer=new JSONObject();
answer.put("ANSWER", rs.getString("ANSWER"));
answer.put("ANSWER_ID", rs.getString("ANSWER_ID"));
answer.put("RANK", rs.getInt("RANK"));
Answers.add(answer);
}
json.put("ANSWERS", Answers);
}
else
{
json.put(SUCCESS, 0);
json.put(MESSAGE, "This Question doesn't has any Answer yet");
return(json);
}
rs.close();
stmt.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
//json.put(SUCCESS, 0);
//json.put(MESSAGE, "Sorry, couldn't Process Request");
return(json);
} |
0f06efc6-63f0-4b98-a205-b4539ffac5ca | 5 | @Override
public void map(LongWritable key, Text value,
OutputCollector<Text, IntWritable> output, Reporter reporter)
throws IOException {
// TODO Auto-generated method stub
boolean start = false;
String line = value.toString();
Pattern title_pattern = Pattern.compile("<title>.*</title>");
Matcher title_matcher = title_pattern.matcher(line);
while (title_matcher.find()) {
title = title_matcher.group();
title = title.substring(7, title.length() - 8)
.replaceAll("\\&", "&")
.replaceAll("\\"", "\"");
return;
}
if(line.contains(new String("<text"))) {
start = true;
}
if(start) {
Pattern pattern = Pattern.compile("\\[\\[[^\\[\\]]+\\]\\]");
Matcher matcher = pattern.matcher(line);
int count = 0;
while (matcher.find())
count ++;
output.collect(new Text(title), new IntWritable(count));
}
if(line.contains(new String("</text>"))) {
start = false;
}
} |
472f741e-8046-4b55-aa49-74cf1206af18 | 1 | @SuppressWarnings("unchecked")
public static final <T> TypeHandler<T> getTypeHandler(Class<T> cls) {
TypeHandler<T> res = (TypeHandler<T>) typehandlers.get(cls);
if (res == null) {
throw new EncodingException("No handler registered for class: " + cls.toString());
}
return res;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.