text stringlengths 14 410k | label int32 0 9 |
|---|---|
public boolean contains(DockLayoutNode node) {
if (node == this) {
return true;
}
for (DockLayoutNode child : mChildren) {
if (child == node) {
return true;
}
if (child instanceof DockLayout) {
if (((DockLayout) child).contains(node)) {
return true;
}
}
}
return false;
} | 5 |
public void setPos1(int val){ if (val == 1){p1 = true;} else { p1 = false; }} | 1 |
public static void main(String[] args) {
/* Use an appropriate Look and Feel */
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
//UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
} | 4 |
private void setGrid(Grid grid) {
if (grid == null)
throw new IllegalArgumentException("Grid can't be null!");
this.grid = grid;
} | 1 |
public static long unsignedInt (byte[] byteArray, int selector, int byteOrdering)
{
// byteOrdering tells how bytes are stored
// selector should always point to lowest byte position of range
// local vars
int a = 0 ;
// case out on the storage scheme
switch (byteOrdering) {
case HI_TO_LO: // aka BIG_ENDIAN
a = ((int) (byteArray[selector++] & 0xFF)) << 24;
a += ((int) (byteArray[selector++] & 0xFF)) << 16;
a += ((int) (byteArray[selector++] & 0xFF)) << 8;
a += ((int) (byteArray[selector] & 0xFF)) ;
break ;
case LO_TO_HI: // aka LITTLE_ENDIAN
a = ((int) (byteArray[selector++] & 0xFF)) ;
a += ((int) (byteArray[selector++] & 0xFF)) << 8;
a += ((int) (byteArray[selector++] & 0xFF)) << 16;
a += ((int) (byteArray[selector] & 0xFF)) << 24;
break ;
default:
break ;
} // end switch
// bye bye
return a ;
} // end method unsignedInt | 2 |
final public Identifier ValueIdentifier() throws ParseException {
ModuleIdentifier module;
Token dot_t;
NodeToken value;
Identifier identifier;
switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
case TYPE_IDENTIFIER_T:
module = ModuleIdentifier();
dot_t = jj_consume_token(DOT_T);
value = ValueExpansion();
identifier = Identifier.Value(module,
value);
break;
case CURRENT_T:
case DEPRECATED_T:
case OBSOLETE_T:
case MANDATORY_T:
case NOT_IMPLEMENTED_T:
case VALUE_IDENTIFIER_T:
value = ValueExpansion();
identifier = Identifier.Value(value);
break;
default:
jj_la1[53] = jj_gen;
jj_consume_token(-1);
throw new ParseException();
}
{if (true) return identifier;}
throw new Error("Missing return statement in function");
} | 9 |
private void addSearchPanel() {
Dimension inputDimension = Constants.getInputDimension();
Dimension dateDimension = Constants.getDateDimension();
searchPanel = new JPanel();
searchPanel.setBorder(new TitledBorder("查询条件"));
searchPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
JLabel jlId = new JLabel("还款单号");
searchPanel.add(jlId);
jtfId = new DigitalTextField();
jtfId.setPreferredSize(inputDimension);
jtfId.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
refreshData();
}
}
});
searchPanel.add(jtfId);
JLabel jlOid = new JLabel("销售单号");
searchPanel.add(jlOid);
jtfOid = new DigitalTextField();
jtfOid.setPreferredSize(inputDimension);
jtfOid.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
refreshData();
}
}
});
searchPanel.add(jtfOid);
JLabel jlIid = new JLabel("货号");
searchPanel.add(jlIid);
jtfIid = new DigitalTextField();
jtfIid.setPreferredSize(inputDimension);
jtfIid.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
refreshData();
}
}
});
searchPanel.add(jtfIid);
JLabel jlConsumer = new JLabel("买家");
searchPanel.add(jlConsumer);
jtfConsumer = new JTextField();
jtfConsumer.setPreferredSize(inputDimension);
jtfConsumer.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
refreshData();
}
}
});
String[] consumers = MyFactory.getConsumerService().listNames();
AutoCompleteExtender consumerAce = new AutoCompleteExtender(jtfConsumer, consumers, null);
consumerAce.setMatchDataAsync(true);
consumerAce.setSizeFitComponent();
consumerAce.setMaxVisibleRows(10);
consumerAce.setCommitListener(new AutoCompleteExtender.CommitListener() {
public void commit(String value) {
jtfConsumer.setText(value);
}
});
searchPanel.add(jtfConsumer);
JLabel jlFruit = new JLabel("货品");
searchPanel.add(jlFruit);
jtfFruit = new JTextField();
jtfFruit.setPreferredSize(inputDimension);
jtfFruit.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
refreshData();
}
}
});
String[] fruits = MyFactory.getFruitService().listNames();
AutoCompleteExtender fruitAce = new AutoCompleteExtender(jtfFruit, fruits, null);
fruitAce.setMatchDataAsync(true);
fruitAce.setSizeFitComponent();
fruitAce.setMaxVisibleRows(10);
fruitAce.setCommitListener(new AutoCompleteExtender.CommitListener() {
public void commit(String value) {
jtfFruit.setText(value);
}
});
searchPanel.add(jtfFruit);
JLabel jlCensored = new JLabel("审核状态");
searchPanel.add(jlCensored);
String censored[] = new String[]{"全部", "未审", "通过", "不通过"};
jcbCensored = new JComboBox(censored);
searchPanel.add(jcbCensored);
JLabel jlDateFrom = new JLabel("日期");
searchPanel.add(jlDateFrom);
DateChooser dateChooserFrom = DateChooser.getInstance("yyyy-MM-dd");
showDateFrom = new JTextField("开始日期");
showDateFrom.setPreferredSize(dateDimension);
dateChooserFrom.register(showDateFrom);
searchPanel.add(showDateFrom);
JLabel jlDateTo = new JLabel("—");
searchPanel.add(jlDateTo);
DateChooser dateChooserTo = DateChooser.getInstance("yyyy-MM-dd");
showDateTo = new JTextField("结束日期");
showDateTo.setPreferredSize(dateDimension);
dateChooserTo.register(showDateTo);
searchPanel.add(showDateTo);
JButton searchBtn = new JButton("查询");
searchBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
refreshData();
}
});
searchPanel.add(searchBtn);
gridX = 0; // X0
gridY = 0; // Y0
gridWidth = 1; // 横占一个单元格
gridHeight = 1; // 列占三个单元格
weightX = 1.0; // 当窗口放大时,长度随之放大
weightY = 0.0; // 当窗口放大时,高度随之放大
anchor = GridBagConstraints.NORTH; // 当组件没有空间大时,使组件处在北部
fill = GridBagConstraints.BOTH; // 当有剩余空间时,填充空间
insert = new Insets(0, 0, 0, 10); // 组件彼此的间距
iPadX = 0; // 组件内部填充空间,即给组件的最小宽度添加多大的空间
iPadY = 35; // 组件内部填充空间,即给组件的最小高度添加多大的空间
gbc = new GridBagConstraints(gridX, gridY, gridWidth, gridHeight, weightX, weightY, anchor,
fill, insert, iPadX, iPadY);
gbl.setConstraints(searchPanel, gbc);
this.add(searchPanel);
} | 5 |
public static boolean isWhitespace(String str)
{
if (str == null)
{
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++)
{
if ((Character.isWhitespace(str.charAt(i)) == false))
{
return false;
}
}
return true;
} | 3 |
@Override
public synchronized void run() {
try{
while (true){
while (ch1.isEmpty()||!ch2.isEmpty()){
wait();
} // Wait for something to do
val=int_receive();
while (numberOfRepetitionAndLost < maxError){
Random random = new Random();
int randomInt = random.nextInt(3); // randomInt gets the values 0, 1 and 2 which
int safeInt = 0;
// correspond to losing, duplicating or properly sending messages
switch (safeInt) {
case 0: // Send normally
int_send(val);
numberOfRepetitionAndLost= maxError; //now, you will not continue in while-loop
break;
case 1: // Lose the message, i.e, the message is not delivered
numberOfRepetitionAndLost++;
break;
case 2: // Duplicate the message
int_send(val);
numberOfRepetitionAndLost++;
break;
}
while (!ch2.isEmpty()){
wait();
} // if message is sent, wait for receiver before looping
}
numberOfRepetitionAndLost = 0; // reset for next message
}
} catch (Exception e){}
} | 9 |
public boolean initialize(ArrayList<String> in) {
assert (in != null) : "Cannot initialize with a null list";
assert (tokens == null) : "Cannot reinitialize EnglishNumber";
assert (in.size() != 0) : "Cannot accept an empty arraylist";
if (in == null)
{
em.error("Cannot initialize a null list");
return false;
}
if (tokens != null){
em.error("Cannot reinitialize EnglishNumber");
return false;
}
if (in.size() == 0){
em.error("No tokens to parse.");
return false;
}
// Tokenize input
tokens = toTokens(in);
if (tokens == null){
return false;
}
position = 0;
// Parse
boolean result = parse();
if (!result){
tokens = null;
return false;
}
// Success! Cache as int
numericValue = interpetAsInt();
return true;
} | 5 |
@Override
public String getConnectionsString() {
String result = "";
for (Iterator<ISocketServerConnection> it = getConnections().iterator(); it.hasNext();) {
ISocketServerConnection ssc = it.next();
if (result.isEmpty()) {
result = new Long(ssc.getIdConnection()).toString();
}
else {
result = result + ", " + ssc.getIdConnection();
}
}
return result;
} | 2 |
public void setName( String name )
{
if( cxnSp != null )
{
cxnSp.setName( name );
}
else if( sp != null )
{
sp.setName( name );
}
else if( pic != null )
{
pic.setName( name );
}
else if( graphicFrame != null )
{
graphicFrame.setName( name );
}
else if( grpSp != null )
{
grpSp.setName( name );
}
} | 5 |
private void createAndAddApplicationToSystemTray() throws IOException {
// Check the SystemTray support
if (!SystemTray.isSupported()) {
System.out.println("SystemTray is not supported");
return;
}
Image image = new ImageIcon("").getImage();
final TrayIcon trayIcon = new TrayIcon(image, TOOL_TIP);
this.processTrayIcon = trayIcon;
ApiProperties.get().setToken(DbReader.getToken(processTrayIcon));
final SystemTray tray = SystemTray.getSystemTray();
final PopupMenu popup = new TrayMenu(tray, trayIcon);
trayIcon.setPopupMenu(popup);
trayIcon.setImageAutoSize(true);
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.out.println("TrayIcon could not be added.");
return;
}
// Add listener to trayIcon.
trayIcon.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This dialog box is run from System Tray");
}
});
} | 2 |
private void drawBeastRadius(GOut g) {
String name;
g.chcolor(255, 0, 0, 96);
synchronized (glob.oc) {
for (Gob tg : glob.oc) {
name = tg.resname();
if ((tg.sc != null)
&& (!name.contains("/cdv"))
&& ((name.contains("kritter/boar")) || (name.contains("kritter/bear")))) {
drawradius(g, tg.sc, 100);
}
}
}
g.chcolor();
} | 5 |
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
List<Usuario> us = new Conectar().ConexionUs();
Usuario u = new Usuario();
String s = null;
try {
s = new UseUser().GetUser();
} catch (Exception ex) {
Logger.getLogger(Ventas.class.getName()).log(Level.SEVERE, null, ex);
}
for(Usuario u1 : us){
StringBuffer st = new StringBuffer(u1.getName());
st.setLength(30);
u1.setName(st.toString());
if(u1.getName().equalsIgnoreCase(s)){
u = u1;
}
}
dispose();
if(u.isAdministrador()){
new MenuMain().Call();
}else{
new MenuEmpleado().Call();
}
}//GEN-LAST:event_jButton1ActionPerformed | 4 |
public void addRoom(String showName, String dei, Room room){
Days day = Days.valueOf(dei);
int d = day.ordinal();
for (Show show : days[d].getShows()) { //iter the shows of that day
if (!show.getName().equals(showName)){ //see if there is a show with tha correct name
for (Room room1 : show.getRooms()) { //iter the rooms of the given show
if (!room1.getName().equals(room.getName())) { //see if there is a room with the same name
show.addRoom(room);
}
}
}
}
} | 4 |
@Override
public int fight() {
return super.fight();
} | 0 |
boolean isImportTaxApplicable(String sItem)
{
if(sItem.contains("import"))
return true;
return false;
} | 1 |
public void startup(Window window) {
this.window = window;
csvLoadCard.init(this);
serializationLoadCard.init(this);
manualSetupCard.init(this);
scrapeInfoCard.init(this);
setupBatteriesCard.init(this);
if (StartupSequence.checkForSerializedData()) {
CardLayout cl = (CardLayout) (getLayout());
cl.show(this, "serializationLoadCard");
} else if (StartupSequence.checkIfCSVDataExists()) {
CardLayout cl = (CardLayout) (getLayout());
cl.show(this, "csvLoadCard");
} else {
CardLayout cl = (CardLayout) (getLayout());
cl.show(this, "scrapeInfoCard");
}
} | 2 |
@EventHandler(priority = EventPriority.HIGH)
public void playerPickUpItem(PlayerPickupItemEvent e) {
if(e.getItem().getItemStack().equals(new ItemStack(Material.SKULL_ITEM, 1))) {
for(TTEnTGame game: TTEnTMain.activeGames) {
for(IngamePlayer p: game.players) {
e.getItem().getLocation().equals(p.getSpawnHeadLocation());
p.getRep().sendMessage("Player " + e.getPlayer().getName() + " has picked up your skull and is bringing it back to ressurect you.");
e.getPlayer().sendMessage("You have picked up " + p.getRep().getName() + "'s skull. Bring it back to spawn to ressurect them.");
int i = 0;
for(ResPlayer r: skullHolders) {
if(r.equals(e.getPlayer())) {
skullHolders.get(i).addRes(p.getRep());
}
i++;
}
}
}
}
} | 5 |
public double nota()
{
double acum =0;
for(RespuestaAlumno respuesta: respuestas)
{
acum = acum + this.puntaje(respuesta);
}
double laNota = acum*10/this.puntajeTotal();
return(laNota);
} | 1 |
public String getName() {
return name;
} | 0 |
public void reorderList(ListNode head){
if(head != null && head.next != null){
ListNode slow = head;
ListNode fast = head;
while(fast!=null && fast.next!=null&&fast.next.next!=null){
slow = slow.next;
fast=fast.next.next;
}
ListNode second = slow.next;
slow.next = null;
second = reverseOrder(second);
ListNode list1 = head;
ListNode list2 = second;
while(list2!=null){
ListNode temp1 = list1.next;
ListNode temp2 = list2.next;
list1.next = list2;
list2.next = temp1;
list1 = temp1;
list2 = temp2;
}
}
} | 6 |
* @return The column, or <code>null</code> if none is found.
*/
public Column overColumnDivider(int x) {
int pos = getInsets().left;
int count = mModel.getColumnCount();
for (int i = 0; i < count; i++) {
Column col = mModel.getColumnAtIndex(i);
if (col.isVisible()) {
pos += col.getWidth() + (mDrawColumnDividers ? 1 : 0);
if (x >= pos - DIVIDER_HIT_SLOP && x <= pos + DIVIDER_HIT_SLOP) {
return col;
}
}
}
return null;
} | 5 |
public void damage(Vector2f lineStart, Vector2f lineEnd, Vector2f nearestIntersection)
{
Vector2f nearestBotIntersect = null;
Enemies nearestBot = null;
for (Enemies enemies : enemises)
{
Vector2f colVector = Game.getLevel().lineInterSectRect(lineStart, lineEnd, new Vector2f(enemies.getTransform().getTranslation().getX(), enemies.getTransform().getTranslation().getZ()), enemies.getSize());
@SuppressWarnings("unused")
Vector2f lastBotIntersect = nearestBotIntersect;
nearestBotIntersect = Game.getLevel().findNearestIntesection(nearestBotIntersect, colVector, lineStart);
if(nearestBotIntersect == colVector)
{
nearestBot = enemies;
}
}
if(nearestBotIntersect != null && (nearestIntersection == null ||
nearestBotIntersect.sub(lineStart).length() < nearestIntersection.sub(lineStart).length()))
{
if (nearestBot.state != Enemies.STATE_DEAD) {
nearestBot.getMaterial().setTexture(nearestBot.getTextures().get(7));
if(nearestBot != null)
nearestBot.damage(Game.getLevel().getPlayer().getDamage());
} else
{
enemises.remove(nearestBot);
}
}
} | 7 |
public Speaker findSpeakerById(final Long id) {
return new Speaker();
} | 0 |
private static void addMetadata( OtuWrapper wrapper, File inFile, File outFile,
boolean fromR) throws Exception
{
HashMap<String, Integer> caseControlMap = getCaseControlMap();
BufferedReader reader = new BufferedReader(new FileReader(inFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outFile));
writer.write("id\tkey\treadNum\tisBlankControl\tnumberSequencesPerSample\tshannonEntropy\tcaseContol\tset\tread");
String[] firstSplits = reader.readLine().split("\t");
int startPos = fromR ? 0 : 1;
for( int x=startPos; x < firstSplits.length; x++)
writer.write("\t" + firstSplits[x]);
writer.write("\n");
for(String s = reader.readLine(); s != null; s= reader.readLine())
{
String[] splits = s.split("\t");
String key = splits[0].replaceAll("\"", "");
writer.write(key+ "\t" + key.split("_")[0] + "\t" + getReadNum(key) + "\t" +
( key.indexOf("DV-000-") != -1) + "\t" +
wrapper.getNumberSequences(key)
+ "\t" + wrapper.getShannonEntropy(key) + "\t" );
Integer val = caseControlMap.get( new StringTokenizer(key, "_").nextToken());
if( val == null)
writer.write("NA\t");
else
writer.write("" + val + "\t");
String set = "";
if( splits[0].indexOf("set1") != -1)
set = "set1";
else if( splits[0].indexOf("set3") != -1)
set = "set3";
else throw new Exception("No");
writer.write(set + "\t");
writer.write( Integer.parseInt(key.split("_")[1]) + "");
for( int x=1; x < splits.length; x++)
writer.write("\t" + splits[x]);
writer.write("\n");
}
writer.flush(); writer.close();
reader.close();
} | 7 |
private DataModel loadFromFile(File pathToFile) {
DataModel dm = null;
if (pathToFile != null) {
ObjectInputStream ois = null;
if (pathToFile.exists()) {
try {
ois = new ObjectInputStream(new FileInputStream(pathToFile));
dm = (DataModel)ois.readObject();
} catch (Exception ex) {
Logger.getLogger(SaveModel.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
try {
if (ois != null) ois.close();
} catch (IOException ex) {
Logger.getLogger(SaveModel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
return dm;
} | 5 |
public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
JSONArray ja = new JSONArray();
for (;;) {
String value = getValue(x);
if (value == null) {
return null;
}
ja.put(value);
for (;;) {
char c = x.next();
if (c == ',') {
break;
}
if (c != ' ') {
if (c == '\n' || c == '\r' || c == 0) {
return ja;
}
throw x.syntaxError("Bad character '" + c + "' (" +
(int)c + ").");
}
}
}
} | 8 |
protected final void setTComponentContainer(TComponentContainer componentContainer)
{
if (tComponentContainer != componentContainer)
{
if (tComponentContainer != null)
{
tComponentContainer.getParent().removeMouseListener(this);
tComponentContainer.getParent().removeMouseMotionListener(this);
if (usingScrollBar == true)
tComponentContainer.removeTComponent(scrollBar);
for (TButton b : tButtons)
b.listenerList = new EventListenerList();
}
tComponentContainer = componentContainer;
tComponentContainer.getParent().addMouseListener(this);
tComponentContainer.getParent().addMouseMotionListener(this);
ActionListener[] listeners = tComponentContainer.getEventListeners();
for (ActionListener listener : listeners)
for (TButton b : tButtons)
b.addActionListener(listener);
if (usingScrollBar == true)
tComponentContainer.addTComponent(scrollBar);
}
} | 7 |
public boolean bishopMove(int startRow, int startCol, int endRow, int endCol)
{
Piece piece = checker[startRow][startCol];
Piece endTile = checker[endRow][endCol];
if(endTile == null || endTile.alligence != piece.alligence) //only move or move and attack
{
if(Math.abs(endCol-startCol) == Math.abs(endRow-startRow)) //diagonal movement
{
int colIndexPar; //horizontal direction
if(endCol>startCol)
{
colIndexPar = 1;
}
else
{
colIndexPar = -1;
}
int rowIndexPar; //vertical direction
if(endRow>startRow)
{
rowIndexPar = 1;
}
else
{
rowIndexPar = -1;
}
for(int i=1; i<Math.abs(endCol-startCol); i++) //check for free path
{
if(checker[startRow+i*rowIndexPar][startCol+i*colIndexPar] != null)
{
return false;
}
}
return true;
}
else //illegal movement
{
return false;
}
}
else //tile occupied by ally
{
return false;
}
} | 7 |
public void dump(String prefix) {
System.out.println(toString(prefix));
if (children != null) {
for (int i = 0; i < children.length; ++i) {
SimpleNode n = (SimpleNode)children[i];
if (n != null) {
n.dump(prefix + " ");
}
}
}
} | 3 |
protected void openXmlPng(BasicGraphEditor editor, File file)
throws IOException
{
Map<String, String> text = mxPngTextDecoder
.decodeCompressedText(new FileInputStream(file));
if (text != null)
{
String value = text.get("mxGraphModel");
if (value != null)
{
Document document = mxXmlUtils.parseXml(URLDecoder.decode(
value, "UTF-8"));
mxCodec codec = new mxCodec(document);
codec.decode(document.getDocumentElement(), editor
.getGraphComponent().getGraph().getModel());
editor.setCurrentFile(file);
resetEditor(editor);
return;
}
}
JOptionPane.showMessageDialog(editor,
mxResources.get("imageContainsNoDiagramData"));
} | 2 |
public static RoutingMessage getRoutingMessage(ByteBuffer buffer) {
int headerSize = buffer.getInt();
// header
Map<String, String> header = null;
if (headerSize > 0) {
header = new HashMap<>();
for (int i = 0; i < headerSize; i++) {
String key = readString(buffer);
String value = readString(buffer);
header.put(key, value);
}
}
//body
int bodyLen = buffer.getInt();
byte[] bodyMessage = new byte[bodyLen];
buffer.get(bodyMessage);
//tags
int tagLen = buffer.getInt();
String[] tags = new String[tagLen];
for (int i = 0; i < tagLen; i++) {
tags[i] = readString(buffer);
}
return new RoutingMessage(header, bodyMessage, tags);
} | 3 |
private void establishConnection(String url, boolean willRetryOnFailure) throws SQLException
{
if (!isEncryptionEnabled())
jdbc = DriverManager.getConnection(url);
else if (0 == encryptionPassword.length)
throw new IllegalStateException(
"The password is no longer available. Please set the password again before reconnecting.");
else
{
Throwable status = null;
final int length = encryptionPassword.length;
final char[] passwordCopy = new char[length + 1];
try
{
int errorPos = copyPassword(passwordCopy, encryptionPassword);
if (0 <= errorPos)
throw new IllegalArgumentException(
"Character code " + (int)encryptionPassword[errorPos]
+ " is not allowed in a password, but found at position " + errorPos);
passwordCopy[length] = ' ';
// prepare the file password
Properties properties = new Properties();
// this violates the Properties contract, but does not leave copies of password in memory
properties.put("password", passwordCopy);
jdbc = DriverManager.getConnection(url, properties);
}
catch (Throwable failure)
{
status = failure;
if (failure instanceof Error)
throw (Error)failure;
if (failure instanceof SQLException)
throw (SQLException)failure;
if (failure instanceof RuntimeException)
throw (RuntimeException)failure;
throw new Error("Unexpected object type thrown while connecting to \"" + url + '"', failure);
}
finally
{
Arrays.fill(passwordCopy, '\0');
if (!willRetryOnFailure || null == status)
clearPassword();
}
}
} | 9 |
public byte[] getData() {
if(tmpData != null) {
if(data == null || tmpData.size() != data.length) {
data = tmpData.toByteArray();
}
}
return data;
} | 3 |
private void AddNodeToQueue( CommandNode node )
throws CreateCMDTreeErrorException
{
if ( SwitchStack.empty() )
{
if ( IfStack.empty() && WhileStack.empty() )
{
__AddNodeToQueue__( CMDTree, node );
}
else
{
RTTestLog.logToConsole( "Stack Error.", LogCollector.ERROR );
CreateCMDTreeErrorException exception = new CreateCMDTreeErrorException(
"栈错误,缺少endif或者endwhile.\n" );
throw exception;
}
}
else
{
if ( SwitchStack.peek() == SWITCHIFSTACK
&& IfStack.empty() != true ) // 当前栈为IF栈,并且栈非空
{
CommandNode LastIfNode = IfStack.peek();
if ( LastIfNode.Switch == true ) // if条件成立语句块
{
__AddNodeToQueue__( LastIfNode.TrueCmdTree, node );
}
else
// else后if条件语句块
{
__AddNodeToQueue__( LastIfNode.FalseCmdTree, node );
}
}
else
{
if ( SwitchStack.peek() == SWITCHWHILESTACK
&& WhileStack.empty() != true ) // 当前栈为WHILE栈,并且栈非空
{
CommandNode LastWhileNode = WhileStack.pop();
__AddNodeToQueue__( LastWhileNode.TrueCmdTree, node );
WhileStack.push( LastWhileNode );
}
else
{
RTTestLog
.logToConsole(
"ERROR in Making CommandTree. Wrong StackSwitch.",
LogCollector.ERROR );
CreateCMDTreeErrorException exception = new CreateCMDTreeErrorException(
"while栈错误,缺少endwhile\n" );
throw exception;
}
}
}
} | 8 |
@Override
public void endTransaction() {
if(commit()){
this.transaction = false;
}
} | 1 |
public int countPlayerPoints(int player)
{
int points = 0;
for (int[] row : board)
{
for (int value : row)
{
if(value == W && player == W)
{
points++;
}
else if(value == B && player == B)
{
points++;
}
}
}
return points;
} | 6 |
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 0;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 0;
}
if (key == KeyEvent.VK_UP) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
} | 4 |
@GET
@Path("/{repoName}")
@Produces(MediaType.APPLICATION_JSON)
public String getRepositoryFiles(
@PathParam("repoName") String repoName,
@Context HttpServletRequest request) {
RepositoryVm repositoryVm;
Gson gson = new Gson();
if (StringUtils.isEmpty(repoName)) {
repositoryVm = new RepositoryVm();
repositoryVm.setErrorMessage("You must provide a repository name.");
return gson.toJson(repositoryVm);
}
try {
repositoryVm = dao.getRepoFiles(repoName, getBaseUrl(request));
}
catch (NotFoundException e) {
logger.log(Level.WARNING, e.getMessage(), e);
repositoryVm = new RepositoryVm();
repositoryVm.setErrorMessage("Could not find repository " + repoName + ".");
}
catch (IOException e) {
logger.log(Level.SEVERE, "Failed to load repo file list: {0}", e.getMessage());
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
}
return gson.toJson(repositoryVm);
} | 3 |
private void printAddUser() throws IOException {
String s, username = null, password = null;
printMenu(PrintMenuName.ADD_USER);
while (true) {
s = br.readLine();
System.out.println(s);
if (s.equals("b")) break;
else if (s != null) {
if (username == null) username = s;
else {
password = s;
try {
userService.createNewUser(username, password);
System.out.println("New user is added");
} catch (MyEmptyUserNameException e) {
System.out.println(e.getMessage());
} catch (MyEmptyPasswordException e) {
System.out.println(e.getMessage());
} catch (MyUserAlreadyExistException e) {
System.out.println(e.getMessage());
} finally {
username = null;
printMenu(PrintMenuName.ADD_USER);
}
}
}
}
printMenu(PrintMenuName.MAIN_MENU);
} | 7 |
public static AbstractModel getRandomGrid(int min, int max, int distance,AbstractModel result) {
// AbstractModel result = new ModelParallel();
Random r = new Random(1);
for (int i = min; i < max; i += distance) {
for (int j = min; j < max; j += distance) {
result.p.add(new Particle(0.5, 0, 0, i + 0.5 - r.nextDouble(),
j + 0.5 - r.nextDouble()));
}
}
return result;
} | 2 |
public static ArrayList<Integer> primeNumbers(int n) {
if (n < 2)
return new ArrayList<Integer>();
isPrime = new boolean[n];
char[] is_composite = new char[(n - 2 >> 5) + 1];
final int limit_i = n - 2 >> 1, limit_j = 2 * limit_i + 3;
ArrayList<Integer> results = new ArrayList<Integer>(
(int) Math.ceil(1.25506 * n / Math.log(n)));
results.add(2);
isPrime[2] = true;
for (int i = 0; i < limit_i; ++i)
if ((is_composite[i >> 4] & 1 << (i & 0xF)) == 0) {
results.add(2 * i + 3);
isPrime[2 * i + 3] = true;
for (long j = 4L * i * i + 12L * i + 9; j < limit_j; j += 4 * i + 6)
is_composite[(int) (j - 3L >> 5)] |= 1 << (j - 3L >> 1 & 0xF);
}
return results;
} | 4 |
@Test
public void minimalTest()
throws Exception
{
Thread.sleep( 5000 );
assertTrue( this.timedTask.getInvocationsTimedTaskA() > 0 );
} | 0 |
public static void main(String[] args) {
ServerSocket server;
final int DAYTIME_PORT = 1300;
Socket socket;
try {
server = new ServerSocket(DAYTIME_PORT);
do {
socket = server.accept();
PrintWriter output = new PrintWriter(socket.getOutputStream(),
true);
Date date = new Date();
output.println(date);
// method toString executed in live above
socket.close();
System.exit(0);
} while (true);
} catch (IOException e) {
System.out.println(e);
}
} | 2 |
private static void readFromFile() {
filepath = JOptionPane
.showInputDialog("Enter the file path of the file you wish to read from:");
try {
File f = new File(filepath);
Scanner sc = new Scanner(f);
while (sc.hasNextLine()) {
String name = sc.nextLine();
String title = sc.nextLine();
ArrayList<Task> unfinishedTasks = new ArrayList<Task>();
String task = sc.nextLine();// skip blank line
task = sc.nextLine();// start of current tasks; blank if none
if (!task.equals("")) {
while (!task.equals("")) {
Task newTask = new Task(task);
unfinishedTasks.add(newTask);
task = sc.nextLine();// blank line
}// end while
} else {
task = sc.nextLine();// blank line
}// end if-else
task = sc.nextLine();// start of completed tasks; blank if none
ArrayList<Task> finishedTasks = new ArrayList<Task>();
if (!task.equals("")) {
while (!task.equals("")) {
Task newTask = new Task(task, true);
finishedTasks.add(newTask);
task = sc.nextLine();// blank line
}// end while
} else {
task = sc.nextLine();// blank line
}// end if-else
ArrayList<Task> taskList = new ArrayList<Task>();
for (Task t : unfinishedTasks) {
taskList.add(t);
}// end for
for (Task t : finishedTasks) {
taskList.add(t);
}// end for
Employee newEmployee = new Employee(name, title, taskList);
employeeList.add(newEmployee);
}// end while
sc.close();
} catch (FileNotFoundException e) {
JOptionPane
.showMessageDialog(null,
"File not found! The Digital Manager will continue without saving.");
filepath = "";
} catch (NullPointerException e) {
JOptionPane
.showMessageDialog(null,
"Incorrect syntax! The Digital Manager will continue without saving.");
employeeList = new ArrayList<Employee>();// refresh list
}// end try-catch-catch
}// end readFromFile | 9 |
public static int[] findPrimes(int max) {
int[] prime = new int[max+1];
ArrayList list = new ArrayList();
//假设所有数都是质数
for(int i = 2; i <= max; i++){
prime[i] = 1;
}
//检查所有数
for(int i = 2; i*i <= max; i++) { // 這邊可以改進
//如果当前数是质数
if(prime[i] == 1) {
//排除掉所有能整除当前数的
for(int j = 2*i; j <= max; j++) {
if(j % i == 0)
prime[j] = 0;
}
}
}
for(int i = 2; i < max; i++) {
if(prime[i] == 1) {
list.add(new Integer(i));
}
}
int[] p = new int[list.size()];
Object[] objs = list.toArray();
for(int i = 0; i < p.length; i++) {
p[i] = ((Integer) objs[i]).intValue();
}
return p;
} | 8 |
public void sublogic(int index) {
Graphics2D g2 = (Graphics2D) bi.getGraphics();
// We talked about this above...
if (foci[index] == null) {
if (DALLATONCE)
return;
else
generateCircle(index);
}
Circle subject = foci[index];
drawCircle(subject, g2);
//let's inflate the circle now...
subject.inflate();
//if it's out of bounds, then:
if (!inBounds(index)) {
/* If we're not permuting, we can call finishCircle,
* which adds the old subject circle to the others list and
* sets the subject circle to null in the foci[] array.
*/
if (!DPERMUTE) {
finishCircle(index);
return;
}
// HOWEVER, if we ARE permuting:
//let's permute the circle's X and Y to get a new position...
//first, let's store the old circle's info.
double originalRad = subject.rad - DINFLATE;
double originalX = subject.x;
double originalY = subject.y;
boolean corrected = false;
/* This loop looks for a new circle position that is within the
* boundaries and that does not intersect any other circles.
* I'm pretty sure it prefers the top-right corner first...
*/
outer:
for (double xi : XPOSES) {
for (double yj : YPOSES) {
subject.x = originalX + DINFLATE * xi;
subject.y = originalY + DINFLATE * yj;
if (inBounds(index)) {
corrected = true;
break outer;
}
}
}
if (!corrected) {
//if we couldn't fit the circle anywhere, then too bad...
finishCircle(index);
} else {
//this is bad code duplication... but whatever.
//We need to get rid of the old circle first.
representation.setFrame(originalX - originalRad, originalY - originalRad, originalRad * 2, originalRad * 2);
g2.setColor(Color.WHITE);
g2.fill(representation);
drawCircle(subject, g2);
}
}
} | 8 |
private double expectedValue(int[] bowl, int bowlId, int round){
int bowlSize = 0;
for(int i=0; i<bowl.length; i++)
bowlSize += bowl[i];
double avgFruitScore = 0;
int totFruitsInDistribution = 0;
for(int i=0; i<NUM_FRUITS; i++){
if(currentDistribution[i] > 0){
totFruitsInDistribution += currentDistribution[i];
avgFruitScore += preference[i] * currentDistribution[i];
}
}
//if for some reason totFruitsInDistrubtion == 0
//assume uniform
if(avgFruitScore == 0)
avgFruitScore = 6.5;
else
avgFruitScore /= totFruitsInDistribution;
double expected = bowlSize * avgFruitScore;
System.out.println("Exp: " + expected);
return expected;
} | 4 |
public static int[] rightHalf(int[] array) {
int size1 = array.length / 2;
int size2 = array.length - size1;
int[] right = new int[size2];
for (int i = 0; i < size2; i++) {
right[i] = array[i + size1];
}
return right;
} | 1 |
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;integratedSecurity=true;";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
} | 8 |
public void playerHoldings() {
if (!register || !Methods.hasMethod()) {
return;
}
Format sdf = new SimpleDateFormat(larvikGaming.getConfig().getString("TimeFormat", "yyyy-MM-dd HH:mm:ss"));
Date date = new Date();
String timeStamp = sdf.format(date);
File outFile = new File(fileDir + "Player-Holdings.txt");
PrintStream printStream = null;
try {
printStream = new PrintStream(outFile);
} catch (FileNotFoundException e) {
}
long timeStart = System.currentTimeMillis();
printStream.println("========================================");
printStream.println("Players money as of: " + timeStamp);
printStream.println("========================================");
OfflinePlayer[] p = Bukkit.getOfflinePlayers();
for (int i = 0; i < p.length; i++) {
String name = p[i].getName();
double balance = 0;
if (Methods.getMethod().hasAccount(name.toLowerCase())) {
balance = Methods.getMethod().getAccount(name.toLowerCase()).balance();
if (balance > 100.0) {
printStream.println(name + ": " + form.format(balance));
}
}
}
printStream.println("-----------------------------------------------");
long time = System.currentTimeMillis() - timeStart;
printStream.println("Time used to generate this information: " + time + "ms.");
printStream.println("-----------------------------------------------");
printStream.close();
} | 6 |
private String formatProperty(String fieldKey, String fieldValue) {
if (!safe) {
// Remove whitespace from name and quotes the value.
// This typically still returns bash-unsafe key-value pairs.
return fieldKey + "=" + fieldValue;
} else {
// This returns bash-safe variables.
// First, we remove any illegal characters
fieldKey = fieldKey.replaceAll("[^a-zA-Z0-9_]+", "_");
// In case the variable name is starting with a digit, we add in an underscore instead.
if (fieldKey.matches("^[0-9].*$")) {
fieldKey = "_" + fieldKey;
}
// All return characters should be escaped for bash
fieldValue = fieldValue.replaceAll("\\n", "\\ \n");
return fieldKey + "='" + fieldValue + "'";
}
} | 2 |
public boolean avaiable(Dish dish) {
LinkedList<Material> materials = dish.getMaterials();
for (Material tmp : materials) {
for (StorageAdapter storage : storageList) {
if (tmp.getName().equals(storage.getName()) && tmp.getAmount() > storage.getAmount()) {
return false;
}
}
}
LinkedList<Ingredient> ingredients = dish.getIngredients();
for (Ingredient tmp : ingredients) {
for (StorageAdapter storage : storageList) {
if (tmp.getName().equals(storage.getName()) && storage.getAmount() <= 0) {
return false;
}
}
}
return true;
} | 8 |
@Override
public void onDraw(Graphics G, int viewX, int viewY) {
if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300)
{
Graphics2D g = (Graphics2D)G;
Composite c = g.getComposite();
// g.setComposite(new Additive());
g.setColor(new Color(255,r.nextInt(255),0,r.nextInt(255)));
g.fillArc((int)(X-6)-viewX, (int)(Y-6)-viewY, 12,12, 0, 360);
for (int i = 0; i < 4; i++)
{
int e1 = 6-r.nextInt(12), e2 = 6-r.nextInt(12);
g.setColor(new Color(255,r.nextInt(255),0,r.nextInt(255)));
g.fillArc((int)(X+e1)-viewX, (int)(Y+e2)-viewY, e1, e2, 0, 360);
}
g.setComposite(c);
}
} | 5 |
static int process(String line) {
int[] arr = giveArray(line.trim().split(" "));
if(arr.length == 1 && arr[0] == 0)
return 0;
int n = arr[0], c = arr[1];
String[] chosen = readLine().trim().split(" ");
boolean[] mp = new boolean[10002];
for(String s : chosen) {
mp[Integer.parseInt(s)] = true;
}
boolean fail = false;
for(int i = 0; i < c; i++) {
int[] cat = giveArray(readLine().trim().split(" "));
int min = cat[1];
for(int j = 2; j < 2 + cat[0]; j++) {
if(mp[cat[j]])
min--;
}
if(min > 0)
fail = true;
}
System.out.println(fail ? "no" : "yes");
return 1;
} | 8 |
public static String numberToString(Number number)
throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0 &&
string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
} | 6 |
private static int getLineNumber(){
return Thread.currentThread().getStackTrace()[3].getLineNumber();
} | 0 |
@Test
public void testTimeStep_PERIOD() throws Exception {
printDebug("----------------------------");
printDebug("PERIOD: " + this.toString());
printDebug("----------------------------");
CSTable t = DataIO.table(r, "obs");
Assert.assertNotNull(t);
// 4 YEARS
Date start = Conversions.convert("1981-4-13", Date.class);
Date end = Conversions.convert("1984-7-12", Date.class);
//System.out.println("Start = " + start.toString() + "; End = " + end.toString());
double[] mean = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.PERIOD_MEAN);
double[] min = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.PERIOD_MIN);
double[] max = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.PERIOD_MAX);
double[] median = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.PERIOD_MEDIAN);
double[] stdev = DataIO.getColumnDoubleValuesInterval(start, end, t, "runoff[0]", DataIO.PERIOD_STANDARD_DEVIATION);
//System.out.println("# values = " + obsval.length);
Assert.assertTrue(mean.length == 4);
Assert.assertTrue(min.length == 4);
Assert.assertTrue(max.length == 4);
Assert.assertTrue(median.length == 4);
Assert.assertTrue(stdev.length == 4);
double[] goldenMean = new double[4];
double[] goldenMin = new double[4];
double[] goldenMax = new double[4];
double[] goldenMedian = new double[4];
double[] goldenStdev = new double[4];
goldenMean[0] = 283.90494296577947;
goldenMin[0] = 31;
goldenMax[0] = 2890;
goldenMedian[0] = 138;
goldenStdev[0] = 325.54260421929246;
goldenMean[1] = 686.2520547945205;
goldenMin[1] = 131;
goldenMax[1] = 4740;
goldenMedian[1] = 322;
goldenStdev[1] = 692.1054096828143;
goldenMean[2] = 876.9123287671233;
goldenMin[2] = 140;
goldenMax[2] = 6390;
goldenMedian[2] = 446;
goldenStdev[2] = 1080.6484826245241;
goldenMean[3] = 679.6907216494845;
goldenMin[3] = 208;
goldenMax[3] = 2310;
goldenMedian[3] = 482.5;
goldenStdev[3] = 506.30640168591486;
for (int i=0; i<mean.length; i++) {
printDebug("Year " + i + ":");
printDebug("Mean["+i+"] = " + mean[i] + "; \tGolden = " + goldenMean[i]);
printDebug("Min["+i+"] = " + min[i] + "; \tGolden = " + goldenMin[i]);
printDebug("Max["+i+"] = " + max[i] + "; \tGolden = " + goldenMax[i]);
printDebug("Median["+i+"] = " + median[i] + "; \tGolden = " + goldenMedian[i]);
printDebug("StDev["+i+"] = " + stdev[i] + "; \tGolden = " + goldenStdev[i] + "; Delta = " + (goldenStdev[i] - stdev[i]));
printDebug("");
Assert.assertTrue(mean[i] == goldenMean[i]);
Assert.assertTrue(min[i] == goldenMin[i]);
Assert.assertTrue(max[i] == goldenMax[i]);
Assert.assertTrue(median[i] == goldenMedian[i]);
double allowedDelta_stdev = 2.28E-13;
Assert.assertEquals(stdev[i], goldenStdev[i], allowedDelta_stdev);
}
} | 1 |
public void init() {
if (inited) {
return;
}
// try and find the form's resources dictionary.
Resources leafResources = library.getResources(entries, "Resources");
// apply resource for tiling if any, otherwise we use the default dictionary.
if (leafResources != null) {
resources = leafResources;
// resources.addReference(this);
// todo, need a way do dispose of reference when we implement this fully
}
// Build a new content parser for the content streams and apply the
// content stream of the calling content stream.
ContentParser cp = new ContentParser(library, leafResources);
cp.setGraphicsState(parentGraphicState);
InputStream in = getInputStreamForDecodedStreamBytes();
if (in != null) {
try {
shapes = cp.parse(in);
}
catch (Throwable e) {
logger.log(Level.FINE, "Error processing tiling pattern.", e);
}
finally {
try {
in.close();
}
catch (IOException e) {
}
}
}
} | 5 |
void prefetch_all_headers(Info first_i, Comment first_c, int dataoffset)
throws SoundException {
Page og = new Page();
int ret;
vi = new Info[links];
vc = new Comment[links];
dataoffsets = new long[links];
pcmlengths = new long[links];
serialnos = new int[links];
for (int i = 0; i < links; i++) {
if (first_i != null && first_c != null && i == 0) {
// we already grabbed the initial header earlier. This just
// saves the waste of grabbing it again
vi[i] = first_i;
vc[i] = first_c;
dataoffsets[i] = dataoffset;
} else {
// seek to the location of the initial header
seek_helper(offsets[i]); //!!!
vi[i] = new Info();
vc[i] = new Comment();
if (fetch_headers(vi[i], vc[i], null, null) == -1) {
dataoffsets[i] = -1;
} else {
dataoffsets[i] = offset;
os.clear();
}
}
// get the serial number and PCM length of this link. To do this,
// get the last page of the stream
{
long end = offsets[i + 1]; //!!!
seek_helper(end);
while (true) {
ret = get_prev_page(og);
if (ret == -1) {
// this should not be possible
vi[i].clear();
vc[i].clear();
break;
}
if (og.granulepos() != -1) {
serialnos[i] = og.serialno();
pcmlengths[i] = og.granulepos();
break;
}
}
}
}
} | 8 |
public PixImage toPixImage() {
PixImage image = new PixImage(width,height);
RunIterator iterate = iterator();
int row = 0;
int column = 0;
do {
int[] runArray = iterate.next();
int count = runArray[0];
while (count > 0) {
image.setPixel(column,row,(short)runArray[1],(short)runArray[2],(short)runArray[3]);
if(column == image.getWidth() - 1){
row++; column = 0;
}
else {
column++;
}
count--;
}
} while (iterate.hasNext());
return image;
} | 3 |
public ResourceClump(int cx, int cy, int radius, int type) {
this.cx = cx;
this.cy = cy;
this.radius = radius;
this.num_voxels = 0;
this.type = type;
int ci = getI(cx);
int cj = getJ(cy);
int iradius = getI(radius);
for (int i = ci - iradius; i < ci + iradius; i++) {
for (int j = cj - iradius; j < cj + iradius; j++) {
if (i < 0 || j < 0 || i >= voxels.length
|| j >= voxels[0].length)
continue;
double di = i - ci;
double dj = j - cj;
double idist = Math.sqrt(di * di + dj * dj);
if (idist < iradius) {
voxels[i][j] = type;
resource_density[i][j] = STARTING_DENSITY;
locked[i][j] = false;
num_voxels++;
}
}
}
addForce();
} | 7 |
@EventHandler
public void login(PlayerLoginEvent ple) {
MemberManager memberManager = Citadel.getMemberManager();
memberManager.addOnlinePlayer(ple.getPlayer());
String playerName = ple.getPlayer().getDisplayName();
Member member = memberManager.getMember(playerName);
if(member == null){
member = new Member(playerName);
memberManager.addMember(member);
}
PersonalGroupManager personalGroupManager = Citadel.getPersonalGroupManager();
boolean hasPersonalGroup = personalGroupManager.hasPersonalGroup(playerName);
GroupManager groupManager = Citadel.getGroupManager();
if(!hasPersonalGroup){
String groupName = playerName;
int i = 1;
while(groupManager.isGroup(groupName)){
groupName = playerName + i;
i++;
}
Faction group = new Faction(groupName, playerName);
groupManager.addGroup(group);
personalGroupManager.addPersonalGroup(groupName, playerName);
} else if(hasPersonalGroup){
String personalGroupName = personalGroupManager.getPersonalGroup(playerName).getGroupName();
if(!groupManager.isGroup(personalGroupName)){
Faction group = new Faction(personalGroupName, playerName);
groupManager.addGroup(group);
}
}
} | 5 |
public static Matrice multiply(Matrice a, Matrice b) throws MatrixException
{
//Condition sur les dimensions
if(a.columns != b.lines)
{
throw new MatrixException("Problème de dimension !");
}
Matrice res = new Matrice(a.lines, b.columns);
double temp = 0.0;
int a_col = 0;
for(int a_lines = 0; a_lines< a.lines; a_lines++)
{
for(int b_col = 0; b_col < b.columns; b_col++)
{
for(a_col = 0; a_col < a.columns; a_col++)
{
temp += a.getValueAt(a_lines, a_col) * b.getValueAt(a_col, b_col);
}
res.setValueAt(a_lines, b_col, temp);
temp = 0.0;
}
}
return res;
} | 4 |
@Override
public void execute() {
Vars.status = "SummoningNode";
Vars.needToSummon = true;
Timer t = new Timer(2500);
if (Summoning.getPoints() < 1 && !Summoning.isFamiliarSummoned()) {
Vars.status = "Pot";
Inventory.getItem(Const.SUM_POT).getWidgetChild().interact("Drink");
t.reset();
while (t.isRunning() && Summoning.getPoints() < 1) {
sleep(200, 300);
}
}
if (Summoning.getPoints() > 1 && !Summoning.isFamiliarSummoned()) {
Vars.status = "Pouch";
Inventory.getItem(Vars.pouches).getWidgetChild().interact("Summon");
t.reset();
while (t.isRunning() && !Summoning.isFamiliarSummoned()) {
sleep(200, 300);
}
}
Vars.needToSummon = false;
} | 8 |
public final static String htmlEscape(String line)
{
StringBuilder sb = new StringBuilder();
char[] chars = line.toCharArray();
for (int i=0; i<chars.length; i++) {
char cur = chars[i];
if ((cur == '\n') || (cur == '\r') || (cur == '\t')) {
sb.append(cur);
}
else if ((cur >= ' ') && (cur <= '~') &&
(cur != '<') && (cur != '>') && (cur != '&')) {
sb.append(cur);
}
else {
sb.append("&#");
sb.append(Integer.toString(cur));
sb.append(";");
}
}
return sb.toString();
} | 9 |
public static int storeVersion(byte[] target, int targetOffset, int targetLength, int targetLimit,
long versionHandle, byte[] source, int sourceOffset, int sourceLength) {
int existedMask = 0;
int to = targetOffset;
if (targetLimit > target.length) {
throw new IllegalArgumentException("Target limit exceed target array length: " + targetLimit + " > "
+ target.length);
}
if (source == target) {
throw new IllegalArgumentException("Source and target arrays must be different");
}
if (sourceLength > MAX_LENGTH_MASK) {
throw new IllegalArgumentException("Source length greater than max: " + sourceLength + " > "
+ MAX_LENGTH_MASK);
}
/*
* Value did not previously exist. Result will be an MVV with one
* version.
*/
if (targetLength < 0) {
assertCapacity(targetLimit, targetOffset + sourceLength + overheadLength(1));
// Promote to MVV, no original state to preserve
target[to++] = TYPE_MVV_BYTE;
}
/*
* Value previously existed as a primordial undefined value (length =
* 0). Result will be an MVV with two versions.
*/
else if (targetLength == 0) {
assertCapacity(targetLimit, targetOffset + sourceLength + overheadLength(2));
// Promote to MVV, original state is undefined
target[to++] = TYPE_MVV_BYTE;
putVersion(target, to, PRIMORDIAL_VALUE_VERSION);
putLength(target, to, UNDEFINED_VALUE_LENGTH);
to += LENGTH_PER_VERSION;
}
/*
* Value previously existed as a primordial value. Result will be an MVV
* with two versions.
*/
else if (target[0] != TYPE_MVV_BYTE) {
assertCapacity(targetLimit, targetOffset + sourceLength + targetLength + overheadLength(2));
// Promote to MVV, shift existing down for header
System.arraycopy(target, to, target, to + LENGTH_TYPE_MVV + LENGTH_PER_VERSION, targetLength);
target[to++] = TYPE_MVV_BYTE;
putVersion(target, to, PRIMORDIAL_VALUE_VERSION);
putLength(target, to, targetLength);
to += LENGTH_PER_VERSION + targetLength;
}
/*
* Value previously existed as an MVV. Result will be an MVV with an
* extra version in most cases. The number result has the same number of
* versions when the supplied versionHandle matches one of the existing
* versions, in which case the value associated with that version is
* simply replaced.
*/
else {
Debug.$assert0.t(verify(target, targetOffset, targetLength));
/*
* Search for the matching version.
*/
to++;
int next = to;
int end = targetOffset + targetLength;
while (next < end) {
final long curVersion = getVersion(target, to);
final int vlength = getLength(target, to);
next += LENGTH_PER_VERSION + vlength;
if (curVersion == versionHandle) {
existedMask = STORE_EXISTED_MASK;
if (vlength == sourceLength) {
/*
* Replace the version having the same version handle;
* same length - can simply be copied in place.
*/
System.arraycopy(source, sourceOffset, target, next - vlength, vlength);
return targetLength | existedMask;
} else {
assertCapacity(targetLimit, targetOffset + targetLength + overheadLength(1) + to - next
+ sourceLength);
/*
* Remove the version having the same version handle -
* the new version will be added below.
*/
System.arraycopy(target, next, target, to, targetOffset + targetLength - next);
end -= (next - to);
next = to;
}
}
to = next;
}
}
assertCapacity(targetLimit, to + LENGTH_PER_VERSION + sourceLength);
// Append new value
putVersion(target, to, versionHandle);
putLength(target, to, sourceLength);
to += LENGTH_PER_VERSION;
System.arraycopy(source, sourceOffset, target, to, sourceLength);
to += sourceLength;
Debug.$assert0.t(verify(target, targetOffset, to - targetOffset));
return (to - targetOffset) | existedMask;
} | 9 |
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((dataNascimento == null) ? 0 : dataNascimento.hashCode());
result = prime * result + ((email == null) ? 0 : email.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((livros == null) ? 0 : livros.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
return result;
} | 5 |
protected Direction decide() {
if (followingWall && rotation == 0) {
// "When the solver is facing the original direction again,
// and the angular sum of the turns made is 0,
// the solver leaves the obstacle and continues
// moving in its original direction." (Wikipedia)
followingWall = false;
}
if (!followingWall) {
// We have not yet found a wall.
// Can we go forward?
if (getPlayerState().canMove(going)) {
// We can go forward, so let's do it.
return going;
} else {
// We can't go forward, so start following the wall.
followingWall = true;
// We want to have the wall on the left, so we turn right.
right();
}
}
// We are following a wall.
// Can we go left?
if (getPlayerState().canMove(going.left())) {
// We can go left. So we turn to the left.
left();
// And go forward.
return going;
} else {
// Turn right until we can go forward.
int i = 0;
while (!getPlayerState().canMove(going)) {
right();
i++;
if (i >= 4) {
// We cannot move in any way,
// so let's commit suicide by crashing into a wall.
// (Technichally, we go in a random impossible direction,
// which will raise a PlayerCannotMoveException.)
return going;
}
}
// Go forward.
return going;
}
} | 7 |
public static String formatRange(long... range) {
switch (range.length) {
case 0: return "bytes=0-";
case 1:
if (range[0] < 0) throw new IllegalArgumentException("negative range");
return "bytes="+range[0]+"-";
case 2:
if (range[0] < 0) throw new IllegalArgumentException("negative range");
if (range[0] > range[1]) throw new IllegalArgumentException(range[0] + ">" + range[1]);
return "bytes="+range[0]+"-"+range[1];
default: throw new IllegalArgumentException("invalid range specified");
}
} | 6 |
Font(BufferedImage sheet, int charWidth, int charHeight) {
this.charWidth = charWidth;
this.charHeight = charHeight;
sprites = new Sprite[L.length()];
int sheetWidth = sheet.getWidth();
for (int i = 0; i < sprites.length; i++) {
sprites[i] = new Sprite(sheet.getSubimage(i * this.charWidth % sheetWidth, (i * charWidth / sheetWidth)*charHeight, charWidth, charHeight));
}
} | 1 |
public String getPath(String path) {
String split[] = path.split("\\.");
if (split.length <= 0)
return path;
String newPath = "";
boolean set = true;
ConfigurationSection section = config.getRoot();
for (int i = 0; i < split.length; i++) {
if (!set) {
newPath += "." + split[i];
continue;
}
set = false;
try {
Set<String> entries = section.getKeys(false);
for (String x : entries) {
if (x.equalsIgnoreCase(split[i])) {
newPath += "." + x;
set = true;
section = section.getConfigurationSection(x);
}
}
} catch (Exception e) {
set = false;
}
if (!set) {
newPath += "." + split[i];
}
}
return newPath.substring(1);
} | 7 |
public void getMap(){
int x = xStart;
int y = yStart;
mapWidth = 0;
mapHeight = 0;
int doorCount = 0;
int interactiveCount = 0;
//Gets map from globalMap
LocalMap blockTypes = globalMap.enterLocalMap(globalPosX , globalPosY);
columns = blockTypes.x;
rows = blockTypes.y;
blocks = new Block[rows][columns];
for(int i = 0; i < blockTypes.y; i++){
x = xStart;
for(int j = 0; j < blockTypes.x; j++){
if(blockTypes.map[i][j] == 3 || blockTypes.map[i][j] == 14){
blocks[i][j] = new DoorBlock(x , y , blockTypes.map[i][j], blockTypes.getDoorId(doorCount + 1), blockTypes.getDoorId(doorCount));
doorCount++;
} else if (blockTypes.map[i][j] == 13) {
blocks[i][j] = new InteractiveBlock(x, y, blockTypes.getInteractiveId(interactiveCount), blockTypes.getInteractiveId(interactiveCount + 1));
interactiveCount++;
} else {
blocks[i][j] = new Block(x , y , blockTypes.map[i][j]);
}
x += Screen.blockSize;
}
y += Screen.blockSize;
}
lastBlockVer = blocks[rows-1][0];
lastBlockHor = blocks[rows-1][columns-1];
mapWidth = x - Screen.blockSize;
mapHeight = y - Screen.blockSize;
} | 5 |
boolean isAttackPlaceDiagonallyAboveRightNotHarming(int position, char[] boardElements, int dimension, int attackPlacesOnTheRight) {
int positionRightAbove = 1;
while (attackPlacesOnTheRight > 0) {
if (isPossibleToPlaceDiagRightAbove(position, dimension, positionRightAbove)
&& isBoardElementAnotherFigure(boardElements[elementDiagonallyRightAbove(dimension, position, positionRightAbove)])) {
return false;
}
positionRightAbove++;
attackPlacesOnTheRight--;
}
return true;
} | 3 |
String getAuthors()
{
return authors;
} | 0 |
public void writeSentence(TokenStructure syntaxGraph) throws MaltChainedException {
if (syntaxGraph == null || dataFormatInstance == null) {
return;
}
if (syntaxGraph.hasTokens()) {
sentenceCount++;
final PhraseStructure phraseStructure = (PhraseStructure)syntaxGraph;
try {
sentenceID.setLength(0);
sentenceID.append(sentencePrefix);
if (phraseStructure.getSentenceID() != 0) {
sentenceID.append(Integer.toString(phraseStructure.getSentenceID()));
} else {
sentenceID.append(Integer.toString(sentenceCount));
}
writer.write(" <s id=\"");
writer.write(sentenceID.toString());
writer.write("\">\n");
setRootID(phraseStructure);
writer.write(" <graph root=\"");
writer.write(rootID.toString());
writer.write("\" ");
writer.write("discontinuous=\"");
writer.write(Boolean.toString(!phraseStructure.isContinuous()));
writer.write("\">\n");
writeTerminals(phraseStructure);
if (phraseStructure.nTokenNode() != 1 || rootHandling.equals(RootHandling.TALBANKEN)) {
writeNonTerminals(phraseStructure);
} else {
writer.write(" <nonterminals/>\n");
}
writer.write(" </graph>\n");
writer.write(" </s>\n");
} catch (IOException e) {
throw new DataFormatException("The TigerXML writer could not write to file. ", e);
}
}
} | 7 |
@Override
public void startSetup(Attributes atts) {
super.startSetup(atts);
addActionListener(this);
} | 0 |
public static void main(String[] args)
{
TuringTrimmingTester t=new TuringTrimmingTester("productions.txt");
} | 0 |
public void visit_lrem(final Instruction inst) {
stackHeight -= 4;
if (stackHeight < minStackHeight) {
minStackHeight = stackHeight;
}
stackHeight += 2;
} | 1 |
void balance(Entry<V> x) {
Entry<V> y;
x.color = true;
while (x != root && x.parent.color) {
if (x.parent == x.parent.parent.left) {
y = x.parent.parent.right;
if (y != null && y.color) {
x.parent.color = false;
y.color = false;
x.parent.parent.color = true;
x = x.parent.parent;
} else {
if (x == x.parent.right) {
x = x.parent;
leftRotate(x);
}
x.parent.color = false;
x.parent.parent.color = true;
rightRotate(x.parent.parent);
}
} else {
y = x.parent.parent.left;
if (y != null && y.color) {
x.parent.color = false;
y.color = false;
x.parent.parent.color = true;
x = x.parent.parent;
} else {
if (x == x.parent.left) {
x = x.parent;
rightRotate(x);
}
x.parent.color = false;
x.parent.parent.color = true;
leftRotate(x.parent.parent);
}
}
}
root.color = false;
} | 9 |
public static String getContentFromSeekableInput(SeekableInput in, boolean convertToHex) {
String content = null;
try {
in.beginThreadAccess();
long position = in.getAbsolutePosition();
ByteArrayOutputStream out = new ByteArrayOutputStream();
/*
byte[] buf = new byte[1024];
while( true ) {
int read = in.read( buf, 0, buf.length );
if( read < 0 )
break;
out.write( buf, 0, read );
}
*/
while (true) {
int read = in.getInputStream().read();
if (read < 0)
break;
out.write(read);
}
in.seekAbsolute(position);
out.flush();
out.close();
byte[] data = out.toByteArray();
if (convertToHex)
content = Utils.convertByteArrayToHexString(data, true);
else
content = new String(data);
}
catch (IOException ioe) {
logger.log(Level.FINE, "Problem getting debug string");
}
finally {
in.endThreadAccess();
}
return content;
} | 4 |
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
int times = Integer.parseInt(in.readLine().trim());
for (int t = 0; t < times; t++) {
in.readLine();
String firstLine = in.readLine().trim();
int size = firstLine.length();
m = new char[size][size];
m[0] = firstLine.toCharArray();
for (int j = 1; j < size; j++)
m[j] = in.readLine().trim().toCharArray();
area = getMaxRectangleSum();
if (t != 0)
out.append("\n");
out.append(area + "\n");
}
System.out.print(out);
} | 3 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FavoritesTag other = (FavoritesTag) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
} | 6 |
private int readStringTable
(byte[] remainingData,
int offset,
int blockStart,
ResStringPool_Header stringPoolHeader,
Map<Integer, String> stringList) throws IOException {
// Read the strings
for (int i = 0; i < stringPoolHeader.stringCount; i++) {
int stringIdx = readUInt32(remainingData, offset);
offset += 4;
// Offset begins at block start
stringIdx += stringPoolHeader.stringsStart + blockStart;
String str = "";
if (stringPoolHeader.flagsUTF8)
str = readStringUTF8(remainingData, stringIdx).trim();
else
str = readString(remainingData, stringIdx).trim();
stringList.put(i, str);
}
return offset;
} | 2 |
@Override
public void insertAt(T object, int index) throws DAIllegalArgumentException, DAIndexOutOfBoundsException
{
if(object == null)
{
throw new IllegalArgumentException();
}
else if((index >= 0) && (index <= size))
{
if(size >= array.length)
{
growArray();
}
//starts at the end and shifts everything up by 1
System.arraycopy(array, index, array, index + 1, size - index);
// sets the object at position index
array[index] = object;
size++;
}
else if((index < 0) || (index > size))
{
throw new IndexOutOfBoundsException();
}
} | 6 |
public ArrayList<String> getEspTitles() {
return espTitles;
} | 0 |
public boolean getScrollableTracksViewportWidth() {
return getPreferredSize().width < getParent().getSize().width;
} | 0 |
public List<Claim> getClaimAndSubclaimList(String teamType) {
List<Claim> claimList = new ArrayList<Claim>();
Element claimE;
Claim claim;
for (Iterator i = root.elementIterator("claim"); i.hasNext();) {
claimE = (Element)i.next();
if (claimE.attributeValue("teamType").equals(teamType)) {
if (claimE.element("isDelete").getText().equals("false")) {
String id = claimE.element("id").getText()
, title = claimE.element("title").getText()
, description = claimE.element("description").getText()
, type = claimE.element("type").getText()
, timeAdded = claimE.element("timeAdded").getText()
, name = claimE.element("name").getText()
, debateId = claimE.element("debateId").getText()
, dialogState = claimE.elementText("dialogState");
claim = new Claim(id, title, description, type
, timeAdded, null, name, debateId, dialogState);
claimList.add(claim);
}
}
}
for (Iterator i = root.elementIterator("subclaim"); i.hasNext();) {
claimE = (Element)i.next();
if (claimE.attributeValue("teamType").equals(teamType)) {
if (claimE.element("isDelete").getText().equals("false")) {
String id = claimE.element("id").getText()
, title = claimE.element("title").getText()
, description = claimE.element("description").getText()
, type = claimE.element("type").getText()
, timeAdded = claimE.element("timeAdded").getText()
, name = claimE.element("name").getText()
, debateId = claimE.element("debateId").getText()
, dialogState = claimE.elementText("dialogState");
claim = new Claim(id, title, description, type
, timeAdded, null, name, debateId, dialogState);
claimList.add(claim);
}
}
}
return claimList;
} | 6 |
public static boolean canAccess(String position, String subsystem){
if(position.equals("manager"))
return true;
if(position.equals("pharmacist")&&!subsystem.equals("employee"))
return true;
if(position.equals("tech")&&subsystem.equals("patient"))
return true;
return false;
} | 5 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ServicePK_Simple other = (ServicePK_Simple) obj;
if (client == null) {
if (other.client != null)
return false;
} else if (!client.equals(other.client))
return false;
if (serviceProvider == null) {
if (other.serviceProvider != null)
return false;
} else if (!serviceProvider.equals(other.serviceProvider))
return false;
return true;
} | 9 |
public static Point2D lookUpNextStep(Point2D start, Point2D end, Class<?>... ignoredObstacles) {
if (Field.arePointsNear(start, end)) { return end; }
int[][] map = getMap(ignoredObstacles);
map[start.x+1][start.y+1] = 0;
map[end.x+1][end.y+1] = 0;
Queue<Integer> points_to_go = new LinkedList<>();
points_to_go.add(end.x+1);
points_to_go.add(end.y+1);
CommonBfsNeighborHandler bfsH = new CommonBfsNeighborHandler(points_to_go, map);
DestinationNeighborHandler destH = new DestinationNeighborHandler(map, start);
while (!points_to_go.isEmpty()) {
int curr_x = points_to_go.poll();
int curr_y = points_to_go.poll();
if (curr_x == start.x+1 && curr_y == start.y+1) {
processNeighbors(destH);
break;
}
bfsH.setCurrentCoord(curr_x, curr_y);
processNeighbors(bfsH);
}
return destH.next_step == null ? start : destH.next_step;
} | 6 |
@Override
public void run() {
for(Player p : DeityNether.plugin.getServer().getOnlinePlayers()){
if(p.getWorld() == DeityNether.plugin.getServer().getWorld(DeityNether.config.getNetherWorldName())){
if(!p.hasPermission(DeityNether.OVERRIDE_PERMISSION) && p.hasPermission(DeityNether.GENERAL_PERMISSION)){
PlayerStats.addTime(p);
checkPlayer(p);
}
}else{
if(PlayerStats.getTimeWaited(p) != NEEDED_WAIT_TIME)
PlayerStats.addWaitTime(p);
}
}
for(OfflinePlayer p : DeityNether.plugin.getServer().getOfflinePlayers()){
PlayerStats.addWaitTime(p);
}
Timestamp now = new Timestamp(System.currentTimeMillis());
Timestamp nextReset = DeityNether.config.getNextReset();
if(now.after(nextReset) || now.equals(nextReset)){
DeityNether.config.setResetStatus(true);
}
} | 8 |
public boolean setWumpusPos(Position newPos){
boolean success = false;
if(getWumpusPos().getX() != -1 && getWumpusPos().getY() != -1) { // Wumpus already exists
removeWumpus();
}
if(this.isInsideBoard(newPos)) {
if(this.isEmpty(newPos)) {
// Set Wumpus
if(writeOnBoard(newPos,WUMPUS)){
getWumpusPos().setX(newPos.getX());
getWumpusPos().setY(newPos.getY());
removeFromBoard(EMPTY, newPos);
setWumpusAlive(true);
// Set Smell
Position smell = new Position();
for(int i=-1; i<2; i++) {
smell.setX(newPos.getX());
smell.setX(smell.getX()+i);
for(int j=-1; j<2; j++) {
smell.setY(newPos.getY());
smell.setY(smell.getY()+j);
if(isInsideBoard(smell)) {
writeOnBoard(smell, SMELL);
}
}
}
success = true;
}
}else{
System.out.println("That position is occupied by: "+this.readFromBoard(newPos));
}
} else {
System.out.println("That position is out of the board");
}
return success;
} | 8 |
public static List<RecParametr> StringToParams(String str)
{
List<RecParametr> list = new ArrayList<RecParametr>();
String[] strs = str.split(";");
for(String s1 : strs)
{
RecParametr r = new RecParametr(s1.trim() + ";");
if(!r.GetName().equals("") && !r.GetValue().equals(""))
list.add(r);
}
return list;
} | 3 |
@Override
public int rowsX() {
return isNotPlayerInventory() ? 4 : 5;
} | 1 |
public static void loadData(ArrayList<ResourceLoader> loaders){
for(ResourceLoader loader : loaders){
loader.addResources();
}
OutputUtility.outputLine("-Loading Resources-");
OutputUtility.increment();
OutputUtility.outputLine("-Loading Images-");
OutputUtility.increment();
image_list.load();
OutputUtility.deincrement();
OutputUtility.outputLine("-Loading Audio-");
OutputUtility.increment();
audio_list.load();
OutputUtility.deincrement();
OutputUtility.deincrement();
TextureLoader.load(image_list);
sheet_list.load();
for(ResourceLoader loader : loaders){
loader.addAnimations();
}
animation_list.load();
GameFontRender.load();
} | 2 |
public double[][] standardizedCovariances(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.covariancesCalculated)this.covariancesAndCorrelationCoefficients();
return this.standardizedCovariances;
} | 2 |
public boolean execute() {
final int cycle=CDState.getCycle();
if( shuffle ) rperm.reset( Network.size() );
for(int j=0; j<Network.size(); ++j)
{
Node node = null;
if( getpair_rand )
node = Network.get(CDState.r.nextInt(Network.size()));
else if( shuffle )
node = Network.get(rperm.next());
else
node = Network.get(j);
if( !node.isUp() ) continue;
CDState.setNode(node);
CDState.setCycleT(j);
final int len = node.protocolSize();
for(int k=0; k<len; ++k)
{
// Check if the protocol should be executed, given the
// associated scheduler.
if (!protSchedules[k].active(cycle))
continue;
CDState.setPid(k);
Protocol protocol = node.getProtocol(k);
if( protocol instanceof CDProtocol )
{
((CDProtocol)protocol).nextCycle(node, k);
if( !node.isUp() ) break;
}
}
}
return false;
} | 9 |
Subsets and Splits
SQL Console for giganticode/java-cmpx-v1
The query retrieves a limited number of text entries within a specific length range, providing basic filtering but minimal analytical insight.