method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
51e6d45a-b299-4a4f-a019-a1da2f31532d | 0 | public void set(int index, Attributes attributeList) {
RangeCheck(index);
attributeLists[index] = attributeList;
} |
0c3b5622-230e-44a5-80e6-d6e415442b5a | 2 | public static void creadXml() {
File file = new File(xml);
if (file.exists()) {
System.out.println("product.xml已存在");
} else {
Document document = DocumentHelper.createDocument();
Element rootElement1 = document.addElement(ENFINITY);
Element offerElement1 = rootElement1.addElement(OFFER);
offerElement1.addAttribute(SKU, "JC-PA80I");
Element nameElement1 = offerElement1.addElement(NAME);
nameElement1.setText("高铝质PA80耐火浇注料");
Element descriptionElement1 = offerElement1.addElement(DESCRIPTION);
descriptionElement1.setText("1");
Element onlineElement1 = offerElement1.addElement(ONLINE);
onlineElement1.setText("1");
Element offerElement2 = rootElement1.addElement(OFFER);
offerElement2.addAttribute(SKU, "JC-PA80II");
Element nameElement2 = offerElement2.addElement(NAME);
nameElement2.setText("高铝质PA80高强耐火浇注料");
Element descriptionElement2 = offerElement2.addElement(DESCRIPTION);
descriptionElement2.setText("2");
Element onlineElement2 = offerElement2.addElement(ONLINE);
onlineElement2.setText("2");
try {
Writer out = new FileWriter(xml);
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(out, format);
writer.write(document);
writer.close();
System.out.println("product.xml创建成功");
} catch (IOException e) {
e.printStackTrace();
System.out.println("product.xml创建失败");
}
}
} |
bc7ab5bb-495b-4bf6-ab9e-a398c547da00 | 6 | public boolean hayLugarEnPlan (int id_padre, String codigo_plan_padre){
boolean haylugar = false;
try {
r_con.Connection();
ResultSet rs = r_con.Consultar("select COUNT(*) from "+nameTable+" where pc_id_padre="+id_padre);
rs.next();
int futuroHijo = rs.getInt(1);
futuroHijo++;
if ((codigo_plan_padre.length()==1) && (codigo_plan_padre.equals("0"))){
haylugar = futuroHijo<=9;
}
else{
//caso hijo de Activo, etc
if (codigo_plan_padre.length()==1){
haylugar = futuroHijo<=9;
}
else{
//caso de hijo en que ya son 1.1, 1.2. etc
if ((codigo_plan_padre.length()>=1)&&((codigo_plan_padre.length()<3))){
haylugar = futuroHijo<=9;
}
else{
//caso de hijo en que ya son .11, .12. etc
haylugar = futuroHijo<=99;
}
}
}
r_con.cierraConexion();
} catch (SQLException ex) {
r_con.cierraConexion();
Logger.getLogger(GUI_Plan_Cuentas.class.getName()).log(Level.SEVERE, null, ex);
}
return haylugar;
} |
610053a8-3d83-44ef-ab6c-10dccc04a447 | 2 | public static boolean hasConstructor(Class<?> clazz, Class<?>... paramTypes) {
return (getConstructorIfAvailable(clazz, paramTypes) != null);
} |
0ea7a3cc-e8f3-43fa-aa86-a87fc446ca2a | 8 | private void packFlac() throws IOException {
// get output file
File outFile = getOutputFile();
if (outFile == null) return;
BitOutputStream os = null;
FileOutputStream fos;
try {
fos = new FileOutputStream(outFile);
os = new BitOutputStream(fos);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return;
}
// get seek table
SeekTable seekTable = makeSeekTable();
if (masterStreamInfo == null) return;
// write FLAC marker
os.writeByteBlock(Constants.STREAM_SYNC_STRING, Constants.STREAM_SYNC_STRING.length);
// output StreamInfo
masterStreamInfo.write(os, false);
// output SeekTable
seekTable.write(os, true);
// generate output file
for (int i = 0; i < albumFiles.size(); i++) {
PackerFile aFile = (PackerFile)albumFiles.get(i);
appendMsg("Process file " + i + ": " + aFile.file);
try {
RandomAccessFile raf = new RandomAccessFile(aFile.file, "r");
raf.seek(aFile.firstFrameOffset);
for (int bytes = raf.read(buffer); bytes > 0; bytes = raf.read(buffer)) {
fos.write(buffer, 0, bytes);
}
fos.flush();
} catch (FileNotFoundException e) {
appendMsg("File " + aFile.file + ": " + e);
} catch (EOFException e) {
appendMsg("File " + aFile.file + ": Done!");
} catch (IOException e) {
appendMsg("File " + aFile.file + ": " + e);
}
}
} |
6fc1ed51-8563-472e-8ff8-55d58ca71914 | 9 | public boolean nameEnumeratorResponse(Interest interest) throws IOException {
boolean result = false;
ContentName neRequestPrefix = interest.name().cut(CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes());
File directoryToEnumerate = NDNNameToFilePath(neRequestPrefix);
if (!directoryToEnumerate.exists() || !directoryToEnumerate.isDirectory()) {
// nothing to enumerate
return result;
}
NameEnumerationResponse ner = new NameEnumerationResponse();
ner.setPrefix(new ContentName(neRequestPrefix, CommandMarker.COMMAND_MARKER_BASIC_ENUMERATION.getBytes()));
Log.info("Directory to enumerate: {0}, last modified {1}", directoryToEnumerate.getAbsolutePath(), new NDNTime(directoryToEnumerate.lastModified()));
// stat() the directory to see when it last changed -- will change whenever
// a file is added or removed, which is the only thing that will change the
// list we return.
ner.setTimestamp(new NDNTime(directoryToEnumerate.lastModified()));
// See if the resulting response is later than the previous one we released.
//now add the response id
ContentName prefixWithId = new ContentName(ner.getPrefix(), _responseName.components());
//now finish up with version and segment
ContentName potentialCollectionName = VersioningProfile.addVersion(prefixWithId, ner.getTimestamp());
//switch to add response id to name enumeration objects
//ContentName potentialCollectionName = VersioningProfile.addVersion(ner.getPrefix(), ner.getTimestamp());
potentialCollectionName = SegmentationProfile.segmentName(potentialCollectionName, SegmentationProfile.baseSegment());
//check if we should respond...
if (interest.matches(potentialCollectionName, null)) {
// We want to set the version of the NE response to the time of the
// last modified file in the directory. Unfortunately that requires us to
// stat() all the files whether we are going to respond or not.
String [] children = directoryToEnumerate.list();
if ((null != children) && (children.length > 0)) {
for (int i = 0; i < children.length; ++i) {
ner.add(children[i]);
}
NameEnumerationResponseMessage nem = ner.getNamesForResponse();
NameEnumerationResponseMessageObject neResponse = new NameEnumerationResponseMessageObject(prefixWithId, nem, _handle);
neResponse.save(ner.getTimestamp(), interest);
result = true;
Log.info("sending back name enumeration response {0}, timestamp (version) {1}.", ner.getPrefix(), ner.getTimestamp());
} else {
Log.info("no children available: we are not sending back a response to the name enumeration interest (interest = {0}); our response would have been {1}", interest, potentialCollectionName);
}
} else {
Log.info("we are not sending back a response to the name enumeration interest (interest = {0}); our response would have been {1}", interest, potentialCollectionName);
if (interest.exclude().size() > 1) {
Exclude.Element el = interest.exclude().value(1);
if ((null != el) && (el instanceof ExcludeComponent)) {
Log.info("previous version: {0}", VersioningProfile.getVersionComponentAsTimestamp(((ExcludeComponent)el).getBytes()));
}
}
}
return result;
} |
b73f33e5-d778-46ff-9e54-861bfa7902ab | 5 | public Reader_factory get_reader(int id) {
Reader_factory reader = null;
if(readers == null) return null;
List listreaders = readers.getChildren();
if (listreaders != null){
Iterator i = listreaders.iterator();
while(i.hasNext()){
Element current = (Element)i.next();
int currid = Integer.parseInt(current.getAttributeValue("id"));
if(currid == id) {
String user = current.getAttributeValue("userid");
int userid = 0;
if(user != null)
userid = Integer.parseInt(user);
reader = new Reader_factory(currid, current.getAttributeValue("manufacturer"),
current.getAttributeValue("name"),
current.getAttributeValue("picture"),
current.getAttributeValue("port"),
userid );
//System.out.println("Reader found "+reader.name);
return reader;
}
}
}
return null; //Not found
} |
3d784016-f66c-4414-a26d-54c1647409ec | 8 | @Override
public T decode(byte[] data) throws ConverterException {
byte[] decompressedData;
if (data[0] == 120) {
decompressedData = decompress(data);
} else {
decompressedData = data;
}
Map<Integer, QualifiedValue<?>> idxLookup = new HashMap<>();
T entity = createEntity();
ByteArrayInputStream bin = new ByteArrayInputStream(decompressedData);
CodedInputStream input = CodedInputStream.newInstance(bin);
int tag;
try {
while ((tag = input.readTag()) != 0) {
int field = WireFormat.getTagFieldNumber(tag);
switch (field) {
case ID:
entity.setId(converterFactory.getIdEncoder().decode(input));
break;
case FIELD:
ByteString bf = input.readBytes();
readField(entity, bf.toByteArray(), idxLookup);
break;
case RELATION:
ByteString br = input.readBytes();
readRelation(entity, br.toByteArray(), idxLookup);
break;
default:
break;
}
}
} catch (Exception e) {
throw new ConverterException("Could not read entity from byte array!", e);
} finally {
try {
bin.close();
} catch (IOException e) {
throw new RuntimeException("Could not close input stream!", e);
}
}
return entity;
} |
521e18a3-944d-4460-b70c-32038a659de3 | 1 | public void visitRCExpr(final RCExpr expr) {
print("rc(");
if (expr.expr() != null) {
expr.expr().visit(this);
}
print(")");
} |
382ef99e-dc77-44fd-b1a7-3b3becf70a51 | 8 | public ArrayList<Integer> getNeighbours(int node, int size) {
ArrayList<Integer> neighbours = new ArrayList<Integer>();
if(node == 0) { //Top-left
neighbours.add(node+1);
neighbours.add(node+size);
}
else if (node == size-1) { //Top-right
neighbours.add(node-1);
neighbours.add(node+size);
}
else if (node == size*size-size) { //Bottom-left
neighbours.add(node+1);
neighbours.add(node-size);
}
else if (node == size*size-1) { //Bottom-right
neighbours.add(node-1);
neighbours.add(node-size);
}
else if (node%size == 0) { //Left
neighbours.add(node+1);
neighbours.add(node+size);
neighbours.add(node-size);
}
else if ((node+1)%size == 0) { //Right
neighbours.add(node-1);
neighbours.add(node+size);
neighbours.add(node-size);
}
else if (node<size) { //Top
neighbours.add(node+1);
neighbours.add(node-1);
neighbours.add(node+size);
}
else if (node>(size*size-size)) { //Bottom
neighbours.add(node+1);
neighbours.add(node-1);
neighbours.add(node-size);
}
else { //Centre (all 4 neighbours)
neighbours.add(node+1);
neighbours.add(node-1);
neighbours.add(node+size);
neighbours.add(node-size);
}
return neighbours;
} |
128fe623-4b97-4be7-bbaa-063d7a4e7a3b | 0 | public void setNewEmail(String newEmail) {
putMergeVar("new-email", newEmail);
} |
2eb744f8-bb6d-4f83-a759-1c9edbf83f91 | 3 | public static JSONObject toJSONObject(String string) throws JSONException {
String name;
JSONObject jo = new JSONObject();
Object value;
JSONTokener x = new JSONTokener(string);
jo.put("name", x.nextTo('='));
x.next('=');
jo.put("value", x.nextTo(';'));
x.next();
while (x.more()) {
name = unescape(x.nextTo("=;"));
if (x.next() != '=') {
if (name.equals("secure")) {
value = Boolean.TRUE;
} else {
throw x.syntaxError("Missing '=' in cookie parameter.");
}
} else {
value = unescape(x.nextTo(';'));
x.next();
}
jo.put(name, value);
}
return jo;
} |
f457079d-b6a5-4dc3-acdb-16b9a7b668f6 | 5 | public void run() {
// Continuous file read
try {
while(true) {
while((line = file.readLine()) != null) {
if(line.matches(".*[Xx][Aa][Mm][Xx][Ee].*")) {
this.server.sendMessage(-1, "Someone is requesting Xamxe", CMD_SRV_MSG);
this.server.sendMessage(-1, "Content: " + line, CMD_SRV_MSG);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
} |
1ee15ae7-ed98-47a9-a0a3-d783679cd481 | 2 | public boolean alreadyVoted(int userId, int formId) {
try {
String q1 = "select count(*) from formresponse where userid = ? and formid = ?;";
PreparedStatement st1 = conn.prepareStatement(q1);
st1.setInt(1, userId);
st1.setInt(2, formId);
ResultSet rs = st1.executeQuery();
conn.commit();
rs.next();
return rs.getInt(1) > 0;
} catch (SQLException e) {
try {
e.printStackTrace();
conn.rollback();
} catch (Exception e2) {
e2.printStackTrace();
}
return true;
}
} |
54769dea-8b1a-478f-bd7e-5d7f46faa008 | 0 | public int getG() {
return this.g;
} |
14e8d3ab-3e49-4d48-be31-5dd6b6115be6 | 0 | public PosFuncionarios getFuncionario(long cedula){
return (PosFuncionarios) getHibernateTemplate().get(PosFuncionarios.class, cedula);
} |
f2715aba-d7f8-44bf-8378-9013a31ce51c | 0 | public IautosSellerInfo getNewSeller() {
return newSeller;
} |
21a86d6c-1867-4efa-b529-9d376b92188e | 2 | private void drawArea(Graphics g, Automaton automaton, State state,
Point point, Color color) {
// Draw the basic background of the state.
drawBackground(g, state, point, color);
// What about the text label?
g.setColor(Color.black);
int dx = ((int) g.getFontMetrics().getStringBounds(state.getName(), g)
.getWidth()) >> 1;
int dy = ((int) g.getFontMetrics().getAscent()) >> 1;
g.drawString(state.getName(), point.x - dx, point.y + dy);
// Draw the outline.
// //System.out.println("State name:" + state.getInternalName());
// if (state.getInternalName() == null) {
g.drawOval(point.x - radius, point.y - radius,
2 * radius, 2 * radius);
// If this is a final state, draw the little "inner circle."
if (automaton.isFinalState(state))
g.drawOval(point.x - radius + 3, point.y - radius + 3,
(radius - 3) << 1, (radius - 3) << 1);
// If this is the initial state.
if (automaton.getInitialState() == state) {
int[] x = { point.x - radius, point.x - (radius << 1),
point.x - (radius << 1) };
int[] y = { point.y, point.y - radius, point.y + radius };
g.setColor(Color.white);
g.fillPolygon(x, y, 3);
g.setColor(Color.black);
g.drawPolygon(x, y, 3);
}
// } else {
// Double temp = new Double(radius * 1.5);
// g.drawRect(point.x - radius, point.y - radius, 2 * radius,
// 2 * radius);
// // If this is a final state, draw the little "inner rectangle."
// if (automaton.isFinalState(state))
// g.drawRect(point.x - radius + 3, point.y - radius + 3,
// (radius - 3) << 1, (radius - 3) << 1);
// // If this is the initial state.
// if (automaton.getInitialState() == state) {
// int[] x = { point.x - radius, point.x - (radius << 1),
// point.x - (radius << 1) };
// int[] y = { point.y, point.y - radius, point.y + radius };
// g.setColor(Color.white);
// g.fillPolygon(x, y, 3);
// g.setColor(Color.black);
// g.drawPolygon(x, y, 3);
// }
// }
} |
0ee74b5d-93b0-445c-9f15-255bc02fdb0e | 5 | public static void main(String[] args)
{
BaseSetting bs = new BaseSetting();
Wording w = new Wording("Je suis un énoncé", new Object[10]);
if (w != null) {System.out.println("WORDING NOT NULL");}
// INSERTION WORDING
w.insert(bs);
if (w != null) {System.out.println("WORDING NOT NULL");}
w = null;
if (w == null) {System.out.println("WORDING NULL");}
w = Wording.findById(1, bs);
if (w != null) {System.out.println("WORDING NULL");}
if (bs != null) {System.out.println("BS OK");}
ArrayList<Question> alq = new ArrayList<>();
QuestionCalculation qc1 = new QuestionCalculation("Qui suis-je ?",1);
ArrayList<Integer> ali1 = new ArrayList<>();
ali1.add(6);
ali1.add(9);
qc1.setOperands(ali1);
ArrayList<Character> alc1 = new ArrayList<>();
alc1.add('-');
qc1.setOperators(alc1);
qc1.setLength(0);
QuestionCalculation qc2 = new QuestionCalculation("Où est Brian ?",1);
ArrayList<Integer> ali2 = new ArrayList<>();
ali2.add(6);
ali2.add(6);
ali2.add(6);
qc2.setOperands(ali2);
ArrayList<Character> alc2 = new ArrayList<>();
alc2.add('/');
alc2.add('/');
qc2.setOperators(alc2);
qc2.setLength(0);
// INSERTION QUESTIONS
qc1.insert(bs);
qc2.insert(bs);
System.out.println("INSERT QC OK");
alq.add(qc1);
alq.add(qc2);
Exercise e1 = new Exercise("Titre1", w, alq, "Exercice de calculs", 1, true);
Exercise e2 = new Exercise("Titre2", w, alq, "Exercice de calculs", 1, true);
Exercise e3 = new Exercise("Titre3", w, alq, "Exercice de calculs", 1, true);
Exercise e4 = new Exercise("Titre4", w, alq, "Exercice de calculs", 1, true);
// INSERTION EXERCISE
e1.insert(bs);
e2.insert(bs);
e3.insert(bs);
e4.insert(bs);
System.out.println("INSERT E OK");
ArrayList<Exercise> ale = Exercise.findAll(bs);
ArrayList<Question> alquest = e1.findById_AllQuestions(1, bs);
System.out.println(">>> "+alquest+" <<<");
} |
5c488404-e484-4ed4-8845-61cc0ced8858 | 1 | public int getTotal() {
calculateTotal();
if (total > 21) {
changeAce();
calculateTotal();
}
return total;
} |
d2a12512-2b8d-4cca-9ebd-6529952ee99d | 3 | private void sendQuickLaunchFile(int index){
File f = quick_launch_files[index];
if(f==null) return;
QLUpdate ql = new QLUpdate();
ql.itemIndex = index;
ql.fileName = f.getName();
// Generate the png's to send to android
FileSystemView fsv = FileSystemView.getFileSystemView();
Icon ico = fsv.getSystemIcon(f);
BufferedImage bi = new BufferedImage(ico.getIconWidth(), ico.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics big = bi.getGraphics();
ico.paintIcon(null, big, 0, 0);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(bi, "png", baos);
} catch (IOException e1) {
System.err.println("Error generating icon");
return;
}
// just send the one file
byte[] imageBytes = baos.toByteArray();
ql.icon = new byte[imageBytes.length];
ql.icon = imageBytes;
if (client_connected) {
System.out.println("Sending QLUpdate: Icon: [" + ql.icon.length + "] String: " + ql.fileName.getBytes().length);
server.sendToAllTCP(ql);
}
} |
7080d9cc-3075-47c3-8fd0-a469e380951d | 8 | static void resetRuns(BitStream outb, G4State state) throws IOException {
//System.err.println("EOL! "+state.a0);
state.white = true;
addRun(0, state, outb);
if (state.a0 != state.width) {
//System.out.println( (state.a0 < state.width ? "Premature EOL" : "Line length mismatch") );
while (state.a0 > state.width)
state.a0 -= state.cur[--state.curIndex];
if (state.a0 < state.width) {
if (state.a0 < 0)
state.a0 = 0;
if ((state.curIndex & 0x1) != 0)
addRun(0, state, outb);
addRun(state.width - state.a0, state, outb);
} else if (state.a0 > state.width) {
addRun(state.width, state, outb);
addRun(0, state, outb);
}
}
int tmp[] = state.ref;
state.ref = state.cur;
state.cur = tmp;
//now zero out extra spots for runs
for (int i = state.curIndex; i < state.width; i++)
state.ref[i] = 0;
for (int i = 0; i < state.width; i++)
state.cur[i] = 0;
state.runLength = 0;
state.a0 = 0;
state.b1 = state.ref[0];
state.refIndex = 1;
state.curIndex = 0;
outb.close();
} |
3f38860a-d865-44e7-8d9b-e0cf0f875e2d | 5 | @Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex == NUMBER) {
return Integer.class;
} else if (columnIndex == TYPE) {
return String.class;
} else if (columnIndex == MODEL) {
return String.class;
} else if (columnIndex == RETURN_DATE) {
return Date.class;
} else {
return Object.class;
}
} |
f728db00-555a-4bb0-9222-9144a1281b10 | 9 | @SuppressWarnings("unchecked")
public static EventReader createEventReader(EventEntry eventEntry){
Properties unisensProperties = UnisensProperties.getInstance().getProperties();
String readerClassName = unisensProperties.getProperty(Constants.EVENT_READER.replaceAll("format", eventEntry.getFileFormat().getFileFormatName().toLowerCase()));
if(readerClassName != null){
try{
Class<EventReader> readerClass = (Class<EventReader>)Class.forName(readerClassName);
Constructor<EventReader> readerConstructor = readerClass.getConstructor(EventEntry.class);
return (EventReader)readerConstructor.newInstance(eventEntry);
} catch (ClassNotFoundException e) {
System.out.println("Class (" + readerClassName + ") could not be found!");
e.printStackTrace();
} catch (InstantiationException e) {
System.out.println("Class (" + readerClassName + ") could not be instantiated!");
e.printStackTrace();
} catch (IllegalAccessException e) {
System.out.println("Class (" + readerClassName + ") could not be accessed!");
e.printStackTrace();
} catch (ClassCastException ec) {
ec.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
return null;
} |
a42418b9-ee22-4d69-8f6e-cc74db0cd28d | 6 | private static Image getImage(String filename) {
// to read from file
ImageIcon icon = new ImageIcon(filename);
// try to read from URL
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
try {
URL url = new URL(filename);
icon = new ImageIcon(url);
} catch (Exception e) { /* not a url */ }
}
// in case file is inside a .jar
if ((icon == null) || (icon.getImageLoadStatus() != MediaTracker.COMPLETE)) {
URL url = StdDraw.class.getResource(filename);
if (url == null) throw new IllegalArgumentException("image " + filename + " not found");
icon = new ImageIcon(url);
}
return icon.getImage();
} |
13c97fa3-44aa-4c84-b8a1-377849618e9a | 0 | public boolean isEmpty() {
return size == 0;
} |
da5450b4-bc45-4303-98d8-a268cc2a85b3 | 4 | @Override
public void run() {
while (crawler.pageDone == false || crawler.contentUrls.size() > 0) {
if (crawler.contentUrls.size() != 0) {
saveAsText(crawler.contentUrls.remove());
} else {
try {
sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} |
8fb6622c-2fa5-4153-a0c8-10ee9b0e5a68 | 6 | public void fill(int x0, int y0, int x1, int y1, int color) {
x0 += xOffs;
y0 += yOffs;
x1 += xOffs;
y1 += yOffs;
if (x0 < 0) x0 = 0;
if (y0 < 0) y0 = 0;
if (x1 >= w) x1 = w - 1;
if (y1 >= h) y1 = h - 1;
for (int y = y0; y <= y1; y++) {
for (int x = x0; x <= x1; x++) {
pixels[x + y * w] = color;
}
}
} |
98247bf6-5c8f-499b-aa6e-f94ddcadd7bf | 9 | @Override
public SetMultimap<Position, Position> getAllAvailableMoves(Player activePlayer, Board board) {
SetMultimap<Position, Position> allMoves = getAllAvailableCaptures(activePlayer, board);
if (!allMoves.isEmpty()) {
return allMoves;
}
for (int i = 1; i < board.getSize(); i++) {
for (int j = 1; j < board.getSize(); j++) {
Position startPos = new Position(i, j);
if (activePlayer == Player.PLAYER_ONE
&& (board.getFieldAt(i, j) == Board.WHITE_KING
|| board.getFieldAt(i, j) == Board.WHITE_REGULAR_PIECE)) {
allMoves.putAll(startPos,
getAvailableMoves(startPos, board));
} else if (activePlayer == Player.PLAYER_TWO
&& (board.getFieldAt(i, j) == Board.BLACK_KING
|| board.getFieldAt(i, j) == Board.BLACK_REGULAR_PIECE)) {
allMoves.putAll(startPos,
getAvailableMoves(startPos, board));
}
}
}
return allMoves;
} |
c20d9afc-a11a-4b77-9b30-21c54cd457d0 | 2 | private void scrapeSearchResults(String siteText) {
Document doc = Jsoup.parse(siteText);
if (doc.select("td:containsOwn(No results returned)").size() == 1) {
return;
}
Elements rows = doc.select("table").get(1).select("tr");
rows.remove(0);
ArrayList<PeopleSearchResult> peopleList = new ArrayList<PeopleSearchResult>();
for (Element row : rows) {
Elements cols = row.select("td");
Element imageNode = cols.get(0);
Element nameNode = cols.get(1);
PeopleSearchResult person = new PeopleSearchResult();
person.setThumbUrl(imageNode.select("img").attr("src"));
person.setImageUrl(Utility.imageUrlFromThumbUrl(person.getThumbUrl(), 'v'));
person.setId(Utility.idFromUrl(nameNode.select("a").attr("href")));
person.setName(nameNode.select("a").text());
peopleList.add(person);
}
Object[] objectArray = peopleList.toArray();
searchResults = Arrays.copyOf(objectArray, objectArray.length, PeopleSearchResult[].class);
} |
cc2c1ffd-139f-4487-930b-10474605b443 | 8 | public boolean execute(CommandSender sender, String[] args) {
String groupName = args[0];
GroupManager groupManager = Citadel.getGroupManager();
Faction group = groupManager.getGroup(groupName);
if(group == null){
sendMessage(sender, ChatColor.RED, "Group doesn't exist");
return true;
}
String playerName = sender.getName();
if(group.isFounder(playerName)){
sendMessage(sender, ChatColor.RED, "You are the owner. If you wish to leave you must either delete or transfer the group");
return true;
}
if(group.isPersonalGroup()){
sendMessage(sender, ChatColor.RED, "You cannot leave your default group");
return true;
}
if(!group.isMember(playerName) && !group.isModerator(playerName)){
sendMessage(sender, ChatColor.RED, "You are not a member of %s", group.getName());
return true;
}
if(group.isModerator(playerName)){
groupManager.removeModeratorFromGroup(groupName, playerName);
}
if(group.isMember(playerName)){
groupManager.removeMemberFromGroup(groupName, playerName);
}
sendMessage(sender, ChatColor.GREEN, "You have left the group %s", group.getName());
MemberManager memberManager = Citadel.getMemberManager();
if(memberManager.isOnline(group.getFounder())){
Player founder = memberManager.getOnlinePlayer(group.getFounder());
sendMessage(founder, ChatColor.YELLOW, "%s has left the group %s", playerName, group.getName());
}
return true;
} |
347e2d91-7f3c-485f-8c98-1444da9e9a5a | 9 | public void updateElement() {
for (Projectile projectile : projectileScope) {
boolean tmpFlagNotUsed = true;
if (projectile.getProjectileType() == PROJECTILE_FIRST) {
for (int i = heroZonesArray.length - 1; i > -1; i--) {
Hero tmphero=FAiF.gameScreen.heroStock.getHeroByZoneId(heroZonesArray[i].zoneId);
if ((tmpFlagNotUsed)&& ( tmphero!= null)) {
if (!tmphero.isDead()){
tmphero.addProjectile(projectile);
tmpFlagNotUsed = false;
}
}
}
} else {
if (projectile.getProjectileType() == PROJECTILE_ALL) {
for (int i = heroZonesArray.length - 1; i > -1; i--) {
if ((FAiF.gameScreen.heroStock
.getHeroByZoneId(heroZonesArray[i].zoneId) != null)) {
FAiF.gameScreen.heroStock.getHeroByZoneId(
heroZonesArray[i].zoneId).addProjectile(
projectile);
}
}
}
}
}
projectileScope.removeAll(projectileScope);
} |
24fa815f-a0bc-491b-aad9-93247cdd2686 | 4 | public void setAroundBounds()
{
if(x < punkt2X)
{
dx = x;
dwidth = punkt2X - x;
}
if(x > punkt2X)
{
dx = punkt2X;
dwidth = x - punkt2X;
}
if(y < punkt2Y)
{
dy = y;
dheight = punkt2Y - y;
}
if(y > punkt2Y)
{
dy = punkt2Y;
dheight = y - punkt2Y;
}
} |
07978733-9d60-495e-8776-12e37e569021 | 2 | protected static String getFieldValue(HttpServletRequest request, String fieldName) {
String value = request.getParameter(fieldName);
if(value == null || value.trim().length() == 0) {
return null;
} else {
return value;
}
} |
64363c04-8114-4b46-b36b-685d4f389abb | 0 | @Before
public void setUp() {
this.p = new Piste(0, 0);
} |
d4e8ac15-b3ac-449a-a489-64e2d5c00006 | 2 | public void llenarCombobox() {
String to = System.getProperty("user.dir"); // recupero el directorio del proyecto
String separator = System.getProperty("file.separator"); //recupero el separador ex: Windows= '\' , Linux='/'
to = to + separator + "src" + separator + "src" + separator; // concateno la ruta destino
File f = new File(to);
this.cbxFile.removeAllItems();
if (f.exists()) { // Directorio existe
File[] ficheros = f.listFiles();
for (int x = 0; x < ficheros.length; x++) {
this.cbxFile.addItem(ficheros[x].getName());
}
} else { //Directorio no existe
}
} |
8516dec4-fd6f-4145-a33a-56e21b4cdb80 | 2 | public int numTrees(int n) {
long a = 1;
long b = 1;
for(int i = 2*n;i> n+1;i--)
a*= i;
for(int i=n;i>0;i--)
b *= i;
return (int) (a/b);
} |
cd07b36a-5c7c-48e2-9af7-b0390cd7cefe | 6 | protected Rules processRules(Element element,RuleDefinitionInterface currentRuleDefn){
Rules rules=(Rules)Factory.getFactory().getDataObject(Factory.ObjectTypes.Rules);
rules.setName(element.getAttribute("name"));
rules.setChange(Change.getInstance(element.getAttribute("change")));
rules.setOnType(SchemaTypes.getInstance(element.getAttribute("on")));
NodeList inludes=element.getElementsByTagName("include");
if(inludes!=null){
for(int i=0;i<inludes.getLength();i++){
Element include=(Element)inludes.item(i);
if(include.hasAttribute("rules")){
rules.addIncludes(include.getAttribute("rules"));
}
if(include.hasAttribute("ruleset")){
if(currentRuleDefn.getRuleSets()!=null && currentRuleDefn.getRuleSets().containsKey(include.getAttribute("ruleset"))){
rules.addRulesSets(currentRuleDefn.getRuleSets().get(include.getAttribute("ruleset")));
}
}
}
}
return rules;
} |
68072e93-5e5d-40e7-82bd-d8317ed0cc5a | 0 | public boolean isDestroyed() {
return carPhysics.isDestroyed();
} |
2bf09ab9-0a98-4532-8edb-81c16f9f6224 | 5 | @EventHandler
public void onBlockBreakEvent(BlockBreakEvent event) {
if (!event.isCancelled()) {
Player player = event.getPlayer();
if (Cloning.contains(player)) {
if (Cloning.isEnabled(player)) {
if (event.getBlock().getState().getData() instanceof Bed) {
Bed bed = (Bed) event.getBlock().getState().getData();
if(bed.isHeadOfBed()){
Cloning.delete(player,event.getBlock().getRelative(bed.getFacing().getOppositeFace()));
return;
}
}
Cloning.delete(player, event.getBlock());
}
}
}
} |
ed2b5250-a72a-4d31-af79-5f23ecf80f56 | 5 | private Method getGetterMethod(Class boClass, String fieldName, Class fieldType) throws DataException {
String getterName = "get" + fieldName.substring(0, 1).toUpperCase();
if (fieldType == Boolean.class || fieldType == boolean.class) {
getterName = "is" + fieldName.substring(0, 1).toUpperCase();
}
if (fieldName.length() > 1) {
getterName += fieldName.substring(1);
}//if
try {
Method method = boClass.getDeclaredMethod(getterName);
if (method.getReturnType() == fieldType) {
return method;
}
}catch (NoSuchMethodException nsme) {
// pass so we throw the exception at the end
}//try
throw new DataException("Error in " + boClass.getName() + ". No method named " + getterName + "(" + fieldType.getName() + ") to correspond with field " + fieldName + " in the database.");
} |
85dc7406-7458-4559-a4f6-c6a390d49905 | 1 | private byte[] createByteArray(InputStream in) throws IOException {
final int bufferSize = 2048;
byte result[] = new byte[bufferSize];
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(result)) != -1) out.write(result, 0, len);
return out.toByteArray();
} |
3ee70e64-3e23-4c3b-9efe-15b4f51ff02d | 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 Area)) {
return false;
}
Area other = (Area) object;
if ((this.areidArea == null && other.areidArea != null) || (this.areidArea != null && !this.areidArea.equals(other.areidArea))) {
return false;
}
return true;
} |
dbab2e76-c2c6-422d-8ee2-da048941c545 | 9 | @Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
if(
(CMLib.flags().isWateryRoom(mob.location()))
||(mob.location().domainType()==Room.DOMAIN_OUTDOORS_AIR)
||(mob.location().domainType()==Room.DOMAIN_INDOORS_AIR)
)
{
mob.tell(L("This magic will not work here."));
return false;
}
final Item target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_UNWORNONLY);
if(target==null)
return false;
if(!Druid_MyPlants.isMyPlant(target,mob))
{
mob.tell(L("@x1 is not one of your plants!",target.name(mob)));
return false;
}
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
// now see if it worked
final boolean success=proficiencyCheck(mob,0,auto);
if(success)
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?"":L("^S<S-NAME> chant(s) to <T-NAMESELF>.^?"));
if(mob.location().okMessage(mob,msg))
{
mob.location().send(mob,msg);
beneficialAffect(mob,target,asLevel,0);
}
}
else
return beneficialWordsFizzle(mob,target,L("<S-NAME> chant(s) to the <T-NAMESELF>, but nothing happens."));
// return whether it worked
return success;
} |
e37c7c22-263e-4696-8545-08d364fcc45c | 8 | public static Connection getConnection() {
if (connectionList == null) {
connectionList = new Connection[maxConnections];
connectionInUse = new boolean[maxConnections];
for (int i = 0; i < maxConnections; i++) {
connectionInUse[i] = false;
}
}
boolean allInUse = true;
int empty = -1;
for (int i = 0; i < maxConnections; i++) {
if (connectionInUse[i] == false) {
allInUse = false;
empty = i;
connectionInUse[i] = true;
break;
}
}
if (!allInUse) {
if (connectionList[empty] == null) {
Connection conn = getConn();
connectionList[empty] = conn;
}
if (debug)
System.out.println("Get a connection in pool[" + empty + "]");
return connectionList[empty];
} else {
if (debug)
System.out.println("Too many connections!");
return null;
}
} |
cdd6228a-1e57-4cb2-b63b-22c7e10dfbd8 | 4 | public Password(String pass) {
try {
this.setKey();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
this.setupCipher();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
}
this.encrypt(pass);
} |
c62fdad9-ca61-4930-a4b5-960de552a01d | 3 | Instruction get0(int index) {
Instruction instr = borderInstr;
if (index < instructionCount / 2) {
for (int i = 0; i <= index; i++)
instr = instr.nextByAddr;
} else {
for (int i = instructionCount; i > index; i--)
instr = instr.prevByAddr;
}
return instr;
} |
c5bd7187-d3f6-49e9-9e3c-c6f9838c903e | 9 | protected void readChild(XMLStreamReader in) throws XMLStreamException {
String childName = in.getLocalName();
if (Ability.getXMLElementTagName().equals(childName)) {
if (getAttribute(in, "delete", false)) {
String id = in.getAttributeValue(null, ID_ATTRIBUTE_TAG);
removeAbilities(id);
in.nextTag();
} else {
Ability ability = new Ability(in, getSpecification());
if (ability.getSource() == null) {
ability.setSource(this);
}
addAbility(ability); // Ability close the element
getSpecification().addAbility(ability);
}
} else if (Modifier.getXMLElementTagName().equals(childName)) {
if (getAttribute(in, "delete", false)) {
String id = in.getAttributeValue(null, ID_ATTRIBUTE_TAG);
removeModifiers(id);
in.nextTag();
} else {
Modifier modifier = new Modifier(in, getSpecification());
if (modifier.getSource() == null) {
modifier.setSource(this);
}
if (modifier.getIndex() < 0) {
modifier.setIndex(getModifierIndex(modifier));
}
addModifier(modifier); // Modifier close the element
getSpecification().addModifier(modifier);
}
} else {
logger.warning("Parsing of " + childName
+ " is not implemented yet");
while (in.nextTag() != XMLStreamConstants.END_ELEMENT
|| !in.getLocalName().equals(childName)) {
in.nextTag();
}
}
} |
95b124b5-0f2c-42f4-8b18-eca45bf58ba2 | 8 | @Override
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D)g;
FontMetrics fontMetrics = null;
if (isLoading)
{
g2d.setColor(loadingBgColor);
}
else if (isSelected())
{
g2d.setColor(selectedBgColor);
}
else
{
g2d.setColor(Color.white);
}
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setColor(Color.black);
g2d.setFont(versionFont);
fontMetrics = g2d.getFontMetrics();
int versionNameX = getWidth() - 40 - fontMetrics.stringWidth(profile.getVersionName());
g2d.drawString(profile.getVersionName(), versionNameX, 20);
g2d.setColor(Color.black);
g2d.setFont(nameFont);
if (oldWidth != getWidth())
{
fontMetrics = g2d.getFontMetrics();
String name = profile.getProfileName();
if (fontMetrics.stringWidth(name) > versionNameX - 25)
{
int widthSum = 0;
for (int i = 0; i < name.length(); i++)
{
widthSum += fontMetrics.charWidth(name.charAt(i));
if (widthSum > versionNameX - 25)
{
name = name.substring(0, i) + "...";
break;
}
}
}
drawName = name;
oldWidth = getWidth();
}
g2d.drawString(drawName, 5, 30);
g2d.setColor(Color.gray);
g2d.setFont(statusFont);
fontMetrics = g2d.getFontMetrics();
String statusString = profile.getStatus().toString();
g2d.drawString(statusString, getWidth() - 40 - fontMetrics.stringWidth(statusString), 32);
BufferedImage image = inactiveIcon;
if (isLoading)
{
image = loadingIcon;
}
else if (profile.getStatus() == Status.FOUND)
{
image = activeIcon;
}
g2d.drawImage(image, getWidth() - image.getWidth() - 5, 4, null);
} |
45e276d4-c6ab-464d-b4c6-b47b4ee8477f | 9 | public void recompute()
{
// Here we check for the tree subdivision.
if( isLeaf() )
{
assert population == particles.size() : "Discepancy in population count of "+id+" ? (population="+population+" p.size="+particles.size()+")";
if( depth < tree.depthmax && population > tree.pmax )
{
mitosis();
for( Cell cell: sub )
cell.recompute();
}
}
else
{
int hasLeafs = 0;
int divs = space.getDivisions();
for( Cell cell: sub )
{
cell.recompute();
hasLeafs += cell.isLeaf() ? 1 : 0;
}
// System.err.printf( "Check fusion of cell %s: pop=%d max=%d aboveLeafs=%b%n", id, population, tree.pmax, leaf );
if( hasLeafs == divs && population <= tree.pmax ) // In fact the condition pop<pmax is
{ // sufficient, since no subcell can
fusion(); // be subdivided if there is this number
} // of particles. Its just another
} // invariant check.
if( data != null )
data.recompute();
} |
1939b84a-5c71-497c-8249-d7b6c6205a93 | 7 | public synchronized void init() {
if (inited) {
return;
}
inited = true;
InputStream in = null;
try {
stream.init();
in = stream.getInputStreamForDecodedStreamBytes();
if (logger.isLoggable(Level.FINEST)) {
String content;
if (in instanceof SeekableInput) {
content = Utils.getContentFromSeekableInput((SeekableInput) in, false);
} else {
InputStream[] inArray = new InputStream[]{in};
content = Utils.getContentAndReplaceInputStream(inArray, false);
in = inArray[0];
}
logger.finest("Content = " + content);
}
if (in != null) {
ICC_Profile profile = ICC_Profile.getInstance(in);
colorSpace = new ICC_ColorSpace(profile);
}
} catch (Exception e) {
logger.log(Level.FINE, "Error Processing ICCBased Colour Profile", e);
}
finally {
try {
if (in != null) in.close();
}
catch (IOException e) {
}
}
} |
81cb39f7-9cc8-4a69-a1bd-7f71fc1ce375 | 0 | public boolean isElectricBrakes() {
return electricBrakes;
} |
abb1ce28-d547-4359-a7d7-f077bb0792e2 | 0 | public void setHead(Items head) {
this.head = head;
} |
ae6f56be-8249-4117-871b-9aa0ceeeddeb | 3 | protected void event(MouseEvent paramMouseEvent)
{
String str = "";
if (this.VerboseEvents) {
if (paramMouseEvent.getID() == 501)
str = "P:";
else if (paramMouseEvent.getID() == 502) {
str = "R:";
}
}
processActionEvent(new ActionEvent(this, 1001, str + this.ActionCommand));
} |
27e971a5-cdd8-41cf-a66c-072f1dfbe35b | 4 | private final void add(final SongDataEntry songdata) {
final Path path = songdata.getPath();
final DirTree t = walkTo(path.getParent());
if (t == null) {
return;
}
synchronized (t) {
final SongDataEntry sd = t.files.get(path.getFilename());
if (sd == null) {
t.files.put(path.getFilename(), songdata);
} else if (sd.getLastModification() < songdata
.getLastModification()) {
t.files.put(path.getFilename(), songdata);
} else {
synchronized (AbtractEoWInAbc.messages) {
AbtractEoWInAbc.messages.remove(path);
}
return;
}
}
for (DirTree tree = t; tree != null; tree = tree.parent) {
tree.size.incrementAndGet();
}
} |
4256fa23-dd0c-4b49-9fe9-d5a1859d5a02 | 6 | public void positionRelativeTo(GameObject go, int xOffset, int yOffset){
this.setViewDegree(go.getViewDegree());
switch (xOffset) {
case X_OFFSET_LEFT:
this.setX((int)(go.getLocation().getX() - this.getSize().width - 4));
break;
case X_OFFSET_MIDDLE:
this.setX(go.getX());
break;
case X_OFFSET_RIGHT:
this.setX((int)(go.getLocation().getX() + go.getSize().width + 4));
break;
default:
break;
}
switch (yOffset) {
case Y_OFFSET_OVER:
this.setY((int)(go.getLocation().getY() - this.getSize().height - 4));
break;
case Y_OFFSET_MIDDLE:
this.setY(go.getY());
break;
case Y_OFFSET_BELOW:
this.setY((int)(go.getLocation().getY() + go.getSize().height + 4));
break;
default:
break;
}
} |
85f64381-7551-4a17-880a-7b894ae1e009 | 2 | public bloque crearBloque(){
BloqueComodin nuevoBloqueComodin = new BloqueComodin();
Random generador = new Random();
int r = generador.nextInt(2);
if(r == 0){
nuevoBloqueComodin.imagen = new ImageIcon(getClass().getResource("c1.jpg"));
nuevoBloqueComodin.tipoBloque="c1";
}
else if(r == 1){
nuevoBloqueComodin.imagen = new ImageIcon(getClass().getResource("c2.jpg"));
nuevoBloqueComodin.tipoBloque="c2";
}
nuevoBloqueComodin.boton = new JButton(nuevoBloqueComodin.imagen);
return (bloque) (nuevoBloqueComodin);
} |
e116be33-820c-41d6-ad59-af9ac33c331f | 8 | public static String readLineFromTokenizerBuffer(InputStream stream) {
{ OutputStringStream buffer = OutputStringStream.newOutputStringStream();
String line = null;
char ch = Stella.NULL_CHARACTER;
char ch2 = Stella.NULL_CHARACTER;
boolean eofP = false;
char newline = Stella.EOL_STRING.charAt(0);
loop000 : for (;;) {
{ Object [] caller_MV_returnarray = new Object[1];
ch = InputStream.readCharacterFromTokenizerBuffer(stream, caller_MV_returnarray);
eofP = ((boolean)(((BooleanWrapper)(caller_MV_returnarray[0])).wrapperValue));
}
if (eofP) {
line = buffer.theStringReader();
if (line.length() == 0) {
line = null;
}
else {
eofP = false;
}
break loop000;
}
if (ch == newline) {
if (Stella.EOL_STRING.length() == 2) {
{ Object [] caller_MV_returnarray = new Object[1];
ch2 = InputStream.readCharacterFromTokenizerBuffer(stream, caller_MV_returnarray);
eofP = ((boolean)(((BooleanWrapper)(caller_MV_returnarray[0])).wrapperValue));
}
if (eofP) {
line = buffer.theStringReader();
if (line.length() == 0) {
line = null;
}
else {
eofP = false;
}
break loop000;
}
if (!(ch2 == Stella.EOL_STRING.charAt(1))) {
buffer.nativeStream.print(ch + ch2);
continue loop000;
}
}
line = buffer.theStringReader();
break loop000;
}
buffer.nativeStream.print(ch);
}
return (line);
}
} |
c589fc56-e0c7-40a2-ba8d-7c05aa9eb6d4 | 8 | public static void main(String[] args) {
int nGramLength = 4;
for (int i = 0; i < args.length; i += 2) {
if (args[i].equals("n-gram")) {
nGramLength = Integer.parseInt(args[i + 1]);
}
}
for(int n = 3; n <= 7; n++) {
System.gc();
PunctuationPredicter pI = new PunctuationPredicter(n, "ppCorpus.txt");
for (int i = 0; i < 1; i++) {
String evaluate = "testSentences" + i +".txt";
String answers = "testSentencesAnswers" + i +"ngram"+n+ ".txt";
String correct = "testSentencesCorrection" + i +".txt";
try {
//BufferedReader br = new BufferedReader(new FileReader(evaluate));
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(evaluate), "UTF-16BE"));
BufferedReader correction = new BufferedReader(new InputStreamReader(new FileInputStream(correct), "UTF-16BE"));
//PrintWriter pw = new PrintWriter(answers);
OutputStreamWriter pw = new OutputStreamWriter(new FileOutputStream(answers), "UTF-16BE");
PrintWriter printOOV = new PrintWriter("testSentencesAnswers" + i + "OOV.txt");
int counter = Integer.MAX_VALUE;
//int counter = 3;
int counting = 1;
while ((counter > 0) && br.ready()) { //Risky?
//while(false) {
long time = System.currentTimeMillis();
String fix = br.readLine();
//System.err.println("---------------------");
//System.err.println(fix);
fix = fix.trim().replaceAll("( )+", " ");
//if(fix.split(" ").length<9) {
if (true) {
//System.err.println("-----------------------------------------------------");
//System.err.println(fix);
//System.out.println(pI.predictPunctuation(fix));
String answer = pI.predictPunctuation(fix);
pI.nGramWrapper.updateOOV(fix.split(" "));
pI.nGramWrapper.updateCoverage(fix.split(" "));
pw.write(answer);
pw.write('\n');
//String correctional = correction.readLine().trim().replaceAll("( )+", " ").replaceAll("(.PERIOD )+", ".PERIOD ");
//System.err.println(correctional + "\t" + pI.getCostOfString(correctional));
//System.err.println(answer + "\t" + pI.getCostOfString(answer));
//System.err.println(answer);
time = System.currentTimeMillis() - time;
time = time / 1000;
System.err.println(counting);
counting++;
//System.err.println("Spent " + time + " s calculating sentence.");
}
counter--;
}
System.out.println(pI.nGramWrapper.getOOV());
System.out.println("In vocabulary = " + pI.nGramWrapper.numberOfTokensInVocabulary);
System.out.println("Out of vocabulary = " + pI.nGramWrapper.numberOfTokensOutOfVocabulary);
System.out.println("Coverage = " + pI.nGramWrapper.getCoverage());
printOOV.println("In vocabulary = " + pI.nGramWrapper.numberOfTokensInVocabulary);
printOOV.println("Out of vocabulary = " + pI.nGramWrapper.numberOfTokensOutOfVocabulary);
//printOOV.println("Coverage = "+pI.nGramWrapper.getCoverage());
printOOV.println(pI.nGramWrapper.getOOV());
pI.nGramWrapper.resetOOV();
pI.nGramWrapper.resetCoverage();
br.close();
pw.close();
printOOV.close();
/*
br = new BufferedReader(new FileReader("testdata.txt"));
while(br.ready()) {
String input = br.readLine();
System.err.println(input+"\t"+pI.getCostOfString(input));
}
*/
} catch (IOException e) {
e.printStackTrace();
}
}
}
//System.out.println("Ready for prediction");
//pI.handleInput(nGramLength);
} |
89f19463-f08b-4f4d-8e1c-ff802793e8d8 | 0 | public King (boolean color){
super(color);
} |
8c92bafe-e7e0-47ea-9829-e20f44499743 | 9 | private void selectComponent(int code)
{
if (code == SELECT_DOWN) buttonSelectedIdx++;
else if (code == SELECT_UP) buttonSelectedIdx--;
if (buttonSelectedIdx < 0) buttonSelectedIdx = BUTTON_COUNT - 1;
else if (buttonSelectedIdx >= BUTTON_COUNT) buttonSelectedIdx = 0;
edit_userName.setVisible(false);
label_userName.setVisible(true);
GUI_util.setSelected(label_user, false);
GUI_util.setSelected(button_start, false);
GUI_util.setSelected(button_oddball, false);
GUI_util.setSelected(button_bandit, false);
GUI_util.setSelected(button_exit, false);
if (buttonSelectedIdx == BUTTON_USER_IDX)
{
GUI_util.setSelected(label_user, true);
label_userName.setVisible(false);
edit_userName.setVisible(true);
edit_userName.requestFocus();
}
else
{
this.requestFocus();
if (buttonSelectedIdx == BUTTON_START_IDX) GUI_util.setSelected(button_start, true);
else if (buttonSelectedIdx == BUTTON_ODDBALL_IDX) GUI_util.setSelected(button_oddball, true);
else if (buttonSelectedIdx == BUTTON_BANDIT_IDX) GUI_util.setSelected(button_bandit, true);
else if (buttonSelectedIdx == BUTTON_EXIT_IDX) GUI_util.setSelected(button_exit, true);
}
} |
abbd0a1e-400e-4187-818d-ceb7299af1e0 | 6 | public LibraryBean[] showByData(LanguageTypeEnum language, String tags) {
String[] tagsArray = DataController.parseTags(tags);
SearchDAO searchDAO = new SearchDAO(Connector.getInstance());
if (language != LanguageTypeEnum.UNDEFINED && tags.length() > 0) {
return searchDAO.showByLanguageAndTags(language, tagsArray);
} else if (language != LanguageTypeEnum.UNDEFINED && tags.length() == 0) {
return searchDAO.showByLanguage(language);
} else if (language == LanguageTypeEnum.UNDEFINED && tags.length() > 0) {
return searchDAO.showByTags(tagsArray);
} else
return searchDAO.showAllLibrary();
} |
1ac09de8-019f-4da8-81a5-8a21d58d660d | 9 | public static int compareSkylinePosition(int[] attributes1, int[] attributes2) {
boolean inf = true, sup = true;
int ret = 0;
for (int i = 0; i < attributes1.length; i++) {
if (attributes1[i] < attributes2[i]) {
sup = false;
} else if (attributes1[i] > attributes2[i]) {
inf = false;
}
}
if ((sup && inf) || (!sup && !inf))
ret = 0;
else if (sup)
ret = 1;
else if (inf)
ret = -1;
return ret;
} |
1a55a2a7-af2f-4f8b-abbd-9b8ffd999c2f | 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(RoadDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(RoadDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(RoadDetails.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(RoadDetails.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 RoadDetails().setVisible(true);
}
});
} |
2a1e9bbf-bbad-41b4-bdf3-91f981294371 | 1 | public boolean isStringInContext(String pattern,String context, int foundPatternAt) {
int patternSize = pattern.length();
String compareString = "";
while(patternSize > 0) { compareString += context.charAt(foundPatternAt); foundPatternAt++; patternSize--;}
return this.compareTwoStrings(pattern, compareString);
} |
264a610f-091f-4092-8dbf-d025bcda4088 | 2 | @EventHandler(priority = EventPriority.NORMAL)
public void onPlayerJoin(PlayerJoinEvent event) {
if (Attunements.defaultAttunement != null) {
String playerName = event.getPlayer().getName();
String worldName = plugin.getServer().getWorlds().get(0).getName();
if ((new File(worldName + "/players/" + playerName + ".dat")).exists() == false) {
Attunements.put(playerName, new Attunement(playerName, Attunements.defaultAttunement));
plugin.debug(playerName + " is new to the server, setting their default attunement location.");
}
}
} |
02867c96-44f8-4076-8ab5-431a8ccc37ff | 2 | @Override
public boolean isValid() {
boolean isValid = true;
for(Part part : parts)
if (!part.isValid())
isValid = false;
return isValid;
} |
95c02345-e74f-4641-a99e-c2d364b2c4dc | 6 | public boolean getBoolean(int index) throws JSONException {
Object object = this.get(index);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new JSONException("JSONArray[" + index + "] is not a boolean.");
} |
9ddcb382-0311-424d-8b4f-9bfde4dd4d1b | 5 | public void insert(Node newNode){
if(root==null){
root=newNode;
root.key=root.hashcode(500); //set root key as 500 by call method
}
else { // if not root
Node curnt=root;
Node parnt;
while (true) { //travese trough the tree to find correct place and joint to tree
parnt=curnt;
if(newNode.getKey()<curnt.getKey()){
curnt=curnt.leftChld;
if(curnt== null){
parnt.leftChld=newNode;
return;
}
}else{
curnt=curnt.rightChld;
if(curnt== null){
parnt.rightChld=newNode;
return;
}
}
}
}
} |
9cd53e21-a737-47f0-b630-fa35d12bf970 | 9 | @Override
public void processStimulus(Enumeration criteria) {
WakeupCriterion wakeup;
AWTEvent[] events;
MouseEvent evt;
while (criteria.hasMoreElements()) {
wakeup = (WakeupCriterion) criteria.nextElement();
if (wakeup instanceof WakeupOnAWTEvent) {
events = ((WakeupOnAWTEvent)wakeup).getAWTEvent();
if (events.length > 0) {
evt = (MouseEvent) events[events.length-1];
doProcess(evt);
}
}
else if (wakeup instanceof WakeupOnBehaviorPost) {
while (true) {
synchronized (mouseq) {
if (mouseq.isEmpty()) break;
evt = (MouseEvent)mouseq.remove(0);
// consolidate MOUSE_WHEEL events
while((evt.getID() == MouseEvent.MOUSE_WHEEL) &&
!mouseq.isEmpty() &&
(((MouseEvent)mouseq.get(0)).getID() ==
MouseEvent.MOUSE_WHEEL)) {
evt = (MouseEvent)mouseq.remove(0);
}
}
doProcess(evt);
}
}
}
wakeupOn(mouseCriterion);
} |
86cf5045-4eaf-4a68-9b73-801da14c9b5e | 1 | private void setLongitude(double longitude) {
double lng = LatLngTool.normalizeLongitude(longitude);
if (Double.isNaN(lng))
throw new IllegalArgumentException("Invalid longitude given.");
this.longitude = lng;
this.longitudeInternal = doubleToLong(lng);
} |
7e5132ee-0810-4f85-b7a0-17306bc38cc2 | 4 | public void updateLists(ArrayList newList, String player)
{
if(player.equalsIgnoreCase("player"))
{
playerCards.subList(0, playerCards.size()).clear();
playerCards.addAll(newList);
}
else if(player.equalsIgnoreCase("dealer"))
{
dealerCards.addAll(newList);
}
else if(player.equalsIgnoreCase("dealero"))
{
dealerOriginalCards.addAll(newList);
}
else if(player.equalsIgnoreCase("playero"))
{
playerOriginalCards.addAll(newList);
}
} |
4d64c659-907d-4596-b368-88d3f083fcf5 | 1 | public void resetStream() throws IOException {
if (this.audioInputStream != null) {
this.audioInputStream.reset();
}
} |
f39fe1ed-b040-4cb6-9586-a2030e832153 | 5 | public Wave24(){
super();
MobBuilder m = super.mobBuilder;
for(int i = 0; i < 700; i++){
if(i % 5 == 0)
add(m.buildMob(MobID.ODDISH));
else if(i % 4 == 0)
add(m.buildMob(MobID.BELLSPROUT));
else if(i % 3 == 0)
add(m.buildMob(MobID.MEOWTH));
else if(i % 2 == 0)
add(m.buildMob(MobID.MANKEY));
else
add(m.buildMob(MobID.VULPIX));
}
} |
5d038a1c-f9c6-4e97-96cd-97eb1fcb840b | 4 | private boolean _jspx_meth_c_when_0(javax.servlet.jsp.tagext.JspTag _jspx_th_c_choose_0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// c:when
org.apache.taglibs.standard.tag.rt.core.WhenTag _jspx_th_c_when_0 = (org.apache.taglibs.standard.tag.rt.core.WhenTag) _jspx_tagPool_c_when_test.get(org.apache.taglibs.standard.tag.rt.core.WhenTag.class);
_jspx_th_c_when_0.setPageContext(_jspx_page_context);
_jspx_th_c_when_0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_c_choose_0);
_jspx_th_c_when_0.setTest(((java.lang.Boolean) org.apache.jasper.runtime.PageContextImpl.evaluateExpression("${db.isConnectedOK}", java.lang.Boolean.class, (PageContext)_jspx_page_context, null)).booleanValue());
int _jspx_eval_c_when_0 = _jspx_th_c_when_0.doStartTag();
if (_jspx_eval_c_when_0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write('成');
out.write('功');
int evalDoAfterBody = _jspx_th_c_when_0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_c_when_0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return true;
}
_jspx_tagPool_c_when_test.reuse(_jspx_th_c_when_0);
return false;
} |
8fdcc0ca-a62e-4cf1-8264-395a3df4cf9c | 9 | private Image findGameElementImage(Element element) {
if (element instanceof Wall) {
return wall;
} else if (element instanceof IdentityDisc) {
IdentityDisc disc = (IdentityDisc) element;
if (disc.charged)
return chargedIdentityDisc;
else
return identitydisc;
} else if (element instanceof LightGrenade) {
if (!((LightGrenade) element).isActive()
&& !((LightGrenade) element).isExploded())
return lightgrenade;
} else if (element instanceof Player) {
if (objectTron.getPlayerNumber((Player) element) == 0) {
return playerRed;
} else {
return playerBlue;
}
} else if (element instanceof Teleporter) {
return teleporter;
}
return null;
} |
2beaf042-63ce-440f-98a4-f4361464f0ba | 1 | private void deobfuscateAndDecompile(String... args) throws IOException {
if(!PERFORM_DEOBFUSCATION_AND_DECOMPILE)
return;
Renamer.main(args);
Runtime.getRuntime().exec("cmd /c start decompile.bat");
} |
b5e6d369-cd5c-45db-a884-8a5e35c79145 | 9 | public static final boolean cyclicEqual(int[] arr, int[] brr) {
final int len = arr.length;
if (len != brr.length) return false;
if (len == 0) return true;
if (len == 1) return arr[0] == brr[0];
int bstart;
int bincr;
for (bstart = 0; bstart < len; ++bstart) if (brr[bstart] == arr[0]) break;
if (bstart >= len) return false;
bincr = (brr[(bstart + 1) % len] == arr[1] ? 1 : -1);
for (int i = 0; i < len; bstart = (bstart + bincr + len) % len, ++i) {
if (arr[i] != brr[bstart]) return false;
}
return true;
} |
2c79addd-99de-4539-bf25-0879a9b39671 | 8 | public void calculateAllMarignals(){
double[] x = new double[_m];
double[] h = new double[_n];
int[] nh1 = new int[_n]; // counts h==1
for (int j=0; j<_n; j++)
nh1[j] = 0;
// initialize first x
for (int i = 0; i<_m; i++)
x[i] = (i+1)%2==0 ? 1 : 0;
for (int t=0; t<this._num_samples; t++){
// generate h, based on x
for (int j=0; j<this._n; j++){
double[] w_j = this.W_j(j);
double xw_j = this.dotProd(x, w_j);
double dj = this._parameters.hiddenBias(j+1);
double phj1 = sigma(xw_j+dj);
h[j] = this.randVal(phj1);
if(h[j]==1)
nh1[j]++;
}
// generate x, based on h
for (int i=0; i<this._m; i++){
double[] wi_ = this.Wi_(i);
double hwi_ = this.dotProd(h, wi_);
double bi = this._parameters.visibleBias(i+1);
double pxi1 = sigma(hwi_+bi);
x[i] = this.randVal(pxi1);
}
}
for (int j=0; j<_n; j++)
this._ph[j] = (nh1[j]+0.0) / this._num_samples;
} |
1d0db553-1fef-40c5-8b12-5d7d4c75c556 | 2 | public void setAdditionalFields(GameFont gameFont, Map<String, String> data) {
if (data.containsKey("charSpacing")) {
gameFont.setCharSpacing(Integer.parseInt(data.get("charSpacing")));
}
if (data.containsKey("verticalSpacing")) {
gameFont.setVerticalSpacing(Integer.parseInt(data.get("verticalSpacing")));
}
} |
8ed0bd43-c3a7-4e25-ae1f-cdc776b5a151 | 1 | @Override
public Double call() throws Exception {
double result = 0.0;
int arg = 0;
for (arg = startValue; arg <= endValue; arg += step) {
result += Math.sin(arg);
}
return result;
} |
9145a744-13f0-4e54-92b1-926893ad372d | 2 | @Override
public boolean equals(Object v) {
boolean retVal = false;
if (v instanceof Conditional){
Conditional a = (Conditional) v;
retVal = a.fact == this.fact && a.NotFlag == this.NotFlag;
}
return retVal;
} |
d65d4862-a674-418b-ada5-e04667275cda | 8 | public static BufferedImage rotatePicture(BufferedImage originalImage, int rotationDegree) {
Logger.getLogger(ImageReader.class.getName()).entering(ImageReader.class.getName(), "rotatePicture", new Object[] {originalImage, rotationDegree});
if (originalImage != null) {
BufferedImage rotatedBufferedImage;
if(rotationDegree == 180) {
rotatedBufferedImage = new BufferedImage(originalImage.getWidth(), originalImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
} else if (rotationDegree == 90 || rotationDegree == 270) {
rotatedBufferedImage = new BufferedImage(originalImage.getHeight(), originalImage.getWidth(), BufferedImage.TYPE_INT_ARGB);
} else if (rotationDegree == 0) {
return originalImage;
} else {
Logger.getLogger(ImageReader.class.getName()).log(Level.WARNING, "The rotation wanted have not been found", rotationDegree);
Logger.getLogger(ImageReader.class.getName()).exiting(ImageReader.class.getName(), "rotatePicture", null);
return null;
}
Graphics2D g2d = rotatedBufferedImage.createGraphics();
g2d.rotate(Math.toRadians(rotationDegree), 0, 0);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
if (rotationDegree == 180) {
g2d.drawImage(originalImage, -originalImage.getWidth(), -originalImage.getHeight(), originalImage.getWidth(), originalImage.getHeight(), null);
}
else if (rotationDegree == 90) {
g2d.drawImage(originalImage, 0, -originalImage.getHeight(), originalImage.getWidth(), originalImage.getHeight(), null);
}
else if (rotationDegree == 270) {
g2d.drawImage(originalImage, -originalImage.getWidth(), 0, originalImage.getWidth(), originalImage.getHeight(), null);
}
g2d.dispose();
originalImage.flush();
Logger.getLogger(ImageReader.class.getName()).exiting(ImageReader.class.getName(), "rotatePicture", rotatedBufferedImage);
return rotatedBufferedImage;
}
Logger.getLogger(ImageReader.class.getName()).exiting(ImageReader.class.getName(), "rotatePicture", null);
return null;
} |
0ab6f1e2-dff2-439c-99f5-3af6b4b9d03f | 3 | public boolean canPlaceBlockAt(World var1, int var2, int var3, int var4) {
return var1.isBlockNormalCube(var2 - 1, var3, var4)?true:(var1.isBlockNormalCube(var2 + 1, var3, var4)?true:(var1.isBlockNormalCube(var2, var3, var4 - 1)?true:var1.isBlockNormalCube(var2, var3, var4 + 1)));
} |
f363cde6-094c-4f84-b3ab-426bab37f1a2 | 4 | public synchronized void averageImages() {
if (history.size() < 1) {
textArea.append("No images!\n");
return;
}
int[] smallest = smallestIndices();
int xSize = smallest[0];
int ySize = smallest[1];
int size = history.size();
BufferedImage result = new BufferedImage(xSize, ySize,
BufferedImage.TYPE_INT_RGB);
/*
* Skips extra pixels (when an image smaller than others) rather than
* averaging those...hrm..
*/
List<Integer> printed = new ArrayList<Integer>();
for (int i = 0; i < xSize; i++) {
printProgress(i, xSize, printed);
for (int j = 0; j < ySize; j++) {
int red = 0;
int blue = 0;
int green = 0;
for (BufferedImage b : history) {
Color pixel = new Color(b.getRGB(i, j));
red += pixel.getRed();
blue += pixel.getBlue();
green += pixel.getGreen();
}
Color newColour = new Color(red / size, blue / size, green
/ size);
result.setRGB(i, j, newColour.getRGB());
}
}
textArea.append(100 + " % done\n");
paintImage(result);
} |
24522b2f-6954-4572-9f90-585f9290fa4d | 4 | public HashMap<Integer, Double> constructLMSpVct(String[] tokens){
int lmIndex = 0;
double lmValue = 0;
HashMap<Integer, Double> lmVct = new HashMap<Integer, Double>();//Collect the index and counts of projected features.
// We assume we always have the features loaded beforehand.
for(int i = 0; i < tokens.length; i++){
if (isLegit(tokens[i])){
if(m_lmFeatureNameIndex.containsKey(tokens[i])){
lmIndex = m_lmFeatureNameIndex.get(tokens[i]);
if(lmVct.containsKey(lmIndex)){
lmValue = lmVct.get(lmIndex) + 1;
lmVct.put(lmIndex, lmValue);
} else
lmVct.put(lmIndex, 1.0);
}
}
}
return lmVct;
} |
a5cfc5f0-e3b4-46d7-8f7f-2bfa07842df4 | 8 | @Override
public final synchronized Class getIFunctionClassDefinition(final Object targetObject, final Method targetMethod ) throws JFKException{
try {
// check params
if( ClassLoaderStatus.BUSY.equals( status ) )
throw new JFKException("The classloader is busy!");
if( (targetObject == null) || (targetMethod == null) )
throw new IllegalArgumentException("Cannot proceed without the method and the target object");
if( (! targetMethod.isAnnotationPresent( Function.class )) && (! targetMethod.isAnnotationPresent(Connect.class)) )
throw new CannotBindFunctionException("The specified method is not a function/connect annotated one!");
// get the annotation name and parameters
if( targetMethod.isAnnotationPresent( Function.class) ){
final Function functionAnnotation = targetMethod.getAnnotation( Function.class );
functionNameFromAnnotation = functionAnnotation.name();
}
else if( targetMethod.isAnnotationPresent( Connect.class ) ){
final Connect connectAnnotation = targetMethod.getAnnotation( Connect.class );
functionNameFromAnnotation = connectAnnotation.name();
}
// set the parameters for the loader
currentMethod = targetMethod;
targetInstance = targetObject;
// define the class
return findClass( IFunction.class.getName() );
} catch (final ClassNotFoundException e) {
logger.error("Error defining the IFunction class", e);
throw new JFKException(e);
}
} |
9e13f272-024f-4c95-813f-748af014bf05 | 4 | public PlayerUi(final Player player, List<String> buttonLabels,
final PrintWriter printToServer, final BufferedReader inFromServer){
super();
this.player = player;
this.printToServer = printToServer;
this.setX(0);
this.setY(0);
int sceneR = randomColorVal();
int sceneG = randomColorVal();
int sceneB = randomColorVal();
color = Color.rgb(sceneR, sceneG, sceneB);
Color labelColor = Color.BLACK;
AnchorPane root = new AnchorPane();
pane = new Pane();
infoLabel = new Text("");
infoLabel.setLayoutX(20);
infoLabel.setLayoutY(10);
pane.getChildren().add(infoLabel);
card1Label = new Text(getCardDisplay(player.getFirstCard(),1));
pane.getChildren().add(card1Label);
card1Label.setFill(labelColor);
card1Label.setLayoutY(20+2 * COMP_VERT_SPACE/3);
card1RevealButton = new Button("Reveal Card 1");
card1RevealButton.setVisible(false);
card1RevealButton.setLayoutY(20);
card1RevealButton.setLayoutX(240);
card1RevealButton.setOnMouseClicked(new EventHandler<Event>(){
@Override
public void handle(Event arg0) {
player.getFirstCard().reveal();
printToServer.println(Responses.FirstCard);
updateFollowingCardReveal();
}
});
pane.getChildren().add(card1RevealButton);
card2Label = new Text(getCardDisplay(player.getSecondCard(),2));
pane.getChildren().add(card2Label);
card2Label.setLayoutY(20+4 * COMP_VERT_SPACE/3);
card2Label.setFill(labelColor);
card2RevealButton = new Button("Reveal Card 2");
card2RevealButton.setLayoutY(20+COMP_VERT_SPACE);
card2RevealButton.setLayoutX(240);
card2RevealButton.setOnMouseClicked(new EventHandler<Event>(){
@Override
public void handle(Event arg0) {
player.getSecondCard().reveal();
printToServer.println(Responses.SecondCard);
updateFollowingCardReveal();
}
});
card2RevealButton.setVisible(false);
pane.getChildren().add(card2RevealButton);
moneyLabel = new Text(getCoinDisplay(player));
pane.getChildren().add(moneyLabel );
moneyLabel.setLayoutY(20+COMP_VERT_SPACE * 2);
moneyLabel.setFill(labelColor);
int buttonNumber = 1;
int currentYPos = 0;
for(final String actionLabel: buttonLabels){
Button actionButton = new Button();
actionButton.setText(actionLabel);
actionButton.setOnMouseClicked(new EventHandler<Event>(){
@Override
public void handle(Event arg0) {
printToServer.println(actionLabel);
disableAllActions();
}
});
actionButton.setLayoutX(0);
currentYPos = 20+(buttonNumber + 2) * COMP_VERT_SPACE;
actionButton.setLayoutY(currentYPos);
buttonNumber++;
actionButton.setDisable(true);
pane.getChildren().add(actionButton);
allActionButtons.add(actionButton);
}
root.getChildren().add(pane);
scene = new Scene(root, 500, 500);
setTitle(player.toString());
setResizable(true);
scene.setFill(color);
setScene(scene);
this.show();
winnerText = new Text("YOU WIN!");
winnerText.setFont(Font.font("Verdana", 20));
winnerText.setLayoutX(5);
winnerText.setLayoutY(45);
winnerText.setFill(Color.WHITE);
winnerText.setVisible(false); //hide until end of game
pane.getChildren().add(winnerText );
loserText = new Text("YOU LOSE! :(");
loserText.setFont(Font.font("Verdana", 20));
loserText.setLayoutX(5);
loserText.setLayoutY(45);
loserText.setFill(Color.WHITE);
loserText.setVisible(false); //hide until end of game
pane.getChildren().add(loserText);
gameHistoryPane = new ScrollPane();
gameHistoryPane.setLayoutX(10);
gameHistoryPane.setLayoutY(60);
gameHistoryPane.setMinSize(400,400);
gameHistoryPane.setVisible(false);
gameHistoryText = new Text("Game history will go here");
gameHistoryText.setVisible(false);
gameHistoryPane.setContent(gameHistoryText);
pane.getChildren().add(gameHistoryPane);
cannotPlayAgainText = new Text("Other players declined, choose: ");
cannotPlayAgainText.setLayoutX(5);
cannotPlayAgainText.setLayoutY(15);
cannotPlayAgainText.setVisible(false);
pane.getChildren().add(cannotPlayAgainText);
playAgainButton = new Button("Play again with same players");
playAgainButton.setLayoutX(5);
playAgainButton.setVisible(false);
playAgainButton.setOnMouseClicked(new EventHandler<Event>(){
@Override
public void handle(Event arg0) {
playAgainButton.setDisable(true);
printToServer.println(Responses.RESTART);
try {
String ready = inFromServer.readLine();
if(ready.equals(Responses.READY.toString())){
CoupClient.startNewGame(printToServer, inFromServer);
CoupApplicationClientSide.startNewGame();
}else if(ready.equals(Responses.NOT_READY.toString())){
updateToDisplayGameDone();
}else{
throw new RuntimeException("Invalid server response: " + ready);
}
} catch (IOException e) {
throw new RuntimeException("No response from server",e);
}
}
});
pane.getChildren().add(playAgainButton);
quitButton = new Button("Quit");
quitButton.setVisible(false);
quitButton.setLayoutX(200);
quitButton.setOnMouseClicked(new EventHandler<Event>(){
@Override
public void handle(Event arg0) {
printToServer.println(Responses.QUIT);
System.exit(1);
}
});
pane.getChildren().add(quitButton);
findNewGameButton = new Button("Find a new game");
findNewGameButton.setVisible(false);
findNewGameButton.setLayoutX(260);
findNewGameButton.setOnMouseClicked(new EventHandler<Event>(){
@Override
public void handle(Event arg0) {
printToServer.println(Responses.QUIT);
CoupClient.establishNewConnection(player.toString());
}
});
pane.getChildren().add(findNewGameButton);
cardChooserUI = new CardChooserUI(color, printToServer, pane);
cardChooserUI.setVisible(false);
root.getChildren().add(cardChooserUI);
root.getChildren().add(buildBluffCallingPane(currentYPos + 20));
bluffCallingPane.setVisible(false);
root.getChildren().add(buildBlockingPane(currentYPos + 20));
blockingPane.setVisible(false);
} |
d59dd44b-1941-4b28-9918-3a3ca3ef7100 | 7 | public void setLines(){
//w, h es el punto de origen
CoordenadasCasa = new int [aristas*2][3];
int fila = 0;
while(vertices.size() > 1 ){
double vf = vertices.pop();
double vi = vertices.pop();
// System.out.println("Va de "+vi+" a "+vf);
String [] p0 = puntos[(int)vi].split(",");
int xi = Integer.parseInt(p0[0]);
int yi = Integer.parseInt(p0[1]);
int zi = Integer.parseInt(p0[2]);
String [] p1 = puntos[(int)vf].split(",");
int xf = Integer.parseInt(p1[0]);
int yf = Integer.parseInt(p1[1]);
int zf = Integer.parseInt(p1[2]);
if(zi == -300){
if(xi > 0){xi -=15;}else{xi +=15;}
if(yi > 0){yi -=15;}else{yi +=15;}
}
if(zf == -300){
if(xf > 0){xf -=15;}else{xf +=15;}
if(yf > 0){yf -=15;}else{yf +=15;}
}
CoordenadasCasa[fila][0] = xi;
CoordenadasCasa[fila][1] = yi;
CoordenadasCasa[fila][2] = zi;
CoordenadasCasa[fila+1][0] = xf;
CoordenadasCasa[fila+1][1] = yf;
CoordenadasCasa[fila+1][2] = zf;
fila +=2;
//System.out.println("Linea de ("+xi+", "+yi+") a ("+xf+", "+yf+") ");
}
/*System.out.println("FILA Columna");
for(int f = 0; f < CoordenadasCasa.length-1; f++){
System.out.println("["+CoordenadasCasa[f][0]+", "+ CoordenadasCasa[f][1]+"]["+CoordenadasCasa[f][3]+", "+ CoordenadasCasa[f][4]+"]");
}
*/
} |
6b4ee87d-e70e-4ddd-99fe-72f9041dbb7c | 1 | public boolean wasReleased() {
return wasDown && !isDown;
} |
e044284e-0a19-4bf4-a796-3e02db733496 | 5 | public String insertarEstudiante(String codigo, String nombre, String sexo, String programa) {
//<editor-fold defaultstate="collapsed" desc="insertarEstudiante()">
if (!nombre.isEmpty() && !codigo.isEmpty() && !sexo.equals(" ") && !programa.equals(" ")) {
Estudiante estudiante = new Estudiante();
estudiante.setCodigo(codigo);
estudiante.setNombre(nombre);
estudiante.setSexo(sexo.toCharArray()[0]);
estudiante.setPrograma(new DaoPrograma().consultarPrograma(programa.split(" -")[0]));
if (daoEstudiante.guardarEstudiante(estudiante) == -1) {
return "No es posible registrar el Estudiante:\n"
+ "(1) Verifique la conexion con la base de datos no tenga problemas.\n"
+ "(2) O que el Estudiante no se encuentre ya registrado";
}
System.out.println("Se insertó un nuevo Estudiante");
return "OK";
} else {
}
return "Es necesario ingresar la informacion de todos los campos";
//</editor-fold>
} |
b244ae1a-0170-41b7-98f5-552268b7ba06 | 8 | private void initButtons() {
filterButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
String targetClassName = searchField.getText();
if ( targetClassName.isEmpty() ) {
return;
}
root.removeAllChildren();
Map<DefaultMutableTreeNode, Set<DefaultMutableTreeNode>> filteredNodes = new HashMap<DefaultMutableTreeNode, Set<DefaultMutableTreeNode>>();
for ( Map.Entry<String, DefaultMutableTreeNode> mapEntry : nodes.entrySet() ) {
if ( mapEntry.getKey().contains(targetClassName) ) {
DefaultMutableTreeNode underRootNode = nodes.get(mapEntry.getKey().split("/")[0]);
Set<DefaultMutableTreeNode> nodesToExpand = filteredNodes.get(underRootNode);
if ( nodesToExpand == null ) {
nodesToExpand = new HashSet<DefaultMutableTreeNode>();
}
String[] classesNamesInPath = mapEntry.getKey().split("/");
DefaultMutableTreeNode targetNode = mapEntry.getValue();
for (int i = classesNamesInPath.length - 1; i > -1; i-- ) {
if ( targetNode.getUserObject().toString().contains(targetClassName) ) {
nodesToExpand.add(targetNode);
} else {
targetNode = (DefaultMutableTreeNode) targetNode.getParent();
}
}
filteredNodes.put(underRootNode, nodesToExpand);
}
}
for ( Map.Entry<DefaultMutableTreeNode, Set<DefaultMutableTreeNode>> filteredNode : filteredNodes.entrySet() ) {
root.add(filteredNode.getKey());
for ( DefaultMutableTreeNode nodeToExpand : filteredNode.getValue() ){
classesTree.expandPath(new TreePath(nodeToExpand.getPath()));
}
}
EventMgr.getMgr(mainMgr).dispatch(new FilterChangedEvent(targetClassName));
classesTree.updateUI();
}
});
releaseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
root.removeAllChildren();
addAllChildren(root, storage.getUnderRootNodes());//fill tree with all classes
EventMgr.getMgr(mainMgr).dispatch(new FilterChangedEvent(""));
classesTree.updateUI();
}
});
} |
d4763717-7ba6-45b4-a40e-e2bddd7c6cb4 | 3 | @Override
public void update()
{
if(Game.instance.input.escape.down)
Game.instance.stopThread();
int i = rand.nextInt(100);
if(i > 90)
{
boolean j = rand.nextBoolean();
if(j)
addParticle(0, 0);
}
super.update();
} |
5a0cc510-9462-417a-beb8-51e0aa81c2bd | 1 | void countDown() {
synchronized (lock) {
if (--count <= 0) {
lock.notify();
}
}
} |
b05d226e-820f-4bb8-bf4d-be22c7e3ed60 | 6 | @Override
public DocIdSet getDocIdSet(IndexReader reader) throws IOException {
final TermEnum enumerator = query.getEnum(reader);
try {
// if current term in enum is null, the enum is empty -> shortcut
if (enumerator.term() == null)
return DocIdSet.EMPTY_DOCIDSET;
// else fill into a OpenBitSet
final OpenBitSet bitSet = new OpenBitSet(reader.maxDoc());
final int[] docs = new int[32];
final int[] freqs = new int[32];
TermDocs termDocs = reader.termDocs();
try {
int termCount = 0;
do {
Term term = enumerator.term();
if (term == null)
break;
termCount++;
termDocs.seek(term);
while (true) {
final int count = termDocs.read(docs, freqs);
if (count != 0) {
for(int i=0;i<count;i++) {
bitSet.set(docs[i]);
}
} else {
break;
}
}
} while (enumerator.next());
query.incTotalNumberOfTerms(termCount);
} finally {
termDocs.close();
}
return bitSet;
} finally {
enumerator.close();
}
} |
39ed2185-2b8b-47ee-938f-e4583ccf2ed0 | 2 | public void rejeuPartie()
{
this.E = this.eDepart;
if (this.getCoupSuivant() < this.mesPositions.size())
{
for(int i = 0; i < this.getCoupSuivant(); i++)
{
this.E.deplacerPiece(this.E.getTableau()[this.mesPositions.elementAt(i).getI()][this.mesPositions.elementAt(i).getJ()], this.mesDestinations.elementAt(i));
// A chaque clic sur le bouton suivant
//do
//{
//}
//while(!this.getSuivant());
//this.setSuivant(false);
}
}
} |
a196e5a3-36db-4540-ba69-0f2fbae1023b | 7 | protected boolean[] incrementingEquality(AttrTypes attrTypes,
int classType) {
print("incremental training produces the same results"
+ " as batch training");
printAttributeSummary(attrTypes, classType);
print("...");
int numTrain = getNumInstances(), numTest = getNumInstances(),
numClasses = 2, missingLevel = 0;
boolean attributeMissing = false, classMissing = false;
boolean[] result = new boolean[2];
Instances train = null;
Estimator [] estimators = null;
boolean built = false;
int attrIndex = 0;
Vector test;
try {
train = makeTestDataset(42, numTrain, 1, attrTypes,
numClasses,
classType
);
// prepare training data set and test value list
test = makeTestValueList(24, numTest, train, attrIndex,
attrTypes.getSetType());
if (missingLevel > 0) {
addMissing(train, missingLevel, attributeMissing, classMissing, attrIndex);
}
estimators = Estimator.makeCopies(getEstimator(), 2);
estimators[0].addValues(train, attrIndex);
} catch (Exception ex) {
throw new Error("Error setting up for tests: " + ex.getMessage());
}
try {
for (int i = 0; i < train.numInstances(); i++) {
((IncrementalEstimator)estimators[1]).addValue(train.instance(i).value(attrIndex), 1.0);
}
built = true;
if (!estimators[0].equals(estimators[1])) {
println("no");
result[0] = false;
if (m_Debug) {
println("\n=== Full Report ===");
println("Results differ between batch and "
+ "incrementally built models.\n"
+ "Depending on the estimator, this may be OK");
println("Here are the results:\n");
println("batch built results\n" + estimators[0].toString());
println("incrementally built results\n" + estimators[1].toString());
println("Here are the datasets:\n");
println("=== Train Dataset ===\n"
+ train.toString() + "\n");
println("=== Test Dataset ===\n"
+ test.toString() + "\n\n");
}
}
else {
println("yes");
result[0] = true;
}
} catch (Exception ex) {
result[0] = false;
print("Problem during");
if (built)
print(" testing");
else
print(" training");
println(": " + ex.getMessage() + "\n");
}
return result;
} |
a151e868-58db-4459-a664-511bd8b5bb97 | 0 | public AngelHeadArmor() {
this.name = Constants.ANGEL_HEAD_ARMOR;
this.defenseScore = 11;
this.money = 350;
} |
555e68ed-5633-4996-94f4-ac8d4e50e9ea | 3 | private void unTouchAllChipsOfColor(int col){
for (int i=0; i<8; i++) {
for (int j=0; j<8; j++) {
if(board[i][j].returnColor() == col)
board[i][j].untouch();
}
}
} |
2dbfda18-9607-45a0-a37d-8409f8aa431b | 3 | @Test
public void RandomGrid() {
//Make two identical models but one parallel and one sequential
AbstractModel paraModel=DataSetLoader.getRandomGrid(100, 800, 40, new ModelParallel());
AbstractModel seqModel=DataSetLoader.getRandomGrid(100, 800, 40, new Model());
//Step through each model stepNumber
stepModel(paraModel);
stepModel(seqModel);
//An error check that makes sure there models passed in have some particles
if(paraModel.p.size() == 0 || seqModel.p.size() == 0)
fail("Error the model had nothing in it");
//success or fail check
if(!checkModels(paraModel.p , seqModel.p)){
fail("The particles were not equal between the two models");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.