method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
51f4d040-53b7-4eb6-bf30-2f9aa5501657
| 6
|
public static void
stringExperiment(PrintWriter pen, SortedList<String> slist)
{
VerboseSortedList<String> strings =
new VerboseSortedList<String>(slist, pen, "strings");
// Add a bunch of strings
heading(pen, "Adding first");
String[] first =
new String[] { "twas", "brillig", "and", "the", "slithy", "toves",
"did", "gyre", "and", "gimble", "in", "the", "wabe" };
for (String str : first)
strings.add(str);
// Look at the resulting list
heading(pen, "Dumping contents");
strings.dump();
// Iterate through the list once.
heading(pen, "Iterating");
for (String str : strings)
;
// Remove some of the elements
heading(pen, "Removing");
for (int i = 0; i < first.length; i += 2)
strings.remove(first[i]);
// Look at the resulting list
heading(pen, "Dumping contents");
strings.dump();
// Iterate through the list once.
heading(pen, "Iterating again");
for (String str : strings)
;
// Add a few more strings
String[] second =
new String[] { "all", "mimsy", "were", "the", "borogoves" };
heading(pen, "Adding additional strings");
for (String str : second)
strings.add(str);
// Look at the resulting list
heading(pen, "Dumping contents");
strings.dump();
// And look up elements by index
heading(pen, "Iterating by index");
int len = slist.length();
for (int i = 1; i < len; i+= 3)
strings.get(i);
} // stringExperiment
|
47cab92a-68ef-4866-a529-db76780658b1
| 7
|
public void writeTermsToFile(String strNumber,
Hashtable<String, Double> oTermVsTFIDF) throws IOException {
String strKey = null;
Double maxValue = Double.MIN_VALUE;
String strTerms = "";
int len = oTermVsTFIDF.size() < 5 ? oTermVsTFIDF.size() : 5;
for (int i = 0; i < len; ++i) {
for (Map.Entry<String, Double> entry : oTermVsTFIDF.entrySet()) {
if (entry.getKey().length() > 2
&& entry.getValue() > maxValue
&& !stopwordsMap.containsKey(entry.getKey()
.toLowerCase())
&& entry.getKey().matches("[a-zA-Z]+")) {
maxValue = entry.getValue();
strKey = entry.getKey();
}
}
/*
for (int i = 0; i < len; ++i) {
for (Map.Entry<String, Double> entry : oTermVsTFIDF.entrySet()) {
if (entry.getKey().length() > 2
&& entry.getValue() > maxValue
&& !stopwordsMap.containsKey(entry.getKey()
.toLowerCase())
&& entry.getKey().matches("[a-zA-Z]+")) {
maxValue = entry.getValue();
strKey = entry.getKey();
}
}
*/
strTerms = strTerms + " " + strKey;
oTermVsTFIDF.remove(strKey);
strKey = null;
maxValue = Double.MIN_VALUE;
}
oBufferedWriter.write(strNumber + " " + strTerms.trim() + "\n");
System.out.println(strTerms);
}
|
7361af99-feed-4c3a-b96e-28e650839431
| 7
|
private static String stringForJSON(String input) {
if (input == null || input.isEmpty()) return "";
final int len = input.length();
final StringBuilder result = new StringBuilder(len + len / 4);
final StringCharacterIterator iterator = new StringCharacterIterator(input);
char ch = iterator.current();
while (ch != CharacterIterator.DONE) {
if (ch == '\n') {
result.append("\\n");
} else if (ch == '\r') {
result.append("\\r");
} else if (ch == '\'') {
result.append("\\\'");
} else if (ch == '"') {
result.append("\\\"");
} else {
result.append(ch);
}
ch = iterator.next();
}
return result.toString();
}
|
c86d6ccc-83e9-4d1c-b7b2-469591e172f7
| 5
|
public void update(long currentTime) {
if (isFinished || target == null) {
return;
}
if (!isStarted) {
startTracking(currentTime);
return;
}
int dt = (int)(currentTime - lastTime);
lastTime += dt;
Point nextLocation;
if (tempPath != null) {
nextLocation = tempPath.getNextLocation(component.getLocationXC(), component.getLocationYC(), target.getLocationXC(), target.getLocationYC());
}
else {
nextLocation = path.getNextLocation(component.getLocationXC(), component.getLocationYC(), target.getLocationXC(), target.getLocationYC());
}
if (nextLocation == null) {
endTracking();
}
else {
component.setLocationC(nextLocation.x, nextLocation.y);
}
}
|
c5d672d2-0855-4d17-a637-cb13a4047eca
| 5
|
private void jMenuItem1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem1MousePressed
try {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
JFrame mainFrame = fightermaker.getApplication().getMainFrame();
//Load XML file
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("Choose you character");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
chooser.showOpenDialog(mainFrame);
File selFile = chooser.getSelectedFile();
directory_path = selFile.getPath();
//Parse XML file
main_doc = docBuilder.parse (new File(directory_path+"/main.xml"));
sfx_doc = docBuilder.parse (new File(directory_path+"/sfx.xml"));
hitboxes_doc = docBuilder.parse (new File(directory_path+"/hitboxes.xml"));
sprites_doc = docBuilder.parse (new File(directory_path+"/sprites.xml"));
// normalize text representation
main_doc.getDocumentElement ().normalize ();
listOfMoves_main_file = main_doc.getElementsByTagName("Move");
DefaultListModel model = new DefaultListModel();
for(int s=0; s<listOfMoves_main_file.getLength() ; s++)
{
model.add(s, ((Element)listOfMoves_main_file.item(s)).getAttribute("name"));
}
list_moves.setModel(model);
}catch (SAXParseException err) {
System.out.println ("** Parsing error" + ", line "
+ err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());
}catch (SAXException e) {
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();
}catch (Throwable t) {
t.printStackTrace ();
}
}//GEN-LAST:event_jMenuItem1MousePressed
|
e8256627-a1e9-4f83-9b72-1789cf562e59
| 8
|
public Object makeDefaultValue(Class type)
{
if (type == int.class)
return new Integer(0);
else if (type == boolean.class)
return Boolean.FALSE;
else if (type == double.class)
return new Double(0);
else if (type == String.class)
return "";
else if (type == Color.class)
return Color.BLACK;
else if (type == Location.class)
return currentLocation;
else if (Grid.class.isAssignableFrom(type))
return currentGrid;
else
{
try
{
return type.newInstance();
}
catch (Exception ex)
{
return null;
}
}
}
|
7e913e96-09d1-4cb8-8395-49a3dd445e15
| 5
|
public synchronized Connection getConnection() throws ConnectionException{
Connection connection;
for ( int i = 0; i < POOL_SIZE; i++ ){
if ( pooledConnections[i] == null ){
connection = createConnection();
PooledSqlConnection pooledConnection = new PooledSqlConnection(this, connection, true);
setInUse(i);
pooledConnections[i] = pooledConnection;
return pooledConnection;
} else if ( ! inUse[i] ){
connection = pooledConnections[i];
setInUse(i);
try{
if ( ! connection.isValid(3) ){
LOGGER.warn("A connection is no longer valid.");
connection = createConnection();
} else {
reusedConnections++;
LOGGER.info("Reusing an established connecting, this is the " + reusedConnections + " time a connection is reused.");
}
} catch (SQLException e){
throw new ConnectionException("Unable to determine if the old exception is valid: " + e.getMessage());
}
return connection;
}
}
unPooledConnections++;
connection = createConnection();
return new PooledSqlConnection(this, connection, false);
}
|
ab9963d8-727e-4851-ac0e-770d73befad0
| 6
|
@Override
public void run() {
if(elCliente.entrada==null){
System.out.println("El Stream esta null");
return;
}
System.out.println("Iniciando el Thread el Input");
System.out.println("Esperando mensajes...");
try{
Object in=elCliente.entrada.readObject();
do{
String mensaje=(String)in;
//System.out.println("("+mensaje+")");
elCliente.servidor.procesaMensaje(mensaje, elCliente.getID());
in=elCliente.entrada.readObject();
}while(in!=null);
}catch(EOFException ee){
}catch(SocketException se){
}catch(NullPointerException ee){
}catch(Exception eof){
System.out.println("Error al escuchar mensaje... "+eof);
eof.printStackTrace();
}finally{
elCliente.servidor.adiosCliente(String.valueOf(elCliente.getID()));
}
System.out.println("Sesion con "+elCliente.getID()+" Terminada");
}
|
af0344e9-4cad-4e4a-8cda-38e72395b280
| 0
|
private ServerConnectionType(String type) {
this.type = type;
}
|
8b079a8d-fd38-4fb0-abb9-4f213d5c80dc
| 2
|
public Counter nextTurn(Counter lastPlaced, Board b) {
Counter next = Counter.EMPTY;
if (lastPlaced == Counter.BLACK) {
next = Counter.WHITE;
} else if (lastPlaced == Counter.WHITE) {
next = Counter.BLACK;
}
return next;
}
|
d491d349-da9c-4114-89bc-bfb51cf79a2f
| 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(mail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(mail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(mail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(mail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new mail().setVisible(true);
}
});
}
|
6fb67563-ebad-46a5-8ab1-6168d6a30199
| 8
|
public static int searchInt(int[] arr,int low,int high,int x){
if(low>high) return -1;
int mid = (low+high)/2;
if(x==arr[mid]) return mid;
if(arr[mid]>=arr[low]&&arr[mid]>=arr[high]){
if(x>=arr[low]&&x<arr[mid]) return searchInt(arr,low,mid-1,x);//could replace this with binarySearch
else return searchInt(arr,mid,high,x);
}else {
if(x>arr[mid]&&x<=arr[high]) return searchInt(arr,mid+1,high,x);//could replace this with binarySearch
else return searchInt(arr,low,mid,x);
}
}
|
ace6952a-a44f-4f7b-ae25-08193210fd47
| 7
|
public void updateUnicodeString( String s )
{
if( s.equals( toString() ) )
{
return;
}
// 0 cch 2 Count of characters in string (NOT the number of bytes)
// 2 grbit 1 Option flags
// make sure to get formatting runs if present
byte[] strbytes = null;
try
{
if( !ByteTools.isUnicode( s ) )
{
strbytes = s.getBytes( DEFAULTENCODING );
grbit = (byte) (grbit & 0xFE);
}
else
{
strbytes = s.getBytes( UNICODEENCODING );
if( !((grbit & 0x1) == 0x1) )
{
grbit += 0x1;
}
}
}
catch( UnsupportedEncodingException e )
{
log.warn( "Problem encoding string: " + e , e);
}
int strdatalen = strbytes.length;
int strlen = s.length();
byte[] blen = ByteTools.cLongToLEBytes( strlen );
if( (grbit & 0x4) == 0x4 )
{ // it was an eastern string. Blow that extrst out...
grbit = (byte) (grbit & 0xFB);
ExtRst = null;
offer -= 4;
westernencoding = true;
}
if( (grbit & 0x8) == 0x8 )
{ // had formatting runs - remove (since cannot keep with new string)
formatlen = 0;
fRichSt = false;
grbit ^= 0x8;
offer -= 2;
}
byte[] newbytes = new byte[strdatalen + offer + formatlen];
newbytes[2] = grbit;
System.arraycopy( blen, 0, newbytes, 0, 2 );
System.arraycopy( strbytes, 0, newbytes, offer, strdatalen );
if( isRichString() )
{
System.arraycopy( formattingarray, 0, newbytes, strdatalen + offer, formatlen );
// put the number of formatting runs back
newbytes[3] = formatrunnum[0];
newbytes[4] = formatrunnum[1];
}
init( newbytes, false );
}
|
7958e05c-5afc-4730-a1bb-9c1d407da5ad
| 1
|
private static void buildCode(String[] st, Node x, String s) {
if (!x.isLeaf()) {
buildCode(st, x.left, s + '0');
buildCode(st, x.right, s + '1');
} else {
st[x.ch] = s;
}
}
|
d414dba3-d478-475a-8add-ba3d0a067ab4
| 0
|
public void testCorrectColorList() {
Combination<Colors> combination = DefaultValues.DEFAULTATTEMPTCOMBINATION1;
List<Colors> list = combination.getColorsList();
assertEquals(list.get(0), Colors.R);
assertEquals(list.get(1), Colors.O);
assertEquals(list.get(2), Colors.Y);
assertEquals(list.get(3), Colors.G);
assertEquals(list.get(4), Colors.B);
}
|
a80d692b-4db9-4430-89c5-b1da16eae3ac
| 7
|
private JList createJList(Object[] data){
JList list = new JList(data) {
private static final long serialVersionUID = 1L;
// Subclass JList to workaround bug 4832765, which can cause the
// scroll pane to not let the user easily scroll up to the beginning
// of the list. An alternative would be to set the unitIncrement
// of the JScrollBar to a fixed value. You wouldn't get the nice
// aligned scrolling, but it should work.
public int getScrollableUnitIncrement(Rectangle visibleRect,
int orientation, int direction) {
int row;
if (orientation == SwingConstants.VERTICAL && direction < 0
&& (row = getFirstVisibleIndex()) != -1) {
Rectangle r = getCellBounds(row, row);
if ((r.y == visibleRect.y) && (row != 0)) {
Point loc = r.getLocation();
loc.y--;
int prevIndex = locationToIndex(loc);
Rectangle prevR = getCellBounds(prevIndex, prevIndex);
if (prevR == null || prevR.y >= r.y) {
return 0;
}
return prevR.height;
}
}
return super.getScrollableUnitIncrement(visibleRect,
orientation, direction);
}
};
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
list.setVisibleRowCount(-1);
return list;
}
|
d572ee45-9226-467b-88d1-fb4cee7a42e8
| 7
|
public int calculateDay(int day)
{
if (day == 1)
return 0;
if (day == 2)
return 1;
if (day == 3)
return 2;
if (day == 4)
return 3;
if (day == 5)
return 4;
if (day == 6)
return 5;
return day != 7 ? 7 : 6;
}
|
d611b812-bc9c-48b3-b57f-a8240b1b0b3a
| 8
|
public boolean compareNames(String... names) {
if (names.length != 2)
return false;
NameComparison nameUtil = NameComparison.get();
String[] firsts = get("firstName"), lasts = get("lastName"), boths = get("name");
if (firsts.length == 0 || lasts.length == 0) {
for (String both : boths) {
if (nameUtil.isSameFullName(nameUtil.parseName(both), names))
return true;
}
} else {
for (int i = 0; i < firsts.length && i < lasts.length; ++i) {
if (nameUtil.isSameFullName(new String[] { firsts[i], lasts[i] }, names))
return true;
}
}
return false;
}
|
503d4603-8b55-4f73-9c1b-58d294840711
| 2
|
@SuppressWarnings("unchecked")
public static TreeMap<String, float[]> restoreTM1D(String findFromFile) {
TreeMap<String, float[]> dataSet = null;
try {
FileInputStream filein = new FileInputStream(findFromFile);
ObjectInputStream objin = new ObjectInputStream(filein);
try {
dataSet = (TreeMap<String, float[]>) objin.readObject();
} catch (ClassCastException cce) {
cce.printStackTrace();
}
objin.close();
} catch (Exception ioe) {
ioe.printStackTrace();
System.out.println("NO resume: saver");
}
return dataSet;
} // /////////// ////////////////////////////
|
d8da8fb3-4cbe-47f5-8dd3-468ae76e98f0
| 7
|
private void drawHands(){
for (int i = 0; i < playerHand.size(); i ++){
boolean isSelected = false;
Card c = playerHand.getCard(i);
for (Integer iS: selections)
if (iS == i)
isSelected = true;
if (isSelected){ // any selected card will be signified by lowering the alpha
Image a = cardImages[c.value()-1][c.suit()].copy();
a.setAlpha(.5f);
a.draw(PLAYER_HAND_X + i*CARD_WIDTH, PLAYER_HAND_Y);
}
else
cardImages[c.value()-1][c.suit()].draw(PLAYER_HAND_X + i*CARD_WIDTH, PLAYER_HAND_Y);
}// end draw player hand
if (displayComputerHand){
for (int i = 0; i < computerHand.size(); i ++){
Card c = computerHand.getCard(i);
cardImages[c.value()-1][c.suit()].draw(COMPUTER_HAND_X + i*CARD_WIDTH, COMPUTER_HAND_Y);
}
} // end draw computer hand face up
else
for (int i = 0; i < computerHand.size(); i ++)
cardBack.draw(COMPUTER_HAND_X + i * CARD_WIDTH, COMPUTER_HAND_Y);
} // end drawHands
|
50f41df4-ee7e-4e6c-9c75-5564b613970f
| 0
|
public void setCategories(String newCategories) {
categories = newCategories.split(",");
}
|
17c0981a-7bfd-4e3f-86e8-0dc6626ec75b
| 5
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Vector2f vector2f = (Vector2f) o;
if (Float.compare(vector2f.x, x) != 0) return false;
if (Float.compare(vector2f.y, y) != 0) return false;
return true;
}
|
d788e3dc-420f-4ee1-9fa4-8e1f843d3e74
| 0
|
public double getMarkerHeight()
{
return markerRect.getHeightCoordinates();
}
|
379313b9-331c-42a7-9e29-f32c71ed0ec7
| 9
|
public static int awtKeyToLWJGL(KeyEvent e)
{
int key_code = e.getKeyCode();
int position = e.getKeyLocation();
/* Code taken from LWJGL, specifically org.lwjgl.opengl.KeyboardEventQueue */
switch (key_code)
{
case KeyEvent.VK_ALT: // fall through
if (position == KeyEvent.KEY_LOCATION_RIGHT)
return Keyboard.KEY_RMENU;
else
return Keyboard.KEY_LMENU;
case KeyEvent.VK_META:
if (position == KeyEvent.KEY_LOCATION_RIGHT)
return Keyboard.KEY_RMETA;
else
return Keyboard.KEY_LMETA;
case KeyEvent.VK_SHIFT:
if (position == KeyEvent.KEY_LOCATION_RIGHT)
return Keyboard.KEY_RSHIFT;
else
return Keyboard.KEY_LSHIFT;
case KeyEvent.VK_CONTROL:
if (position == KeyEvent.KEY_LOCATION_RIGHT)
return Keyboard.KEY_RCONTROL;
else
return Keyboard.KEY_LCONTROL;
default:
if (KEY_MAP.containsKey(key_code))
{
return KEY_MAP.get(key_code);
}
else
{
return Keyboard.KEY_NONE;
}
}
}
|
2a0872ad-e5df-425b-8d77-e3590fc6a2b8
| 8
|
public void tick(){
if(alive){
if(listener.isPressed(40)){
if(y<750){
y = y + 8;
}
}
if(listener.isPressed(38)){
if(y>0){
y = y - 8;
}
}
if(listener.isPressed(32)){
if(delay<=20){
shots = shots.add(new laser(x+34,y+28));
delay = delay + 20;
}
}
}
flame();
shots.tick();
shots.clean();
if(delay>=0){
delay = delay -1;
}
}
|
aaaf3064-b62e-4a20-8276-918fd045a3e2
| 2
|
public BattleField(int width, int heigth) {
hitCount = 0;
if (width > 5) {
this.width = width;
}
if (heigth > 5) {
this.width = heigth;
}
ships = new HashSet<>();
initFields();
}
|
9b9211b5-1185-4c65-8719-b8839cd08d88
| 2
|
@Override
public Data read(int index) {
if (index > -1 && index < 16) { //Ensure valid index (0-15)
return generalPurposeRegisters[index];
}
return null;
}
|
92a1e066-dd0d-4373-95a2-88a11e38fe7e
| 1
|
@Override
public void removeOne(int intId, String strTabla) throws Exception {
Statement oStatement;
try {
oStatement = (Statement) oConexionMySQL.createStatement();
String strSQL = "DELETE FROM " + strTabla + " WHERE id = " + intId;
oStatement.executeUpdate(strSQL);
} catch (SQLException e) {
throw new Exception("mysql.deleteOne: Error al eliminar el registro: " + e.getMessage());
}
}
|
d0129731-01db-477c-9f81-b4c78f80a08a
| 1
|
public boolean getScrollableTracksViewportWidth() {
if (adapt)
return true;
return getPreferredSize().width < getParent().getSize().width;
}
|
11f1581d-dea5-4c78-8586-6ac7a2235e39
| 2
|
public void visitEnd() {
if (state != CLASS_TYPE) {
throw new IllegalStateException();
}
state = END;
if (sv != null) {
sv.visitEnd();
}
}
|
3b959a0f-0860-433d-8b11-b1a281edf9db
| 8
|
public void changeSelection(int rowIndex, int columnIndex, boolean toggle,
boolean extend) {
prevRowIndex = currentRowIndex;
prevColumnIndex = currentColumnIndex;
currentRowIndex = rowIndex;
currentColumnIndex = columnIndex;
// logger.debug("prevRowIndex=" + prevRowIndex);
// logger.debug("prevColumnIndex=" + prevColumnIndex);
// logger.debug("currentRowIndex=" + currentRowIndex);
// logger.debug("currentColumnIndex=" + currentColumnIndex);
super.changeSelection(rowIndex, columnIndex, toggle, extend);
boolean cancelled = this.checkAutoInsertCancel();
boolean inserted = false;
if (!cancelled) {
inserted = this.checkAutoInsert();
}
// possible changes to cell selection...
if (getModel() != null && getModel().getRowCount() > 0) {
if (inserted) {
changeSelection((this.getRowCount()-1), 0, false, false); // first cell in new row to be selected
} else {
if (this.isCellEditable(currentRowIndex, currentColumnIndex)) {
if (this.startEditingOnSelection) {
this.editCellAt(currentRowIndex, currentColumnIndex);
// forcing focus to the selected component:
this.transferFocus();
if (this.getCellEditor() instanceof DefaultCellEditor) {
DefaultCellEditor editor = (DefaultCellEditor) this.getCellEditor();
editor.getComponent().requestFocus();
}
}
} else {
if (skipNotEditableCells) {
moveToNextCell();
}
}
}
}
this.lastKeyPressedEvent = null;
}
|
d7d7aeae-9687-4c24-8bfe-8826f0fedae6
| 8
|
public static Stella_Object accessMeasureSlotValue(Measure self, Symbol slotname, Stella_Object value, boolean setvalueP) {
if (slotname == Utilities.SYM_UTILITIES_BASE_UNIT) {
if (setvalueP) {
self.baseUnit = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.baseUnit);
}
}
else if (slotname == Utilities.SYM_UTILITIES_SCALE) {
if (setvalueP) {
self.scale = ((KeyValueList)(value));
}
else {
value = self.scale;
}
}
else if (slotname == Utilities.SYM_UTILITIES_PRIME_ID) {
if (setvalueP) {
self.primeId = ((Ratio)(value));
}
else {
value = self.primeId;
}
}
else if (slotname == Utilities.SYM_STELLA_NAME) {
if (setvalueP) {
self.name = ((StringWrapper)(value)).wrapperValue;
}
else {
value = StringWrapper.wrapString(self.name);
}
}
else {
{ OutputStringStream stream000 = OutputStringStream.newOutputStringStream();
stream000.nativeStream.print("`" + slotname + "' is not a valid case option");
throw ((StellaException)(StellaException.newStellaException(stream000.theStringReader()).fillInStackTrace()));
}
}
return (value);
}
|
4c4ca51c-734c-4ff4-b69a-a8bf23074dc6
| 8
|
public PathNode search(final Unit unit, Location start,
final GoalDecider goalDecider,
final CostDecider costDecider,
final int maxTurns, final Unit carrier) {
Location entry = findRealStart(unit, start, carrier);
int initialTurns = (!unit.isAtSea()) ? 0
: ((unit.isOnCarrier()) ? unit.getCarrier() : unit).getWorkLeft();
PathNode path;
if (entry instanceof Europe) {
Unit waterUnit = (carrier != null) ? carrier : unit;
// Fail fast if Europe is unattainable.
if (!waterUnit.getType().canMoveToHighSeas()) return null;
path = searchInternal(unit, (Tile)waterUnit.getEntryLocation(),
goalDecider, costDecider, maxTurns,
carrier, null);
if (path == null) return null;
path.addTurns(waterUnit.getSailTurns());
path.previous = new PathNode(entry, waterUnit.getMovesLeft(),
0, carrier != null, null, path);
path = path.previous;
} else {
path = searchInternal(unit, entry.getTile(),
goalDecider, costDecider, maxTurns,
carrier, null);
}
if (path != null && initialTurns != 0) path.addTurns(initialTurns);
return path;
}
|
dd9615cd-abe0-4b3e-8cb5-d6a0955e023c
| 0
|
public static String getDesc(int bookId) {
return bookDesc[bookId-300];
}
|
342dade5-0a1f-4542-8303-f2b2e52d18b0
| 4
|
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PID other = (PID) obj;
if (id != other.id)
return false;
return true;
}
|
9cedcad7-523f-463d-bf75-8438dfa554d2
| 6
|
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
|
0206f312-b660-493b-98f8-b3a29ad4bcf4
| 5
|
public void itemStateChanged(ItemEvent arg0)
{
if (arg0.getSource().equals(playerBox) && arg0.getStateChange() == ItemEvent.SELECTED)
{
// config.setActivePlayer((Class)arg0.getItem());
selectedPlayer = (Class) arg0.getItem();
config.setPlayerClass((Class<Player>) playerBox.getSelectedItem());
if(selectedPlayer.getName().equals("mosquito.g0.InteractivePlayer"))
{
this.interactiveHelp.setVisible(true);
this.generateMosquitosButton.setVisible(true);
}
else
{
this.interactiveHelp.setVisible(false);
this.generateMosquitosButton.setVisible(false);
}
//System.out.println("SELECTED:" + selectedPlayer.toString());
}
if (arg0.getSource().equals(boardBox) && arg0.getStateChange() == ItemEvent.SELECTED)
{
config.setSelectedBoard((File) arg0.getItem());
}
}
|
12915a76-5655-4116-a823-83382388e216
| 3
|
private static void displayRateReview(BufferedReader reader, VideoStore videoStore) {
try {
System.out.println("Please enter the title of the video the review was for:");
String isbn = getISBNFromTitle(reader, videoStore, reader.readLine());
System.out.println("Please enter the name of the reviewer (leave blank to show all reviews):");
String reviewer = reader.readLine();
LinkedList<Review> reviews = videoStore.getOtherReviews(reviewer, isbn);
displayReviews(reviews, true);
System.out.println(reviews.size() + 1 + ". Cancel");
System.out.println("Please choose a review:");
int choice = readMenuChoice(reader, reviews.size() + 1);
if (choice == reviews.size() + 1) {
return;
}
reviewer = reviews.get(choice - 1).getReviewer();
System.out.println("Please enter the usefulness of the review (0 = Useless, 1 = Useful, 2 = Very Useful):");
int score = readInt(reader, 0, 2);
if (videoStore.rateReview(isbn, reviewer, score)) {
System.out.println("Successfully added the usefulness rating for the review.");
return;
}
System.out.println("Could not successfully add the usefulness rating for the review.");
} catch (Exception e) {
System.out.println("There was an error while creating the usefulness rating.");
}
}
|
948fdbd0-a4de-482c-8d39-88890fe0fa16
| 7
|
public void init() throws IOException
{
//create a vector to hold the lines of text read from the file
buffer = new ArrayList<>(1000);
modified = false; //no data has yet been modified or added
//create various decimal formats
DecimalFormats = new DecimalFormat[11];
DecimalFormats[0] = new DecimalFormat("#");
DecimalFormats[1] = new DecimalFormat("#.#");
DecimalFormats[2] = new DecimalFormat("#.##");
DecimalFormats[3] = new DecimalFormat("#.###");
DecimalFormats[4] = new DecimalFormat("#.####");
DecimalFormats[5] = new DecimalFormat("#.#####");
DecimalFormats[6] = new DecimalFormat("#.######");
DecimalFormats[7] = new DecimalFormat("#.#######");
DecimalFormats[8] = new DecimalFormat("#.########");
DecimalFormats[9] = new DecimalFormat("#.#########");
DecimalFormats[10] = new DecimalFormat("#.##########");
//create a buffered reader stream to the language file
FileInputStream fileInputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader in = null;
try{
fileInputStream = new FileInputStream(filename);
inputStreamReader = new InputStreamReader(fileInputStream, fileFormat);
in = new BufferedReader(inputStreamReader);
String line;
//read until end of file reached or "[end of header]" tag reached
while ((line = in.readLine()) != null){
buffer.add(line);
if (line.equals("[Header End]")) {break;}
}
}
catch (FileNotFoundException e){
//if an existing file was not found, add some header info to the buffer
//so it will be saved when the file is created
buffer.add("");
buffer.add(";Do not erase blank line above -"
+ " has hidden code needed by UTF-16 files.");
buffer.add(";To make a new file, copy an existing ini file and change"
+ " only data below this line.");
buffer.add("");
}
catch(IOException e){
logSevere(e.getMessage() + " - Error: 346");
throw new IOException();
}
finally{
if (in != null) {in.close();}
if (inputStreamReader != null) {inputStreamReader.close();}
if (fileInputStream != null) {fileInputStream.close();}
}
}//end of IniFile::init
|
91327638-f0a8-4717-9beb-6a7c6b5a9cd4
| 7
|
public List<Airfield> getRecentAirfield()
{
try{
List<Airfield> airfields = DatabaseDataObjectUtilities.getAirfields();
List<Airfield> recentAirfieldList = new ArrayList<Airfield>();
if(instance == null)
{
return null;
}
else
{
for (int index = 0; (index < instance.recentAirfield.size()) && (recentAirfieldList.size() < 5); index++){
for (int index2 = 0; (index2 < airfields.size()); index2++){
if (airfields.get(index2).getId().equals(instance.recentAirfield.get(index))){
recentAirfieldList.add(airfields.get(index2));
}
}
}
return recentAirfieldList;
}
}catch(SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(RecentLaunchSelections.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
|
2c73ef38-ad60-4325-915e-4e2b44fa50d0
| 0
|
public CheckResultMessage check19(int day) {
return checkReport.check19(day);
}
|
87b5867f-a7af-4b59-a21c-12bdb1b101c5
| 1
|
private static void printListOldWay(String type) {
System.out.println("Old Way " + type + ":");
for (User u : users) {
System.out.println("\t" + u);
}
System.out.println();
}
|
ee42731e-75ad-4ef5-ac44-9b74f400087a
| 0
|
@BeforeTest
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://localhost:8888/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
|
844680aa-4f12-4922-93ab-ac150e765a9e
| 6
|
public void setWeights(int node) {
for (int i = 0; i < result.length; i++) {
if (adjMatrix[node][i] != 0 && visited[i] != 1 && (result[i] > (result[node] + adjMatrix[node][i]) ||
result[i] == -1))
result[i] = result[node] + adjMatrix[node][i];
}
visited[node] = 1;
int res = getMinimum();
if (res == -1) return;
setWeights(res);
}
|
ea01f107-96f7-48fd-8b02-96c3ddc3394b
| 4
|
public void body()
{
int resourceID[] = new int[this.totalResource_];
double resourceCost[] = new double[this.totalResource_];
String resourceName[] = new String[this.totalResource_];
LinkedList resList;
ResourceCharacteristics resChar;
// waiting to get list of resources. Since GridSim package uses
// multi-threaded environment, your request might arrive earlier
// before one or more grid resource entities manage to register
// themselves to GridInformationService (GIS) entity.
// Therefore, it's better to wait in the first place
while (true)
{
// need to pause for a while to wait GridResources finish
// registering to GIS
super.gridSimHold(1.0); // hold by 1 second
resList = super.getGridResourceList();
if (resList.size() == this.totalResource_)
break;
else
{
System.out.println(this.name_ +
":Waiting to get list of resources ...");
}
}
// a loop to get all the resources available
int i = 0;
for (i = 0; i < this.totalResource_; i++)
{
// Resource list contains list of resource IDs not grid resource
// objects.
resourceID[i] = ( (Integer)resList.get(i) ).intValue();
// Requests to resource entity to send its characteristics
super.send(resourceID[i], GridSimTags.SCHEDULE_NOW,
GridSimTags.RESOURCE_CHARACTERISTICS, this.ID_);
// waiting to get a resource characteristics
resChar = (ResourceCharacteristics) super.receiveEventObject();
resourceName[i] = resChar.getResourceName();
resourceCost[i] = resChar.getCostPerSec();
System.out.println(this.name_ +
":Received ResourceCharacteristics from " +
resourceName[i] + ", with id = " + resourceID[i]);
// record this event into "stat.txt" file
super.recordStatistics("\"Received ResourceCharacteristics " +
"from " + resourceName[i] + "\"", "");
}
Gridlet gridlet;
String info;
// a loop to get one Gridlet at one time and sends it to a random grid
// resource entity. Then waits for a reply
int id = 0;
for (i = 0; i < this.list_.size(); i++)
{
gridlet = (Gridlet) this.list_.get(i);
info = "Gridlet_" + gridlet.getGridletID();
id = GridSimRandom.intSample(this.totalResource_);
System.out.println(this.name_ + ":Sending " + info + " to " +
resourceName[id] + " with id = " + resourceID[id]);
// Sends one Gridlet to a grid resource specified in "resourceID"
super.gridletSubmit(gridlet, resourceID[id]);
// Recods this event into "stat.txt" file for statistical purposes
super.recordStatistics("\"Submit " + info + " to " +
resourceName[id] + "\"", "");
// waiting to receive a Gridlet back from resource entity
gridlet = super.gridletReceive();
System.out.println(this.name_ + ":Receiving Gridlet " +
gridlet.getGridletID() );
// Recods this event into "stat.txt" file for statistical purposes
super.recordStatistics("\"Received " + info + " from " +
resourceName[id] + "\"", gridlet.getProcessingCost());
// stores the received Gridlet into a new GridletList object
this.receiveList_.add(gridlet);
}
// shut down all the entities, including GridStatistics entity since
// we used it to record certain events.
super.shutdownGridStatisticsEntity();
super.shutdownUserEntity();
super.terminateIOEntities();
System.out.println(this.name_ + ":%%%% Exiting body()");
}
|
a9fbd428-94b3-40c1-9f3b-480f0eb482dd
| 4
|
@Override
public void run() {
Random rnd = new Random();
try (ServerSocket server = new ServerSocket(port)) {
System.out.println("server up and running on port " + port);
ServerOutputHandler output = new ServerOutputHandler(
allConnections, m, rnd.nextLong());
output.start();
while (true) {
Socket s = server.accept();
allConnections.add(s);
ServerInputHandler in = new ServerInputHandler(s, m, allConnections);
in.start();
output.addPlayername(in.getPlayername());
if (allConnections.size() == 2) {
output.setRandomSeed(rnd.nextLong());
output.initiateGameOnClients();
} else if (allConnections.size() > 2) {
allConnections.add(s);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
|
78ad3d89-f8bd-48e8-98cd-3b58aa8e4d5d
| 2
|
public void setState(State _state)
{
if(getWidth() > 0 && getHeight() > 0)
{
getGui().setVisible(false);
state = _state;
getGui().setVisible(true);
}else{
ClientHelper.log(LogType.GUI, "GuiManager: setState wurde vor setBounds aufgerufen");
}
}
|
86ced496-a8f7-41fa-977e-a93edf187adf
| 6
|
public void processArgs(Option opt, ListIterator iter) throws ParseException
{
// loop until an option is found
while (iter.hasNext())
{
String str = (String) iter.next();
// found an Option, not an argument
if (getOptions().hasOption(str) && str.startsWith("-"))
{
iter.previous();
break;
}
// found a value
try
{
opt.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(str));
}
catch (RuntimeException exp)
{
iter.previous();
break;
}
}
if (opt.getValues() == null && !opt.hasOptionalArg())
{
throw new MissingArgumentException(opt);
}
}
|
e11715b8-f43f-4a54-8b15-79b2c7736a7b
| 7
|
@Override
public void runClient(GameEntity entity, float delta) {
if(EntityManager.interpolate && prevSnapshot != null && nextSnapshot != null) {
float progress = acc/0.05f;
Vector3 pos = nextSnapshot.v3_0;
Vector3 vel = nextSnapshot.v3_1;
Vector3 imp = nextSnapshot.v3_2;
if(progress < 1f) {
pos = Compare.interpolate(prevSnapshot.v3_0, pos, progress, Interpolation.linear);
vel = Compare.interpolate(prevSnapshot.v3_1, vel, progress, Interpolation.linear);
imp = Compare.interpolate(prevSnapshot.v3_2, imp, progress, Interpolation.linear);
}
if(pos != null) updateTransform(pos.x, pos.y, pos.z, angle);
if(vel != null) updateVelocity(vel.x, vel.y, vel.z);
if(imp != null) updateImpulse(imp.x, imp.y, imp.z);
acc+=delta;
}
}
|
0f0286b2-7cd2-496e-9912-dc1ea27c997d
| 4
|
private void addDependent(JSRTargetInfo result) {
if (dependent == null || dependent == result)
dependent = result;
else if (dependent instanceof JSRTargetInfo) {
Set newDeps = new HashSet();
newDeps.add(dependent);
newDeps.add(result);
} else if (dependent instanceof Collection) {
((Collection) dependent).add(result);
}
}
|
f292b836-d988-4221-a8fe-e249cff1197e
| 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(Frm_ConUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Frm_ConUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Frm_ConUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Frm_ConUsuarios.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Frm_ConUsuarios().setVisible(true);
}
});
}
|
41988be5-0bde-4b09-ac10-9f7974105fcf
| 8
|
@Override
public void run() {
try {
BamWindow window = bamWindows.getWindow();
VariantCandidateEmitter emitter = new VariantCandidateEmitter(referenceFile, counters, window, options);
List<VariantCandidate> variantCandidates = new ArrayList<VariantCandidate>();
for(String contig : intervals.getContigs()) {
for(Interval interval : intervals.getIntervalsInContig(contig)) {
List<VariantCandidate> candidates = emitter.emitWindow(contig, interval.getFirstPos(), interval.getLastPos());
if (candidates.size() > 0) {
variantCandidates.addAll(candidates);
}
basesComputed += interval.getSize();
}
}
// Call true SNPs
for (VariantCandidate v: variantCandidates) {
// dataStream.println(v.getContig() + ":" + v.getPosition() + "\t" + v.getRefBase() + "\t" + Arrays.toString(v.getAlnBases()));
Variant var = this.classifier.classify(v);
if (var != null) {
this.variants.add(var);
}
}
} catch (IOException iox) {
iox.printStackTrace();
} catch (FastaIndex.IndexNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
|
e9b7e9f1-5b72-4c22-b47c-eea45a0491a2
| 0
|
public int getValue()
{
return value;
}
|
325df6c6-f577-4e70-aad3-d806c1ed89bf
| 5
|
public int getKeyCode(int game) {
String name;
switch(game){
case UP: name = "UP"; break;
case DOWN: name = "DOWN"; break;
case LEFT: name = "LEFT"; break;
case RIGHT: name = "RIGHT"; break;
case FIRE: name = "FIRE"; break;
default:
return game;
}
return ApplicationManager.manager.getKeyCode(name);
}
|
859319aa-cf4b-46f8-ad77-cc1969c04ae4
| 3
|
@Test
public void testRunStartServerSpotFaculty()throws Exception{
AccessControlServer server = new AccessControlServer(1932);
server.start();
SpotStub spot = new SpotStub("101",1932);
spot.start();
sleep(1000);
String ans = "";
int x = 0;
while(x != -1 && x<=50){ //if no response is recieved in 10 seconds, test is deemed failed.
x++;
ans = spot.getAnswer();
sleep(100);
if(ans != ""){
x = -1;
}
}
assertEquals("Faculty",ans);
}
|
374fe200-874c-404d-81d8-cc1fdf5c1452
| 0
|
public GridWorker(GridProcessingManager gpm, int id) {
this.gpm = gpm;
this.id = id;
}
|
74a8668d-4e86-41a9-983f-33c56e081b7a
| 6
|
public String diff_toDelta(LinkedList<Diff> diffs) {
StringBuilder text = new StringBuilder();
for (Diff aDiff : diffs) {
switch (aDiff.operation) {
case INSERT:
try {
text.append("+").append(URLEncoder.encode(aDiff.text, "UTF-8")
.replace('+', ' ')).append("\t");
} catch (UnsupportedEncodingException e) {
// Not likely on modern system.
throw new Error("This system does not support UTF-8.", e);
}
break;
case DELETE:
text.append("-").append(aDiff.text.length()).append("\t");
break;
case EQUAL:
text.append("=").append(aDiff.text.length()).append("\t");
break;
}
}
String delta = text.toString();
if (delta.length() != 0) {
// Strip off trailing tab character.
delta = delta.substring(0, delta.length() - 1);
delta = unescapeForEncodeUriCompatability(delta);
}
return delta;
}
|
3a025884-2219-41f5-88b4-b8fbbc2a6586
| 9
|
private void drawLine(HomCoords2D homCoords1, HomCoords2D homCoords2, BufferedImage textureTop, BufferedImage textureBottom, Color colour) {
// We note that we speak about points in the textured image as (x, y) where (0, 0) represents the middle of the image,
// and the coordinates are scaled so that (+-1, +-1) are the four corners of the texture.
// Now, in textureTop, we have (x, y) representing the point [x+iy, 1]
// In textureBottom we have (x, y) representing the point [1, x-iy].
// So the first thing to decide is whether or not we have to draw to both textures.
try {
boolean homCoords1UpperHemisphere = homCoords1.isUpperHemisphere();
boolean homCoords2UpperHemisphere = homCoords2.isUpperHemisphere();
// if both points are in the top half of the sphere, then we can draw the line purely in textureTop.
if (homCoords1UpperHemisphere && homCoords2UpperHemisphere) {
drawLineGivenComplexCoordinates(homCoords1.stereographicProjectionFromSouthPole(), homCoords2.stereographicProjectionFromSouthPole(), textureTop, colour);
}
if (!homCoords1UpperHemisphere && !homCoords2UpperHemisphere) {
drawLineGivenComplexCoordinates(homCoords1.stereographicProjectionFromNorthPole(), homCoords2.stereographicProjectionFromNorthPole(), textureBottom, colour);
}
// The harder situation is when the line crosses the top and bottom.
// We shall assume that neither point is one of the poles.
if (homCoords1UpperHemisphere && !homCoords2UpperHemisphere || !homCoords1UpperHemisphere && homCoords2UpperHemisphere) {
// We first project from the north pole
Complex homCoords1FromNorth = homCoords1.stereographicProjectionFromNorthPole();
Complex homCoords2FromNorth = homCoords2.stereographicProjectionFromNorthPole();
drawLineGivenComplexCoordinates(homCoords1FromNorth, homCoords2FromNorth, _textureBottom, colour);
// Then we project from the south pole.
Complex homCoords1FromSouth = homCoords1.stereographicProjectionFromSouthPole();
Complex homCoords2FromSouth = homCoords2.stereographicProjectionFromSouthPole();
drawLineGivenComplexCoordinates(homCoords1FromSouth, homCoords2FromSouth, _textureTop, colour);
}
} catch (Exception e) {
System.out.println("Failed to draw line");
}
}
|
fc71c98d-ca9d-4a96-9fb8-b8fdd0a9ae18
| 0
|
public void setCountry(String country) {
this.country = country;
}
|
9a30a82c-5504-49fe-80fd-ecae44a1cd68
| 7
|
private void button_delete_selectedMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_button_delete_selectedMousePressed
if(hitbox_index_selected!=-1)
{
int i=0;
for(Node hitboxes_node=current_frame.getFirstChild();hitboxes_node!=null;hitboxes_node=hitboxes_node.getNextSibling())//Hitbox loop
{
if(hitboxes_node.getNodeName().equals("Hitboxes"))
{
if(((Element)hitboxes_node).getAttribute("variable").equals(hitbox_color_selected))
{
for(Node hitbox=hitboxes_node.getFirstChild();hitbox!=null;hitbox=hitbox.getNextSibling())//Red Hitboxes loop
{
if(hitbox.getNodeName().equals("Hitbox"))
{
if(i==hitbox_index_selected)
{
hitbox.getParentNode().removeChild(hitbox);
break;
}
i++;
}
}
}
}
}
updateHitboxes(current_frame);
}
else
{
JOptionPane.showMessageDialog(null, "Select a hitbox in a frame first.", "Be careful", JOptionPane.INFORMATION_MESSAGE);
}
}//GEN-LAST:event_button_delete_selectedMousePressed
|
bc34603d-9517-491f-b97c-6be29437340c
| 7
|
protected List<Getter> getters(Class<?> type) {
List<Getter> result=new ArrayList<Getter>();
for(Class<?> c=type;c!=null;c=c.getSuperclass())
for(Field field : c.getDeclaredFields())
if((field.getModifiers()&Modifier.STATIC) != 0) {
// We never serialize static fields
} else
if((field.getModifiers()&Modifier.PUBLIC) != 0)
result.add(new FieldGetter(field));
else {
List<String> names=getterNames(field);
Method method=findMethod(type, field.getType(), names);
if(method != null)
result.add(new MethodGetter(field, method));
}
return result;
}
|
704398db-a5c9-4e3d-a3f5-e682db4ca41f
| 6
|
private void doCalculation(double xf, double yf, int xi, int yi) {
double a, b, aa, bb;
float hue, huesat, new_gamma;
double[] iter;
a = 2 * (xf - 0.5) * zoom + xcen;
b = 2 * (yf - 0.5) * zoom + ycen;
aa = a;
bb = b;
iter = NewtonIterate(aa, bb, alg);
if (mandelbrotAddition) {
// get Color based on angle of z
// double angle = (float)Math.atan(bb/aa);
double angle = (float) Math.atan(iter[2] / iter[3]);
angle = angle + (Math.PI / 2);
angle = angle / Math.PI;
hue = (float) angle;
} else {
// limit the colors to 30% of the spectrum, unless a complex root
float limitfactor = 0.3f;
if (img_order != 0)
limitfactor = 1.0f;
hue = initColor + (float) (iter[1] * limitfactor) / roots.size();
}
// normal shading
huesat = (float) iter[0] / (depth / brightness);
if (huesat >= 1.0f)
huesat = 0.9999f;
huesat = (iter[0] == depth) ? 1 : huesat * 16000000;
if (huesat > 16000000) {
huesat = Math.abs(16000000 + (16000000 - huesat));
}
huesat = ((int) huesat % 16000000) / 16000000.0f;
new_gamma = (float) Math.pow(huesat, intensity);
int[] rgb = MPGlobal.HSBtoRGB(hue, 1.0f - huesat, new_gamma);
addPixel(xi, yi, rgb);
// rough painting
if (runtotal < pixels.length * 2) {
offscreenGraphics.setColor(new Color(pixels[yi * ximlen + xi]));
offscreenGraphics.fillRect(xi, yi, (int) quad, (int) quad);
}
}
|
8794c0a5-ffde-4e01-8a5d-a215202a3eb7
| 8
|
private void populate()
{
Random rand = Randomizer.getRandom();
field.clear();
for(int row = 0; row < field.getDepth(); row++) {
for(int col = 0; col < field.getWidth(); col++) {
if(rand.nextDouble() <= fox_creation_probability) {
Location location = new Location(row, col);
Fox fox = new Fox(true, field, location);
actors.add(fox);
}
else if(rand.nextDouble() <= rabbit_creation_probability) {
Location location = new Location(row, col);
Rabbit rabbit = new Rabbit(true, field, location);
actors.add(rabbit);
}
else if(rand.nextDouble() <= bear_creation_probability) {
Location location = new Location(row, col);
Bear bear = new Bear(true, field, location);
actors.add(bear);
}
else if (rand.nextDouble() <= hunter_creation_probability) {
Location location = new Location(row, col);
Hunter hunter = new Hunter(field, location);
actors.add(hunter);
}
else if(rand.nextDouble() <= wolf_creation_probability) {
Location location = new Location(row, col);
Wolf wolf = new Wolf(true, field, location);
actors.add(wolf);
}
else if(rand.nextDouble() <= grass_creation_probability) {
Location location = new Location(row, col);
Grass grass = new Grass(true, field, location);
actors.add(grass);
}
// else leave the location empty.
}
}
}
|
51d1e2a5-1edc-4722-8f1c-8204000df13d
| 5
|
private TagCompound saveObjective(Objective o)
{
TagCompound c = new TagCompound(o.getID());
c.setTag("name", new TagString("name", o.getName()));
c.setTag("target", new TagString("target", o.getTarget()));
c.setTag("type", new TagString("type", o.getType().getClass().getName()));
c.setTag("iconid", new TagInt("iconid", o.getItemIconId()));
c.setTag("optional", new TagByte("optional", (byte)(o.isOptional() ? 1 : 0)));
c.setTag("visible", new TagByte("visible", (byte)(o.isVisible() ? 1 : 0)));
TagList rewards = new TagList("rewards", TagType.COMPOUND);
for(QuestAction a:o.getRewards())rewards.add(saveAction(a));
c.setTag("rewards", rewards);
String[] desc = o.getDescription();
if(desc.length > 0)
{
TagList description = new TagList("description", TagType.STRING);
for(String s:desc)description.add(new TagString("", s));
c.setTag("description", description);
}
return c;
}
|
51e7a507-ac54-42b9-9c67-98000d13c837
| 6
|
private List<Tuple> joinResults() {
boolean continueReading = true;
List<Tuple> result = new LinkedList<Tuple>();
while(continueReading) {
try {
String line = null;
Tuple t2 = null;
while( (line = input2.getNextString()) != null ){
if (line.indexOf("END") == 0) {
continueReading = false;
} else {
//read tuple from second input
t2 = Tuple.makeTupleFromPipeData(line);
String targetKey = t2.get(input2JK);
if (storedData.containsKey(targetKey)) {
for (Tuple t1 : storedData.get(targetKey)) {
result.add( Tuple.join(t1, t2, input1JK, input2JK) );
}
}
}
}
} catch (IOException e) {
}
}
return result;
}
|
71a20e22-b2be-46ac-963d-a9002e754693
| 9
|
public static boolean isValidClassName(String s) {
if (s.length() < 1) return false;
if (s.equals("package-info")) return true;
if (surrogatesSupported) {
int cp = s.codePointAt(0);
if (!Character.isJavaIdentifierStart(cp))
return false;
for (int j=Character.charCount(cp); j<s.length(); j+=Character.charCount(cp)) {
cp = s.codePointAt(j);
if (!Character.isJavaIdentifierPart(cp))
return false;
}
} else {
if (!Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int j=1; j<s.length(); j++)
if (!Character.isJavaIdentifierPart(s.charAt(j)))
return false;
}
return true;
}
|
c57cbd58-9499-4171-8765-d5719e4aa74b
| 7
|
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
char[] v = new char[]{'A','U','E','O','I'};
char[] c = new char[]{'J','S','B','K','T','C','L','D','M','V','N','W','F','X','G','P','Y','H','Q','Z','R','S'};
int casos = Integer.parseInt(bf.readLine());
for (int i = 0; i < casos; i++) {
int n = Integer.parseInt(bf.readLine());
StringBuilder sb = new StringBuilder();
char vocales[] = new char[(int) Math.ceil((double)n/2)];
char sol[]=new char[n];
char consonantes[] = new char [n/2];
for (int j = 0; j < vocales.length; j++) {
vocales[j]= vocales[j/21];
}
for (int j = 0; j < consonantes.length; j++) {
vocales[j]= consonantes[j/5];
}
Arrays.sort(vocales);Arrays.sort(consonantes);
int contVocales = 0;
int posVocales=0;
int contConsonantes = 0;
int posConsonantes =0;
for (int j = 0; j < n; j++) {
if(j%2==0){
sb.append(vocales[posVocales%vocales.length]);
contVocales++;
if(contVocales==25){
posVocales++;
contVocales=0;
}
}else{
sb.append(consonantes[posConsonantes%consonantes.length]);
contConsonantes++;
if(contConsonantes==5){
posConsonantes++;
contConsonantes=0;
}
}
}
System.out.println(sb);
}
}
|
13ab1106-2c24-4130-ab33-91354b337426
| 1
|
public void visit_invokevirtual(final Instruction inst) {
final MemberRef method = (MemberRef) inst.operand();
final Type type = method.nameAndType().type();
stackHeight -= type.stackHeight() + 1;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += type.returnType().stackHeight();
}
|
8a6611bb-a98f-42cc-9769-f811de46afc0
| 9
|
public void drawSquares() {
for (byte i = 0; i < board.length; i++) {
for (byte y = 0; y < board[i].length; y++) {
switch (board[i][y]) {
case WALL:
theG.setColor(Color.BLUE);
theG.fillRect(y * SCALE, i * SCALE, SCALE, SCALE);
break;
case FREE:
drawBlackSquare(i, y);
break;
case DOT:
drawBlackSquare(i, y);
theG.setColor(Color.WHITE);
theG.fillOval(y * SCALE + 5, i * SCALE + 7, DOT_SIZE, DOT_SIZE);
break;
case ENERGIZER:
drawBlackSquare(i, y);
theG.setColor(Color.WHITE);
theG.fillOval(y * SCALE + 5, i * SCALE + 7, ENERGIZER_SIZE, ENERGIZER_SIZE);
break;
case PACMAN:
drawBlackSquare(i, y);
theG.setColor(Color.YELLOW);
theG.fillOval(y * SCALE, i * SCALE, PACMAN_SIZE, PACMAN_SIZE);
break;
case GHOST:
break;
default:
drawBlackSquare(i, y);
break;
}
}
}
for (byte i = 0; i < theGhosts.length; i++) {
drawGhost(theGhosts[i]);
}
}
|
6a7a7a64-9d5e-4331-aab3-9e9a8917c6be
| 1
|
@Override
public void mouseDragged(MouseEvent event) {
Point where = mListener.convertToLocalCoordinates(new Point(event.getX(), event.getY()));
mInterimBounds.setBounds(mBoundsToAdjust);
mAdjuster.adjust(where.x - mSnapshot.x, where.y - mSnapshot.y, mBoundsToAdjust, mBoundsSnapshot);
if (!mInterimBounds.equals(mBoundsToAdjust)) {
mListener.boundaryChanged(mInterimBounds, mBoundsToAdjust);
}
}
|
0a90ba13-bd35-40f1-b04e-cc9e3639534b
| 0
|
@Override
public String toString() {
return StringUtil.concatenateStrings("Watcher: ", watchKey.toString());
}
|
0efe9ab4-6986-4a37-bac5-c86f28fd82ac
| 0
|
public Date getStart() {
return start;
}
|
99a6ecd2-ac73-498e-9d50-24625de80ff3
| 6
|
public void borrarElement(String dia, int hora, Element e) {
int i;
if (dia.equals("dilluns")) i = 0;
else if (dia.equals("dimarts")) i = 1;
else if (dia.equals("dimecres")) i = 2;
else if (dia.equals("dijous")) i = 3;
else if (dia.equals("divendres")) i = 4;
else if (dia.equals("dissabte")) i = 5;
else i = 6;
quadricula[i][hora].borrarElement(e);
}
|
bc5fd7ce-8220-422d-9d99-157ea2caf052
| 1
|
public void renderAll(){
render();
for (GameObject child: children){
child.renderAll();
}
}
|
de03ec3a-c9c8-4423-9029-bded6f4c4a14
| 5
|
public boolean actionPatrol(Actor actor, Target spot) {
//I.say("Patrolling to: "+spot) ;
if (actor.base() != null) {
final IntelMap map = actor.base().intelMap ;
map.liftFogAround(spot, actor.health.sightRange() * 1.207f) ;
}
//
// If you're on sentry duty, check whether you need to stand watch.
if (type == TYPE_SENTRY_DUTY) {
if (postTime == -1) postTime = actor.world().currentTime() ;
final float spent = actor.world().currentTime() - postTime ;
if (spent < WATCH_TIME) return false ;
else postTime = -1 ;
}
//
// If not, head on to the next stop on your patrol route-
final int index = patrolled.indexOf(onPoint) + 1 ;
if (index < patrolled.size()) {
onPoint = (Boardable) patrolled.atIndex(index) ;
}
else {
onPoint = null ;
}
return true ;
}
|
6d9cc022-2061-4c97-bff3-bb9ea5255b68
| 3
|
public void useFuel(int amount) {
if((amount <= fuelLevel) && (amount > 0) && !infinite) {
fuelLevel -= amount;
}
}
|
2f2b8932-80e1-4067-9f22-a01434980c08
| 2
|
public void inorderPrint( )//LNR
{
if (left != null)
{
left.inorderPrint( );
}
System.out.println(data);
if (right != null)
{
right.inorderPrint( );
}
}
|
d8626374-e9f4-494b-bfe5-18b8889d392f
| 2
|
public static AudioInputStream toAudioInputStream(
double[] audioData,
float sampleRate )
{
int m = audioData.length;
AudioFormat format = new AudioFormat(sampleRate, 16, 1, true, false);
// build byte array
byte[] byteArray = new byte[m * 2];
int val;
for ( int i = 0; i < m; ++i )
{
val = (int)(audioData[i] * Short.MAX_VALUE);
if ( val < 0 )
{
val = -val - 1;
byteArray[i * 2] = (byte)(~(val & 255));
byteArray[i * 2 + 1] = (byte)(~(val >> 8));
}
else
{
byteArray[i * 2] = (byte)(val & 255);
byteArray[i * 2 + 1] = (byte)(val >> 8);
}
}
AudioInputStream audioStream =
new AudioInputStream(new ByteArrayInputStream(byteArray), format, m);
return(audioStream);
}
|
ac60fe9f-7947-4c65-903c-e6dc769c6525
| 8
|
public static void main(String[] args) {
try {
MainMenuUI mainMenu = new MainMenuUI();
boolean exit = false;
while (!exit) {
int option = mainMenu.firstMenu();
switch (option) {
case 1:
createInfo();
break;
case 2:
editInfo();
break;
case 3:
doLogin();
break;
case 4:
searchProductsByCategory();
break;
case 5:
searchProductByName();
break;
case 0:
exit = true;
break;
}
}
} catch (Exception e) {
LOGGER.error(e);
ExceptionUI.printUncontrolledException(e);
}
}
|
ed8db953-5f3f-4b06-a022-2061f185b141
| 1
|
private double getMatchFactor(int index){
double matchFactor = 0;
int j = 1;
for (int i = index; i < index+7; i++){
double velocityDiff = this.log.get(i).getVelocity() - this.pattern.get(j).getVelocity();
double logHeadingDelta = this.log.get(i).getHeadingRadians() - this.log.get(i-1).getHeadingRadians();//watch for array bounds
double patternHeadingDelta = this.log.get(i).getHeadingRadians() - this.log.get(i-1).getHeadingRadians();//watch for array bounds
double headingDiff = logHeadingDelta - patternHeadingDelta;
matchFactor += velocityDiff + headingDiff;
j++;
}
return matchFactor;
}
|
26f8a8cc-cc0f-4a08-b8b4-8f365ea0834b
| 8
|
private String buildMyUrl(String apilink, String link, int out, String nastavka)
{
StringBuffer urlBuilder = new StringBuffer();
urlBuilder.append(apilink);
urlBuilder.append("format=").append(out==Constants.JSON_FORMAT? "json" :
out==Constants.PLAIN_TEXT_FORMAT? "plaintext" : out==Constants.XML_FORMAT? "xml"
: out == Constants.QR_FORMAT ? "qr" : "json");
if(mApiKey!=null && mUser!=null)
urlBuilder.append("&korisnik=").append(mUser).append("&apikey=").append(mApiKey);
if(nastavka!=null && nastavka.length()>0)
urlBuilder.append("&nastavka=").append(nastavka);
urlBuilder.append("&link=").append(link);
return urlBuilder.toString();
}
|
a4e0c168-59dc-4ea2-827a-8f18930ca8f0
| 8
|
public void tick() {
if (input.menu.clicked) game.setMenu(null);
if (input.up.clicked) selected--;
if (input.down.clicked) selected++;
int len = player.inventory.items.size();
if (len == 0) selected = 0;
if (selected < 0) selected += len;
if (selected >= len) selected -= len;
if (input.attack.clicked && len > 0) {
Item item = player.inventory.items.remove(selected);
player.activeItem = item;
game.setMenu(null);
}
}
|
4e35d748-2f6f-4998-bd6a-cc8b414e4e4e
| 4
|
private void dropAlarm() {
BufferedReader in;
try {
AlarmListViewHelper helper = (AlarmListViewHelper) dropAlarmComboBox.getSelectedItem();
if(helper == null)
return;
Alarm a = helper.getAlarm();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
dos.writeBytes(ServerFrame.dropAlarmCmd + "\n");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(a);
String cmd = in.readLine();
if(cmd.equals(ServerFrame.acceptCmd)) {
return;
} else if(cmd.equals(ServerFrame.failCmd)) {
JOptionPane.showConfirmDialog(this, "Can't drop this alarm.", "Warning", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE);
} else {
throw new Exception();
}
} catch(Exception e) {
e.printStackTrace();
}
}
|
528e7b5d-0806-409f-ac49-095d0ca8e76b
| 7
|
public void actionPerformed(ActionEvent arg0)
{
if (((JButton) arg0.getSource()).getText().compareTo("start") == 0)
{
player.setReady(true);
}
else if (((JButton) arg0.getSource()).getText().compareTo("pause") == 0)
{
player.rest();
}
else if (((JButton) arg0.getSource()).getText().compareTo("restart") == 0)
{
try {
resetGame();
} catch (Exception e) {
e.printStackTrace();
}
}
else if (((JButton) arg0.getSource()).getText().compareTo("save") == 0)
{
System.out.println("Save button pressed");
try {
Game.saveGame();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
System.out.println("Save tried");
}
}
|
80128e9e-a7a9-4fdc-9ed6-1772e916f63c
| 3
|
private boolean verifyAddress(String address){
char[] charAdd = address.toCharArray();
char[] invalid = new char[]{'(', ')', '{', '}', '$', ';', '@', ':', '#', '%', '<', '>', '§'};
for (int i=0; i<address.length(); i++) {
for (char anInvalid : invalid) {
if (charAdd[i] == anInvalid) {
label.setText(" Invalid character");
return false;
}
}
}
return true;
}
|
a3c9157a-2b4a-4aaf-8023-fb5b492bdb3e
| 7
|
@Override
public Solution solve(Graph graph, long time, long duration) {
// return newGreedy(graph, time, duration);
int n = graph.getNodes();
Solution solution = new Solution(n);
if (n == 2) {
solution.path = new short[] {0, 1};
return solution;
}
if (n == 1) {
solution.path = new short[] {0};
return solution;
}
boolean[] used = new boolean[n];
short best;
short startNode = 0;
used[startNode] = true;
short curNode = startNode;
for (int j = 0; j < n; j++) {
int i;
best = curNode;
for (i = 0; i < n; i++) {
if (!used[i] &&
(graph.distances[curNode][i] < graph.distances[curNode][best] || best == curNode))
best = (short)i;
}
used[best] = true;
solution.path[curNode] = best;
curNode = best;
}
solution.path[curNode] = startNode;
// int startValue = 0;
//// Random random = new Random();
//// solution.path[0] = 0;
//// solution.path[0] = (short) random.nextInt(n);
//// System.err.println("Path start: " + solution.path[0]);
//
//
//
//
// solution.set((short)startValue, 0); //[0] = (short) startValue;
// used[startValue] = true;
//
// for (int i = 1; i < n; i ++) {
// best = -1;
// for (short j = 0; j < n; j ++) {
// if (!used[j] && (best == -1 || graph.distances[solution.path[i-1]][j] < graph.distances[solution.path[i-1]][best])) {
//
// best = j;
// }
// }
// solution.set(best, i);
// //solution.path[i] = best;
// used[best] = true;
//
// }
return solution;
}
|
35786c46-0ee6-486a-8969-b1dcfcdc3acf
| 6
|
public static ListNode reverseKGroup(ListNode head, int k) {
if (head==null||k<=1){
return head;
}
ListNode superHead = new ListNode(0);
superHead.next=head;
ListNode check = head;
ListNode insert = superHead;
int count = 1;
ArrayList<ListNode> nodeArray = new ArrayList<ListNode>();
while(check!=null){
if(count < k) {
nodeArray.add(check);
check = check.next;
count++;
}
else if (count == k) {
ListNode nextNode = check.next;
insert.next = check;
insert = insert.next;
for(int i = nodeArray.size()-1;i>=0;i--){
insert.next = nodeArray.get(i);
insert = insert.next;
}
insert.next = nextNode;
nodeArray.clear();
check = nextNode;
count=1;
}
}
return superHead.next;
}
|
787accc0-cbfa-491d-af56-736da95396e2
| 3
|
public static Map<String, Object> getPrimaryKey(Object obj)
throws Exception {
Map<String, Object> attrs = new HashMap<String, Object>();
String pkName = null;
for (Field field : obj.getClass().getDeclaredFields()) {
Annotation[] annotations = field.getDeclaredAnnotations();
if (annotations.length > 0
&& Id.class.equals(annotations[0].annotationType())) {
pkName = field.getName();
break;
}
}
attrs.put("column", pkName);
String getterName = BeanUtils.getter(pkName);
Method getter = obj.getClass().getMethod(getterName);
attrs.put("value", getter.invoke(obj));
return attrs;
}
|
f9a12fec-76e2-4e3a-bf7e-c3918b39d0f4
| 7
|
public Modelo(Data data) throws IloException, FileNotFoundException {
this.data = data;
cplex = new IloCplex();
cplex.setOut(new PrintStream("./solution/" + data.filename + ".log"));
//decision variable y (integer)
y = new IloIntVar[data.nLinks];
for (int i = 0; i < data.nLinks; i++) {
Link link = data.links[i];
String varName = "y(" + link.sNode + "," + link.tNode + ")";
y[i] = cplex.intVar(0, link.capacity, varName);
//y[i] = cplex.intVar(0, Integer.MAX_VALUE, varName);
}
//flow cost
/*
IloLinearNumExpr cost = cplex.linearNumExpr();
for (int i = 0; i < data.nLinks; i++) {
Link link = data.links[i];
cost.addTerm(link.unitCost, y[i]);
}
cplex.addMinimize(cost);
*/
IloIntVar b = cplex.intVar(0, Integer.MAX_VALUE, "b");
cplex.addMaximize(b);
//flow conservation constraints
for (int n = 0; n < data.nNodes; n++) {
Node node = data.nodes[n];
IloLinearNumExpr constFlow = cplex.linearNumExpr();
for (int i = 0; i < data.nLinks; i++) {
Link link = data.links[i];
if (node.label == link.sNode) {
constFlow.addTerm(1, y[i]);
} else if (node.label == link.tNode) {
constFlow.addTerm(-1, y[i]);
}
}
if (node.label == 1) {
constFlow.addTerm(-1, b);
}
else if (node.label == 6) {
constFlow.addTerm(1, b);
}
cplex.addEq(constFlow, 0);
}
/*
//capacity constraints
for (int i = 0; i < data.nLinks; i++) {
Link link = data.links[i];
cplex.addLe(y[i], link.capacity);
}
*/
}
|
1e82f426-c473-4fea-abf9-682b0267482d
| 2
|
public void cargarProductos() {
try {
String sql = "SELECT * FROM productos";
Connection conn = Conexion.GetConnection();
PreparedStatement ps = conn.prepareStatement(sql);
pro = ps.executeQuery();
while (pro.next()) {
String[] row = {pro.getString(1), pro.getString(2), pro.getString(3), pro.getString(4), pro.getString(5), pro.getString(6)};
tmProd.addRow(row);
}
jTableProductos.setModel(tmProd);
} catch (SQLException e) {
JOptionPane.showMessageDialog(this, e.getErrorCode() + ": " + e.getMessage());
}
}
|
12204ac7-48df-4afd-a421-0155772cd2c7
| 7
|
public boolean stem() {
int v_1;
int v_2;
// (, line 464
// (, line 465
// call more_than_one_syllable_word, line 465
if (!r_more_than_one_syllable_word())
{
return false;
}
// (, line 466
// backwards, line 467
limit_backward = cursor; cursor = limit;
// (, line 467
// do, line 468
v_1 = limit - cursor;
lab0: do {
// call stem_nominal_verb_suffixes, line 468
if (!r_stem_nominal_verb_suffixes())
{
break lab0;
}
} while (false);
cursor = limit - v_1;
// Boolean test continue_stemming_noun_suffixes, line 469
if (!(B_continue_stemming_noun_suffixes))
{
return false;
}
// do, line 470
v_2 = limit - cursor;
lab1: do {
// call stem_noun_suffixes, line 470
if (!r_stem_noun_suffixes())
{
break lab1;
}
} while (false);
cursor = limit - v_2;
cursor = limit_backward; // call postlude, line 473
if (!r_postlude())
{
return false;
}
return true;
}
|
c46fd1ec-3d00-4438-8e0a-ab6d6fcbff15
| 7
|
@Override
protected void doLoadTestData(StdConverter.Operation oper, File dir) throws Exception
{
/* First of all, read in all the data, bind to in-memory object(s),
* and then (if read test), convert to the specific type converter
* uses.
*/
byte[] readBuffer = new byte[DEFAULT_BUF_SIZE];
ByteArrayOutputStream tmpStream = new ByteArrayOutputStream(DEFAULT_BUF_SIZE);
_totalLength = 0;
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".xml");
}
});
StdConverter<DbData> stdConverter = getStdConverter();
_readableData = (oper == StdConverter.Operation.WRITE) ?
null : new byte[files.length][];
_writableData = (oper == StdConverter.Operation.WRITE) ?
new DbData[files.length] : null;
for (int i = 0, len = files.length; i < len; ++i) {
File f = files[i];
// Read file contents, bind to in-memory object (using std conv)
readAll(f, readBuffer, tmpStream);
byte[] fileData = tmpStream.toByteArray();
DbData origData = (DbData) stdConverter.readData(new TestByteArrayInputStream(fileData));
if (_writableData != null) {
_writableData[i] = origData;
}
/* Then we better verify that we can round-trip content from
* object to native format and back: and if it comes back
* equal to original data, we are good to go.
*/
tmpStream.reset();
_converter.writeData(tmpStream, origData);
byte[] convData = tmpStream.toByteArray();
if (convData.length == 0) { // sanity check
throw new IllegalStateException("Converter "+_converter.getClass().getName()+" produced empty result");
}
if (_readableData != null) {
_readableData[i] = convData;
}
DbData convResults = (DbData)_converter.readData(new TestByteArrayInputStream(convData));
if (!convResults.equals(origData)) {
// Not very clean, but let's output for debugging:
System.err.println("Incorrect mapping");
System.err.println("Source xml: ["+origData+"]");
System.err.println("Using "+_converter+": ["+convResults+"]");
throw new IllegalStateException("Item #"+i+"/"+len+" differs for '"+_converter+"'");
}
}
}
|
a1dee203-abb9-449a-845a-1df792da9e1a
| 8
|
@Override
public Object esegui() throws ExtraTokenException, OperazioneNonValidaException, ParentesiParsingException, OperandoMissingException, ParsingException, OperatoreMissingException
{
Token stampa;
VarRepository variabili = VarRepository.getInstance();
ArrayList<Token> daStampareProvvisoria = (ArrayList<Token>)daStampare.clone();
for(int j=0;j<daStampareProvvisoria.size();j++)
if(daStampareProvvisoria.get(j).ritornaTipoToken().equals(Tok.VARIABILE))
{
String nome = (String)daStampareProvvisoria.get(j).ritornaValore();
Token valoreVariabile = variabili.getVariabile(nome);
if(!valoreVariabile.equals(null))
daStampareProvvisoria.set(j, valoreVariabile);
}
if(daStampareProvvisoria.size()==1)
{
if(daStampareProvvisoria.get(0).ritornaTipoToken().equals(Tok.STRINGA))
{
stampa = daStampareProvvisoria.get(0);
System.out.println(stampa.ritornaValore());
return null;
}
}
if(Condizione.isExprMatematica(daStampareProvvisoria))
{
ExprMatematica em = new ExprMatematica(daStampareProvvisoria);
stampa = em.getRisultato();
}
else if(Condizione.isExprBooleana(daStampareProvvisoria))
{
ExprBooleana eb = new ExprBooleana(daStampareProvvisoria);
stampa = eb.getRisultato();
}
else if(Condizione.isConfronto(daStampareProvvisoria))
{
Condizione cond = new Condizione(daStampareProvvisoria);
stampa = cond.getRisultato();
}
else throw new ParsingException();
System.out.println(stampa.ritornaValore());
return null;
}
|
f9413394-be18-4aaa-8395-a7be4de02bc5
| 2
|
public Object clone() {
TicTacToeBoard deepClone = new TicTacToeBoard();
for (int row = 0; row < TicTacToeBoard.SIZE; row++) {
for (int col = 0; col < TicTacToeBoard.SIZE; col++) {
deepClone.square[row][col] = this.square[row][col];
}
}
deepClone.turn = this.turn;
deepClone.numEmptySquares = this.numEmptySquares;
return deepClone;
}
|
a5cb703d-0a26-46e8-bb3e-f8af44cf84e5
| 9
|
public static void formatResults(ArrayList<Agent[]> generations, String file) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file, false));
} catch (IOException ex) {
ex.printStackTrace();
}
int gens = generations.size();
// header
for (int i = 0; i < gens; i++) {
try {
if (i == gens - 1)
writer.write("g" + i + "\n");
else
writer.write("g" + i + ",");
} catch (IOException ex) {
ex.printStackTrace();
}
}
int pop = generations.get(0).length;
for (int indiv = 0; indiv < pop; indiv++) {
// dados
for (int i = 0; i < gens; i++) {
Agent agent = generations.get(i)[indiv];
float fitness = agent.fitness;
try {
if (i == gens - 1)
writer.write(fitness + "\n");
else
writer.write(fitness + ",");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
try {
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
|
7ab9a3f8-8da1-46eb-adf3-02c2ebef2c7d
| 5
|
private Response sendLimitedRequest(String requestUrl, String requestBody)
{
//Lock to prevent multiple requests from executing at once
rateLock.lock();
try
{
//Wait (if required) for the request time limit
if(limiterEnabled)
{
try
{
if(requestQueueShort.size() == limitShort)
requestQueueShort.take();
if(requestQueueLong.size() == limitLong)
requestQueueLong.take();
}
catch(InterruptedException e)
{
// Dunno lol
}
}
//Send request
Response response = sendRequest(requestUrl, requestBody);
//Add a request locks
if(limiterEnabled)
{
requestQueueShort.add(new RequestLock(limitShortInterval));
requestQueueLong.add(new RequestLock(limitLongInterval));
}
return response;
}
finally
{
//Unlock to let the next request through
rateLock.unlock();
}
}
|
fde1083e-bd79-4a17-9aed-be682461dfd3
| 3
|
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
Transferable clipboardContent = getToolkit().getSystemClipboard().getContents(this);
if ((clipboardContent != null)
&& (clipboardContent.isDataFlavorSupported(DataFlavor.stringFlavor))) {
try {
String tempString;
tempString = (String) clipboardContent.getTransferData(DataFlavor.stringFlavor);
jTextField1.setText(tempString);
} catch (Exception e) {
e.printStackTrace();
}
}
}//GEN-LAST:event_jButton2ActionPerformed
|
8a66c1e9-678c-40c2-9c8d-168d2dce033a
| 3
|
@Override
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
DatabaseManager manager=DatabaseManager.getManager();
try {
ServletResult.sendResult(response, manager.getRoomDao()
.deleteById(Integer.parseInt(request.getParameter(ID)))==1 ?
ServletResult.SUCCESS
: ServletResult.ERROR);
} catch (NumberFormatException e) {
e.printStackTrace();
ServletResult.sendResult(response, ServletResult.BAD_NUMBER_FORMAT);
} catch (SQLException e) {
e.printStackTrace();
ServletResult.sendResult(response, ServletResult.ERROR);
}
}
|
bc6883f2-441f-488d-900e-29714de5ed61
| 5
|
private static int getCharWidth(char c) {
int charWidth = 5;
if(width5.indexOf(c) >= 0) {
charWidth = 5;
}
if(width4.indexOf(c) >= 0) {
charWidth = 4;
}
if(width3.indexOf(c) >= 0) {
charWidth = 3;
}
if(width2.indexOf(c) >= 0) {
charWidth = 2;
}
if(width1.indexOf(c) >= 0) {
charWidth = 1;
}
return charWidth;
}
|
030a360a-790e-4b54-9d8a-939142078316
| 1
|
@Test
public void testPlayerCapturesOneFlagAndLastPlayerBoxedIn() throws InvalidActionException {
final GameEnded gameEnded = new GameEnded();
game.addEventListener(new Listener() {
@Override
public void handleEvent(Event event) {
if(event.getType() == EventType.END_GAME)
gameEnded.setToTrue();
}
}, EventType.END_GAME);
// Player 1 moves 4 up
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
// Player 2 moves 4 down
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
// Player 3 moves 4 right
game.moveAction(Direction.RIGHT);
game.moveAction(Direction.RIGHT);
game.moveAction(Direction.RIGHT);
game.moveAction(Direction.RIGHT);
// Player 4 moves 4 up
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
// Player 1 moves 4 up
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
game.moveAction(Direction.UP);
// Player 2 boxes in Player 4
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.DOWN);
game.endTurnAction();
// Player 3 moves 1 right
game.moveAction(Direction.RIGHT);
game.endTurnAction();
// Player 1 picks up flag of Player 3
game.moveAction(Direction.UP);
game.pickUpAction(0);
game.moveAction(Direction.RIGHTDOWN);
game.moveAction(Direction.DOWN);
// Player 2 moves 1 right
game.moveAction(Direction.RIGHT);
game.endTurnAction();
// Player 3 moves 1 right
game.moveAction(Direction.RIGHT);
game.endTurnAction();
// Player 1 moves 4 down
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
// Player 2 moves 1 left down and 1 down
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.DOWN);
game.endTurnAction();
// Player 3 moves 1 down
game.moveAction(Direction.DOWN);
game.endTurnAction();
// Player 1 captures flag and teleports
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.DOWN);
game.moveAction(Direction.RIGHTUP);
// Player 2 boxes himself in
game.moveAction(Direction.DOWN);
game.moveAction(Direction.LEFTUP);
game.moveAction(Direction.LEFTDOWN);
game.moveAction(Direction.RIGHT);
// Player 3 moves 1 left
game.moveAction(Direction.LEFT);
game.endTurnAction();
// Player 1 moves 4 right up
game.moveAction(Direction.RIGHTUP);
game.moveAction(Direction.RIGHTUP);
game.moveAction(Direction.RIGHTUP);
game.moveAction(Direction.RIGHTUP);
// Player 2 should have been removed from the game
assertTrue(gameEnded.isTrue);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.