text
stringlengths 14
410k
| label
int32 0
9
|
---|---|
public GetDataBySubjectPanel(JFrame frame, QueryDefinition query) throws Exception {
super(frame, query, new GetDataBySubject(query.getDocument()));
JTabbedPane panel = new JTabbedPane();
//
// Defines the "Subject IDs" tab.
/////////////////////////////
ItemSet<SubjectID> subItems = new ItemSet<SubjectID>() {
@Override
public void add(SubjectID item) {
GetDataBySubjectPanel.this.getRequest().addSubject(item);
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
@Override
public void remove(SubjectID item) {
GetDataBySubjectPanel.this.getRequest().removeSubject(item);
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
@Override
public int size() {
return GetDataBySubjectPanel.this.getRequest().getSubjectCount();
}
@Override
public SubjectID get(int index) {
return GetDataBySubjectPanel.this.getRequest().getSubject(index);
}
@Override
public void set(int index, String name, Object value) {
SubjectID id = this.get(index);
if(name.equals("Contributor")) {
id.setContributor((Contributor) value);
} else if(name.equals("Value")) {
id.setValue((String) value);
}
GetDataBySubjectPanel.this.getRequest().notifyChange();
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
};
ItemTablePanel<SubjectID> subjectsPanel = new ItemTablePanel<SubjectID>(SubjectID.class, subItems);
panel.add("Subject IDs", subjectsPanel);
//
// Defines the "Parameters" tab.
/////////////////////////////
ItemSet<Parameter> paramItems = new ItemSet<Parameter>() {
@Override
public void add(Parameter item) {
GetDataBySubjectPanel.this.getRequest().addParameter(item);
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
@Override
public void remove(Parameter item) {
GetDataBySubjectPanel.this.getRequest().removeParameters(item);
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
@Override
public int size() {
return GetDataBySubjectPanel.this.getRequest().getParameterCount();
}
@Override
public Parameter get(int index) {
return GetDataBySubjectPanel.this.getRequest().getParameter(index);
}
@Override
public void set(int index, String name, Object value) {
Parameter id = this.get(index);
if(name.equals("Name")) {
id.setName((String) value);
} else if(name.equals("Value")) {
id.setValue((String) value);
}
GetDataBySubjectPanel.this.getRequest().notifyChange();
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
};
ItemTablePanel<Parameter> paramsPanel = new ItemTablePanel<Parameter>(Parameter.class, paramItems);
panel.add("Parameters", paramsPanel);
//
// Defines the "Logs" tab.
/////////////////////////////
ItemSet<LogEntry> logItems = new ItemSet<LogEntry>() {
@Override
public void add(LogEntry item) {
GetDataBySubjectPanel.this.getRequest().addLog(item);
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
@Override
public void remove(LogEntry item) {
GetDataBySubjectPanel.this.getRequest().removeLog(item);
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
@Override
public int size() {
return GetDataBySubjectPanel.this.getRequest().getLogCount();
}
@Override
public LogEntry get(int index) {
return GetDataBySubjectPanel.this.getRequest().getLog(index);
}
@Override
public void set(int index, String name, Object value) {
LogEntry id = this.get(index);
if(name.equals("Value")) {
id.setValue((String) value);
}
GetDataBySubjectPanel.this.getRequest().notifyChange();
stateChanged(new GetDatabySubjectPanelChangeEvent(GetDataBySubjectPanel.this));
}
};
ItemTablePanel<LogEntry> logPanel = new ItemTablePanel<LogEntry>(LogEntry.class, logItems);
panel.add("Logs", logPanel);
//
// Defines the "other" tab.
/////////////////////////////
JPanel otherPanel = new JPanel();
otherPanel.setLayout(new GridBagLayout());
GridBagConstraints cMain = new GridBagConstraints();
cMain.fill = GridBagConstraints.HORIZONTAL;
cMain.anchor = GridBagConstraints.PAGE_START;
cMain.gridx = 0;
cMain.gridy = 0;
JPanel trxIdPanel = new JPanel();
GridBagConstraints c = new GridBagConstraints();
trxIdPanel.setLayout(new GridBagLayout());
otherPanel.add(trxIdPanel, cMain);
panel.add("Other", otherPanel);
trxIdPanel.setBorder(BorderFactory.createTitledBorder("Transaction ID"));
this.btnGroup = new ButtonGroup();
ActionListener btnActions = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(GetDataBySubjectPanel.this.rdoBtnStatic.isSelected()) {
GetDataBySubjectPanel.this.trxIdTextField.setEditable(true);
GetDataBySubjectPanel.this.trxIdTextField.grabFocus();
GetDataBySubjectPanel.this.getRequest().setTransactionIDMode(TransactionMode.Static);
} else if(GetDataBySubjectPanel.this.rdoBtnRandom.isSelected()) {
GetDataBySubjectPanel.this.trxIdTextField.setEditable(false);
GetDataBySubjectPanel.this.getRequest().setTransactionIDMode(TransactionMode.Random);
} else if(GetDataBySubjectPanel.this.rdoBtnNone.isSelected()) {
GetDataBySubjectPanel.this.trxIdTextField.setEditable(false);
GetDataBySubjectPanel.this.getRequest().setTransactionIDMode(TransactionMode.None);
}
}
};
this.rdoBtnNone = new JRadioButton("None", true);
this.rdoBtnNone.addActionListener(btnActions);
this.btnGroup.add(this.rdoBtnNone);
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 0;
c.gridy = 0;
trxIdPanel.add(this.rdoBtnNone, c);
this.rdoBtnRandom = new JRadioButton("Random");
this.rdoBtnRandom.addActionListener(btnActions);
this.btnGroup.add(this.rdoBtnRandom);
c.gridx = 0;
c.gridy = 1;
trxIdPanel.add(this.rdoBtnRandom, c);
this.rdoBtnStatic = new JRadioButton("Static");
this.rdoBtnStatic.addActionListener(btnActions);
this.btnGroup.add(this.rdoBtnStatic);
c.gridx = 0;
c.gridy = 2;
trxIdPanel.add(this.rdoBtnStatic, c);
this.trxIdTextField = new JTextField();
this.trxIdTextField.addActionListener(this);
this.trxIdTextField.setEditable(false);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 1;
c.gridy = 2;
trxIdPanel.add(this.trxIdTextField, c);
JPanel bufferPanel = new JPanel();
cMain.gridx = 0;
cMain.gridy = 1;
cMain.weightx = 1;
cMain.weighty = 1;
otherPanel.add(bufferPanel, cMain);
this.trxIdTextField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent arg0) {
String text = GetDataBySubjectPanel.this.trxIdTextField.getText();
GetDataBySubjectPanel.this.getRequest().setTransactionId(text);
stateChanged(null);
}
@Override
public void insertUpdate(DocumentEvent arg0) {
this.changedUpdate(arg0);
}
@Override
public void removeUpdate(DocumentEvent arg0) {
this.changedUpdate(arg0);
}
});
this.addFirstTab("Fields", panel);
} | 8 |
public void notifyOfRowModification(Row row, Column column) {
for (OutlineModelListener listener : getCurrentListeners()) {
listener.rowWasModified(this, row, column);
}
} | 1 |
public static boolean verify(byte[] data, String publicKey, String sign)
throws Exception {
// 解密由base64编码的公钥
byte[] keyBytes = SecurityCoder.base64Decoder(publicKey);
// 构造X509EncodedKeySpec对象
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KEY_ALGORITHM 指定的加密算法
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// 取公钥匙对象
PublicKey pubKey = keyFactory.generatePublic(keySpec);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initVerify(pubKey);
signature.update(data);
// 验证签名是否正常
return signature.verify(SecurityCoder.base64Decoder(sign));
} | 0 |
private void updateView() {
if (this.nodes == null || this.nodes.length > 1
|| !this.nodes[0].exists()) {
this.titleBorder.setTitle("-");
this.jzvStat.setStat(null);
this.taUpdate.setText("");
this.taChildData.setText("");
this.jbUpdate.setEnabled(false);
this.jbNewChild.setEnabled(false);
this.jbDelete.setEnabled(this.nodes != null);
} else {
this.titleBorder.setTitle(this.nodes[0].getPath());
this.jzvStat.setStat(this.nodes[0].getStat());
byte[] data = this.nodes[0].getData();
this.taUpdate.setText(new String(data == null ? "null".getBytes()
: data));
this.taChildData.setText("");
this.jbUpdate.setEnabled( !this.taUpdate.getText().trim().equals("") );
this.jbNewChild.setEnabled( !this.jtfChildName.getText().trim().equals("") );
this.jbDelete.setEnabled(true);
}
this.repaint();
} | 4 |
public void act() {
if (enabled) {
boolean last = hover;
boolean lastP = pressed;
if (Greenfoot.mouseMoved(this)) {
hover = true;
} else if (Greenfoot.mouseMoved(null)) {
hover = false;
}
if (Greenfoot.mousePressed(this)) {
pressed = true;
}
if (Greenfoot.mouseClicked(this) /* && hover */) {
clicked = true;
}
if (Greenfoot.mouseClicked(null) || Greenfoot.mouseDragEnded(null)) {
pressed = false;
}
if (last != hover || lastP != pressed) {
// state changed
createImage();
}
}
} | 9 |
private void jLabel15MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel15MouseClicked
jTextPane1.insertIcon(new ImageIcon(getClass().getResource("/picture/3.jpg")));
pos.add(jTextPane1.getText().toString().length()-1);
pic.add("|");
}//GEN-LAST:event_jLabel15MouseClicked | 0 |
private void calculateToExit()
{
int newDirection = 0;
if (getColumn() > HOME_COLUMN) {
newDirection = 3;
} else if (getColumn() < HOME_COLUMN) {
newDirection = 1;
} else if (getRow() > HOME_ROW) {
newDirection = 0;
} else {
isAtHome = false;
}
setDirection(newDirection);
} | 3 |
public final String getFirstParameter(String name) {
List<String> list = getParameter(name);
if (list != null) {
return list.isEmpty() ? "" : list.get(0);
}
return null;
} | 2 |
public String getreasontext(){
return reason;
} | 0 |
public static void main(String[] args) {
if(args.length > 0){
String name = "./" + args[0];
File file = new File(name);
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(file));
String line;
while((line = in.readLine()) != null){
System.out.println(line);
}
} catch (FileNotFoundException ex){
System.out.println("File " + name + " does not exist.");
} catch (IOException ex){
ex.printStackTrace();
} finally {
closeReader(in);
}
}
} | 4 |
@Override
public int attack(double agility, double luck) {
if(random.nextInt(100) < luck)
{
System.out.println("I just did a guided attack!");
return random.nextInt((int) agility) * 2;
}
return 0;
} | 1 |
public boolean isCellEditable(int row, int col)
{
if (col > 1 && row != getRowCount() - 1 || col == 0)
{
return true;
}
return false;
} | 3 |
public void updateInterface() {
ItemStack is = null;
this.inventory.clear();
if(this.sort_mode == DeckEditor.SORT_NUMBER) {
Collections.sort(this.deck);
} else if(this.sort_mode == DeckEditor.SORT_ABC) {
Collections.sort(this.deck, DeckEditor.SORTER_ABC);
} else if(this.sort_mode == DeckEditor.SORT_ATK) {
Collections.sort(this.deck, DeckEditor.SORTER_ATK);
Collections.reverse(this.deck);
} else if(this.sort_mode == DeckEditor.SORT_DEF) {
Collections.sort(this.deck, DeckEditor.SORTER_DEF);
Collections.reverse(this.deck);
} else if(this.sort_mode == DeckEditor.SORT_TYPE) {
Collections.sort(this.deck);
Collections.sort(this.deck, DeckEditor.SORTER_TYPE);
} else if(this.sort_mode == DeckEditor.SORT_SHUFFLE) {
Collections.shuffle(this.deck);
}
int p = 0;
for(Integer card : this.deck) {
is = new ItemStack(Material.PAPER);
Duelist.createOwnedCardInfo(is, Card.fromId(card).copy());
if(this.sort_mode == DeckEditor.SORT_SHUFFLE) {
this.inventory.setItem(p, is);
p++;
} else {
this.inventory.addItem(is);
}
}
is = new ItemStack(Material.PAPER);
Main.setItemName(is, "Sort by: " + DeckEditor.getSortName(this.sort_mode));
Main.giveLore(is, 1);
Main.setItemData(is, 0, "Click to change");
this.inventory.setItem(44, is);
} | 8 |
public int next() {
int nextPos = index;
char c = desc.charAt(nextPos);
if (c == '(') {
++index;
c = desc.charAt(++nextPos);
param = true;
}
if (c == ')') {
++index;
c = desc.charAt(++nextPos);
param = false;
}
while (c == '[')
c = desc.charAt(++nextPos);
if (c == 'L') {
nextPos = desc.indexOf(';', nextPos) + 1;
if (nextPos <= 0)
throw new IndexOutOfBoundsException("bad descriptor");
}
else
++nextPos;
curPos = index;
index = nextPos;
return curPos;
} | 5 |
public AlumnoBean loadId(AlumnoBean oAlumno) throws NumberFormatException {
try {
if (request.getParameter("id") != null) {
oAlumno.setId(Integer.parseInt(request.getParameter("id")));
} else {
oAlumno.setId(0);
}
} catch (NumberFormatException e) {
throw new NumberFormatException("Controller: Error: Load: Formato de datos en parámetros incorrecto " + e.getMessage());
}
return oAlumno;
} | 2 |
static void readFile(String filename) throws IOException {
Scanner reader = new Scanner(new FileReader(filename));
String currentLine = reader.next();
boolean read1 = true;
boolean read2 = false;
Vertice currentVertice;
while (reader.hasNext()) {
if (!reader.hasNext("arestas") && read1) {
currentLine = reader.next();
currentVertice = new Vertice(Integer.parseInt(currentLine));
currentLine = reader.next();
currentVertice.setCoordenadaX(Double.parseDouble(currentLine));
currentLine = reader.next();
currentVertice.setCoordenadaY(Double.parseDouble(currentLine));
grafo.addVertice(currentVertice);
}
if (reader.hasNext("arestas")) {
read1 = false;
currentLine = reader.next();
read2 = true;
} else if (read2) {
currentLine = reader.next();
int o = Integer.parseInt(currentLine);
currentLine = reader.next();
int d = Integer.parseInt(currentLine);
currentLine = reader.next();
double custo = Double.parseDouble(currentLine);
grafo.addAresta(o, d, custo);
}
}
reader.close();
} | 5 |
@Override
public void execute(DebuggerVirtualMachine dvm) {
} | 0 |
public static int getTotalAchievementRecord() {
int totalRecords = 0;
try {
String statement = new String("SELECT COUNT(id) FROM " + DBTable);
PreparedStatement stmt = DBConnection.con.prepareStatement(statement);
ResultSet rs = stmt.executeQuery();
if (rs.next())
totalRecords = rs.getInt("COUNT(id)");
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
return totalRecords;
} | 2 |
private byte[] createChecksum() {
try {
InputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("MD5");
int numRead;
do {
numRead = fis.read(buffer);
if(numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while(numRead != -1);
fis.close();
return complete.digest();
} catch (FileNotFoundException e) {
System.out.println("Geen inputstream kunnen maken");
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
System.out.println("Geen MD5 algoritme kunnen laden");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Bestand niet kunnen lezen");
e.printStackTrace();
}
return null;
} | 5 |
public void input_samples(float[] s)
{
for (int i=31; i>=0; i--)
{
samples[i] = s[i]*eq[i];
}
} | 1 |
@Test
public void insertAddsAtTheBeginningOfList() {
l.insert(a);
l.insert(b);
assertEquals(b, l.min());
} | 0 |
public void dumpInstruction(TabbedPrintWriter writer)
throws java.io.IOException {
if (label != null) {
writer.untab();
writer.println(label + ":");
writer.tab();
}
writer.print("switch (");
instr.dumpExpression(writer.EXPL_PAREN, writer);
writer.print(")");
writer.openBrace();
for (int i = 0; i < caseBlocks.length; i++)
caseBlocks[i].dumpSource(writer);
writer.closeBrace();
} | 2 |
public static void main(String[] args){
try{
BufferedReader in=null;
if(args.length>0){
in = new BufferedReader(new FileReader(args[0]));
}
else{
in = new BufferedReader(new InputStreamReader(System.in));
}
ArrayList<String> input = new ArrayList<String>();
String inp = in.readLine();
while(inp!=null){
input.add(inp);
inp=in.readLine();
}
int nodeCount = input.size();
ArrayList<Edge> verticesList = new ArrayList<Edge>(nodeCount*3);
StringTokenizer st;
StringTokenizer stSplitter;
for(int i=0;i<nodeCount;i++){
st = new StringTokenizer((String)input.get(i));
while(st.hasMoreTokens()){
stSplitter = new StringTokenizer(st.nextToken(), ":");
verticesList.add(new Edge(i, Integer.parseInt(stSplitter.nextToken()), Integer.parseInt(stSplitter.nextToken())));
}
}
int verticesLen = verticesList.size();
Edge[] vertices = new Edge[verticesLen];
for (int i = 0; i < verticesLen; i++) {
vertices[i] = verticesList.get(i);
}
Arrays.sort(vertices);
System.out.println(new StringBuilder().append(mst(vertices, nodeCount)).toString());
}
catch(Exception e){
e.printStackTrace();
}
} | 6 |
private boolean agregaCatalogo(HttpServletRequest request, HttpServletResponse response) throws IOException {
ConexionBD con = new ConexionBD();
String descripcion = request.getParameter("descripcion");
String catalogo = request.getParameter("elegirCatalogo");
String tipo_familia = request.getParameter("select_catalogo_tipo_equipo");
if (catalogo.equals("") || descripcion.equals("")) {
return false;
} else {
if(catalogo.equals("catalogo_familia")){
if((!tipo_familia.equals("")) && !con.insertaCatalogoFamilia(descripcion, Integer.parseInt(tipo_familia))){
return true;
}else{
return false;
}
}else{
if(!con.insertaCatalogo(catalogo, descripcion)){
return true;
}else{
return false;
}
}
}
} | 6 |
static final int method1382(int i, int i_6_) {
anInt2463++;
if (i != 6406) {
if (i != 6409) {
if (i == 32841)
return 1;
if (i != 6410) {
if (i == 6407)
return 3;
if ((i ^ 0xffffffff) == -6409)
return 4;
} else
return 2;
} else
return 1;
} else
return 1;
if (i_6_ != -6409)
anIntArray2466 = null;
throw new IllegalArgumentException("");
} | 7 |
public Combination<Colors> getLastAttempt () {
Row lastRow = this.grid.get(grid.size() - 1);
return lastRow.getAttempt();
} | 0 |
public void union(int p, int q) {
if (!connected(p, q)) {
int pRoot = this.getRoot(p);
int qRoot = this.getRoot(q);
id[pRoot] = qRoot;
}
} | 1 |
public int getSmart() { // method422
int i = payload[offset] & 0xff;
if (i < 0x80) {
return getUnsignedByte();
} else {
return getUnsignedShort() - 0x8000;
}
} | 1 |
private void process_bmpcache2(RdpPacket_Localised data, int flags,
boolean compressed, Options option) throws RdesktopException,
IOException {
Bitmap bitmap;
int y;
int cache_id, cache_idx_low, width, height, Bpp;
int cache_idx, bufsize;
byte[] bmpdata, bitmap_id;
bitmap_id = new byte[8]; /* prevent compiler warning */
cache_id = flags & ID_MASK;
Bpp = ((flags & MODE_MASK) >> MODE_SHIFT) - 2;
Bpp = option.getColourDepthInBytes();
if ((flags & PERSIST) != 0) {
bitmap_id = new byte[8];
data.copyToByteArray(bitmap_id, 0, data.getPosition(), 8);
}
if ((flags & SQUARE) != 0) {
width = data.get8(); // in_uint8(s, width);
height = width;
} else {
width = data.get8(); // in_uint8(s, width);
height = data.get8(); // in_uint8(s, height);
}
bufsize = data.getBigEndian16(); // in_uint16_be(s, bufsize);
bufsize &= BUFSIZE_MASK;
cache_idx = data.get8(); // in_uint8(s, cache_idx);
if ((cache_idx & LONG_FORMAT) != 0) {
cache_idx_low = data.get8(); // in_uint8(s, cache_idx_low);
cache_idx = ((cache_idx ^ LONG_FORMAT) << 8) + cache_idx_low;
}
// in_uint8p(s, data, bufsize);
/*
//logger.info("BMPCACHE2(compr=" + compressed + ",flags=" + flags
+ ",cx=" + width + ",cy=" + height + ",id=" + cache_id
+ ",idx=" + cache_idx + ",Bpp=" + Bpp + ",bs=" + bufsize + ")");
*/
bmpdata = new byte[width * height * Bpp];
int[] bmpdataInt = new int[width * height];
if (compressed) {
if (Bpp == 1)
bmpdataInt = Bitmap.convertImage(
Bitmap.decompress(width, height, bufsize, data, Bpp),
Bpp, option);
else
bmpdataInt = Bitmap.decompressInt(width, height, bufsize, data,
Bpp, option);
if (bmpdataInt == null) {
//logger.debug("Failed to decompress bitmap data");
// xfree(bmpdata);
return;
}
bitmap = new Bitmap(bmpdataInt, width, height, 0, 0);
} else {
for (y = 0; y < height; y++)
data.copyToByteArray(bmpdata, y * (width * Bpp),
(height - y - 1) * (width * Bpp), width * Bpp); // memcpy(&bmpdata[(height
// - y -
// 1) *
// (width
// *
// Bpp)],
// &data[y
// *
// (width
// *
// Bpp)],
// width
// *
// Bpp);
bitmap = new Bitmap(Bitmap.convertImage(bmpdata, Bpp, option),
width, height, 0, 0);
}
// bitmap = ui_create_bitmap(width, height, bmpdata);
if (bitmap != null) {
cache.putBitmap(cache_id, cache_idx, bitmap, 0);
// cache_put_bitmap(cache_id, cache_idx, bitmap, 0);
if ((flags & PERSIST) != 0)
PstCache.pstcache_put_bitmap(cache_id, cache_idx, bitmap_id,
width, height, width * height * Bpp, bmpdata, option);
} else {
//logger.debug("process_bmpcache2: ui_create_bitmap failed");
}
// xfree(bmpdata);
} | 9 |
private void buttonServerControllerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonServerControllerActionPerformed
if (!Server.isRunning) {
try {
server = new Server();
serverThread = new Thread(server);
serverThread.start();
} catch (Exception e) {
printException(e);
}
} else {
if (server != null) {
try {
server.shutdown();
} catch (Exception e) {
printException(e);
}
}
serverThread = null;
server = null;
}
Server.isRunning = !Server.isRunning;
buttonServerController.setText((Server.isRunning ? "Stop" : "Start") + " Server");
}//GEN-LAST:event_buttonServerControllerActionPerformed | 5 |
public PeakData(String[] data) {
clear();
peakNum = data.length;
if (data.length == 1) {
if (data[0].split("\t")[0].equals("0") && data[0].split("\t")[1].equals("0")) {
peakNum = 0;
}
}
mz = new double[peakNum];
intensity = new int[peakNum];
selectPeakFlag = new boolean[peakNum];
String[] words;
for (int i=0; i<peakNum; i++) {
words = data[i].split("\t");
mz[i] = Double.parseDouble(words[0]);
intensity[i] = Integer.parseInt(words[1]);
}
} | 4 |
protected void UnpackArchives(JProgressBar progressCurr,JProgressBar progressBarTotal)
{
for(int i=0;i<FileCount;i++)
{
System.out.println(i+" Unzip "+ FileList[i]);
try {
Utils.deleteDirectory(getWorkingDirectory() + File.separator + GlobalVar.itemsServers[GlobalVar.CurrentServer]+ File.separator+".minecraft"+ File.separator+FileList[i].substring(0, FileList[i].length()-4)); //Рекурсивно вычищаем ее
if (FileList[i].equals("other.zip")) {
//Utils.deleteDirectory(getWorkingDirectory() + File.separator + GlobalVar.itemsServers[GlobalVar.CurrentServer]+ File.separator+".minecraft"+ File.separator+"config"); //Рекурсивно вычищаем ее
File t = new File(getWorkingDirectory() + File.separator + GlobalVar.itemsServers[GlobalVar.CurrentServer]+ File.separator+".minecraft"+ File.separator+"idfixminus.txt");
if (t.exists()) t.delete();
t = new File(getWorkingDirectory() + File.separator + GlobalVar.itemsServers[GlobalVar.CurrentServer]+ File.separator+".minecraft"+ File.separator+"servers.dat");
if (t.exists()) t.delete();
}
Utils.LogPrintConsole("Начинаю установку: "+FileList[i]);
UnZip(FileList[i],FileSize[i],progressCurr,progressBarTotal);
} catch (PrivilegedActionException ex) {
Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
}
}
} | 5 |
@Override
public boolean run() {
if (verbose) Timer.showStdErr("Checking database using CDS sequences");
// Load config
if (config == null) loadConfig();
// Read CDS form file
if (verbose) Timer.showStdErr("Reading CDSs from file '" + cdsFile + "'...");
readCdsFile(); // Load CDS
if (verbose) Timer.showStdErr("done (" + cdsByTrId.size() + " CDSs).");
// Load predictor
if (config.getSnpEffectPredictor() == null) {
if (verbose) Timer.showStdErr("Reading database...");
config.loadSnpEffectPredictor(); // Read snpEffect predictor
if (verbose) Timer.showStdErr("done");
}
// Compare CDS
if (verbose) Timer.showStdErr("Comparing CDS...");
cdsCompare();
if (verbose) Timer.showStdErr("done");
return true;
} | 9 |
public String getHoraEncargo() {
return horaEncargo;
} | 0 |
public Game(CLayout layout, JPanel panelContainer ){
// Point to the files you would like to use for the display
// To switch levels all you have to do is change these three lines
String dir = layout.getDirectory("level");
if( layout.level1 ){
abovePath = dir + "Level1-Over.png";
belowPath = dir + "Level1-Under.png";
maskPath = dir + "Level1-Mask.png";
layout.level1 = false;
}else if( layout.level2 ){
abovePath = dir + "Level2-Over.png";
belowPath = dir + "Level2-Under.png";
maskPath = dir + "Level2-Mask.png";
layout.level2 = false;
}else if( layout.level3 ){
abovePath = dir + "Level3-Over.png";
belowPath = dir + "Level3-Under.png";
maskPath = dir + "Level3-Mask.png";
layout.level3 = false;
}
// Before, I had to substring the filepath differently while working on OS X.
// Currently I do not know if I have to do that with the new version
// String os = System.getProperty( ("os.name") );
// if( os.contains("Windows") ){
// abovePath = abovePath.substring(1);
// belowPath = belowPath.substring(1);
// maskPath = maskPath.substring(1);
// }else if( os.contains("Mac") ){
// abovePath = abovePath.substring(0);
// belowPath = belowPath.substring(0);
// maskPath = maskPath.substring(0);
// }
// Create an ImageLoader to load all of the pictures for us.
imgLoader = new ImageLoader( abovePath, belowPath, maskPath );
// Create the new game panel!
MainGameScreen w = new MainGameScreen( imgLoader, layout, panelContainer );
layout.panelContainer.add(w, "5");
layout.cl.show(panelContainer, "5");
} | 3 |
private void renderMenu(Graphics g){
FontUtils.drawCenter(TowerGame.ricasso30, "Peachtree Tower", 165, 60, 470, Color.white);
FontUtils.drawCenter(TowerGame.ricasso20, "Start Game", 165, 125, 470, Color.gray);
FontUtils.drawCenter(TowerGame.ricasso20, "Options", 165, 155, 470, Color.gray);
switch (main){
case 1:
FontUtils.drawCenter(TowerGame.ricasso20, "- Start Game -", 165, 125, 470, Color.white);
break;
case 2:
FontUtils.drawCenter(TowerGame.ricasso20, "- Options -", 165, 155, 470, Color.white);
break;
}
} | 2 |
void hookExampleWidgetListeners () {
if (logging) {
Widget[] widgets = getExampleWidgets ();
for (int i = 0; i < widgets.length; i++) {
hookListeners (widgets [i]);
}
Item[] exampleItems = getExampleWidgetItems ();
for (int i = 0; i < exampleItems.length; i++) {
hookListeners (exampleItems [i]);
}
String [] customNames = getCustomEventNames ();
for (int i = 0; i < customNames.length; i++) {
if (eventsFilter [EVENT_NAMES.length + i]) hookCustomListener (customNames[i]);
}
}
} | 5 |
private void genericTest(int rows, int columns,String chessPiecesStr,
String[] expectedRepresentationString){
List<Piece> pieces;
pieces = ChessTools.getPiecesFromString(chessPiecesStr);
Cell[] chessBoard;
chessBoard = new Cell[rows * columns];
Arrays.fill(chessBoard, Cell.DEFAULT_EMPTY_CELL);
ChessGameConfiguration cgc = new ChessGameConfiguration(chessBoard,rows,columns);
ChessGameConfiguration[] results = searchEngine.search(cgc, pieces);
boolean fault = false;
if (results.length == expectedRepresentationString.length){
for(int i= 0; i < results.length && !fault; i++){
BigInteger biRepresentation = ChessTools.calculateRepresentationNumber(results[i].getCurrentBoard());
String alfabet = ChessConstants.CHESS_BOARD_REPRESENTATION_ALFABET;
String currentRepresentationString = ChessTools.convertToRepresentationString(biRepresentation, alfabet.toCharArray());
fault = !currentRepresentationString.equals(expectedRepresentationString[i]);
}
}else{
fault = true;
}
assertFalse(fault);
} | 3 |
public boolean isConstExpression() {
if (target != null || src != null) {
return false;
}
if (lValue != null && rValue != null) {
return true;
}
return lValue != null;
} | 4 |
public static Keyword continueAntecedentsProof(ControlFrame frame, Keyword lastmove) {
{ Iterator iterator = ((Iterator)(KeyValueList.dynamicSlotValue(frame.dynamicSlots, Logic.SYM_STELLA_ITERATOR, null)));
boolean firsttimeP = iterator == null;
boolean reversepolarityP = frame.reversePolarityP;
if (lastmove == Logic.KWD_UP_TRUE) {
{ Proposition object000 = ((Proposition)(KeyValueList.dynamicSlotValue(frame.dynamicSlots, Logic.SYM_LOGIC_ANTECEDENTS_RULE, null)));
Stella_Object oldValue000 = object000.truthValue;
frame.truthValue = TruthValue.weakenTruthValue(ControlFrame.propagateFrameTruthValue(frame.result, frame), ((TruthValue)(Stella_Object.accessInContext(oldValue000, object000.homeContext, false))));
}
if (((Boolean)(Logic.$RECORD_JUSTIFICATIONSp$.get())).booleanValue()) {
ControlFrame.recordModusPonensJustification(frame, lastmove);
}
return (Logic.KWD_CONTINUING_SUCCESS);
}
else {
}
if (firsttimeP) {
iterator = Description.allocateAntecedentsIterator(ControlFrame.extractSubgoalDescriptionOfFrame(frame), ControlFrame.findExternalArgumentsForSubgoal(frame), reversepolarityP);
if (iterator == null) {
return (Logic.KWD_FAILURE);
}
KeyValueList.setDynamicSlotValue(frame.dynamicSlots, Logic.SYM_STELLA_ITERATOR, iterator, null);
}
loop000 : while (iterator.nextP()) {
{ Proposition impliesproposition = ((Proposition)(iterator.value));
Description antecedentdescription = (reversepolarityP ? ((Description)((impliesproposition.arguments.theArray)[1])) : ((Description)((impliesproposition.arguments.theArray)[0])));
if (ControlFrame.checkForDuplicateRuleP(frame, impliesproposition)) {
continue loop000;
}
KeyValueList.setDynamicSlotValue(frame.dynamicSlots, Logic.SYM_LOGIC_ANTECEDENTS_RULE, impliesproposition, null);
if (!Proposition.trueP(impliesproposition)) {
if (Proposition.getForwardGoals(impliesproposition).emptyP()) {
continue loop000;
}
else {
{
ControlFrame.createConditionalAntecedentSubframe(frame, frame.proposition, impliesproposition);
return (Logic.KWD_MOVE_DOWN);
}
}
}
{ ControlFrame downframe = ControlFrame.createSubgoalFrame(frame, null, Logic.KWD_FULL_SUBQUERY);
KeyValueList.setDynamicSlotValue(downframe.dynamicSlots, Logic.SYM_LOGIC_DESCRIPTION, antecedentdescription, null);
return (Logic.KWD_MOVE_DOWN);
}
}
}
return (Logic.KWD_FAILURE);
}
} | 9 |
private void cull() {
Node child;
outer: for (Iterator<Node> i = children.iterator(); i.hasNext();) {
child = i.next();
for (Node otherChild : children) {
if (otherChild == child)
continue;
if (otherChild.hasChild(child.name) != null) {
i.remove();
continue outer;
}
}
}
for (Node c : children)
c.cull();
} | 5 |
public List<Account> findDeliquentAccounts() throws Exception {
ArrayList<Account> delinquentAccounts = new ArrayList<>();
List<Account> accounts = accountDao.findAllAccounts();
Date thirtyDaysAgo = daysAgo(30);
for (Account account : accounts) {
boolean owesMoney = account.getBalance()
.compareTo(BigDecimal.ZERO) > 0;
boolean thirtyDaysLate = account.getLastPaidOn()
.compareTo(thirtyDaysAgo) <= 0;
if (owesMoney && thirtyDaysLate) {
delinquentAccounts.add(account);
}
}
return delinquentAccounts;
} | 3 |
public static PeopleData createNewPeopleData(String key, String value, UUID person_id) {
if (key != null && value != null && person_id != null) {
return new PeopleData(key, value, person_id);
} else if (key != null) {
return new PeopleData(key, null, person_id);
} else if (value != null) {
return new PeopleData(null, value, person_id);
} else if (person_id != null) {
return new PeopleData(null, null, person_id);
}
return null;
} | 6 |
public void simulate() {
Gdx.app.log("Funding", funding+"");
if(!unused) {
Random r = new Random();
population+=(10000*funding*(1-(parent.getSurvivabiliy()/100.0f)));
Gdx.app.log("POPULUS", population+"pp");
if(r.nextFloat()<(1-(parent.getSurvivabiliy()/100.0f))) {
if(r.nextInt(100)<=40-(funding/10.0f)) {
population -= (1000-funding);
} else {
population *= 0.5;
}
}
if(population>=100000) {
//Gdx.app.log("CONGRATULATIONS ON "+parent.getName(), "You succeded to colonise");
parent.player.eventPool.add(new Event(parent.player, parent.textures.getTexture("colony_event"), new String[] {"Long may it continue!"}, "On "+parent.getName()+" a colony named "+name+" has gathered enough population to make a new colony.", "CONGRATULATIONS ON "+parent.getName()+"!") {
@Override
public void action(int selectionID) {
// TODO Auto-generated method stub
}
});
parent.successColony(this);
unused = true;
} else if(population<=100) {
//Gdx.app.log("DISASTER ON "+parent.getName(), "You failed to colonise");
parent.failureColony(this);
unused = true;
parent.player.eventPool.add(new Event(parent.player, parent.textures.getTexture("event_filler"), new String[] {"We must leave it alone.", "We must revive the colony. (Recreate the colony with 100 funding)."}, "On "+parent.getName()+" a colony named "+name+" has been ravaged by a giant beast.", "DISASTER ON "+parent.getName()+"!") {
@Override
public void action(int selectionID) {
switch(selectionID) {
case 1:
if(parent.player.Money-5100>=0) {
parent.startColony();
parent.colony.funding = 100;
parent.player.changeMoney(-5100);
}
break;
}
}
});
}
completionPc = population/1000000;
}
} | 7 |
private MenuScreen()
{
super("img/menu/bgmenu.png", "img/menu");
curseur = new CursorMenu("img/menu/cursor.png");
stage = new Stage();
curseur.setPosition(curseur.getX(), curseur.getY());
sprite = new Sprite(new Texture(Gdx.files.internal("img/menu/bgmenu2.png")));
sprite.setPosition(0, 0);
stage.addListener(new InputListener()
{
public boolean keyDown(InputEvent event, int keyCode)
{
if (keyCode == Input.Keys.UP)
{
curseur.monter();
return true;
}
if (keyCode == Input.Keys.DOWN)
{
curseur.descendre();
return true;
}
if (keyCode == Input.Keys.ENTER)
{
Sound musique = Gdx.audio.newSound(Gdx.files.internal("sounds/timber.wav"));
musique.play();
switch (curseur.getPosition())
{
case 1:
((com.badlogic.gdx.Game) Gdx.app.getApplicationListener())
.setScreen(GameScreen.getInstance());
return true;
case 2:
((com.badlogic.gdx.Game) Gdx.app.getApplicationListener())
.setScreen(new ControlScreen());
return true;
case 3:
((com.badlogic.gdx.Game) Gdx.app.getApplicationListener())
.setScreen(new CreditScreen());
return true;
case 4:
Gdx.app.exit();
return true;
case 5:
Gdx.app.exit();
return true;
default:
return false;
}
}
return false;
}
});
Gdx.input.setInputProcessor(stage);
} | 8 |
public SessionList getSessions(String asLastModified, int aiMaxSize) {
String lsParam = "";
if (aiMaxSize > 0) {
lsParam += "&max_size=" + Integer.toString(aiMaxSize);
}
if (UtilityMethods.isValidString(asLastModified)) {
lsParam += "&last_modified=" + asLastModified;
}
if (UtilityMethods.isValidString(lsParam)) {
lsParam = lsParam.replaceFirst("&", "?");
}
return get(SessionList.class, REST_URL_SESSIONS + lsParam);
} | 3 |
private boolean camposNecesarios () {
if ((jTextField1.getText().length()==0) ||
(jTextField2.getText().length()==0) ||
(jTextField3.getText().length()==0) ||
(jTextField4.getText().length()==0) ||
(jTextField5.getText().length()==0) ||
(jTextField6.getText().length()==0))
{
JOptionPane.showMessageDialog(null, "Complete todos los campos!","Atención",JOptionPane.WARNING_MESSAGE);
return false;
}
return true;
} | 6 |
public void main(){
Scanner s = new Scanner(System.in);
PiggyBank_HIWHD pb = new PiggyBank_HIWHD();
boolean cont = true;
while (cont){
System.out.println("1. Show total in bank.");
System.out.println("2. Add a penny.");
System.out.println("3. Add a nickel.");
System.out.println("4. Add a dime.");
System.out.println("5. Add a quarter.");
System.out.println("6. Take money out of the bank.");
System.out.println("Enter 0 to exit.");
System.out.print("Enter your choice: ");
switch (s.nextInt()){
default:
case 1:
System.out.println("You have: $" + pb.value);
break;
case 2:
pb.value += 0.01;
System.out.println("You now have: $" + pb.value);
break;
case 3:
pb.value += 0.05;
System.out.println("You now have: $" + pb.value);
break;
case 4:
pb.value += 0.10;
System.out.println("You now have: $" + pb.value);
break;
case 5:
pb.value += 0.25;
System.out.println("You now have: $" + pb.value);
break;
case 6:
System.out.print("Enter an amount to remove: ");
pb.value -= s.nextDouble();
System.out.println("You now have: $" + pb.value);
break;
case 0:
cont = false;
}
}
} | 8 |
public String longestPalindrome2(String s) {
if (s == null || s.length() == 0) {
return s;
}
mapping = new boolean[s.length()][s.length()];
calculated = new boolean[s.length()][s.length()];
for (int k = s.length() - 1; k >= 0; k--) {
for (int i = 0; i < s.length() - k; i++) {
int j = i + k;
if (isPalindrome(s, i, j)) {
return s.substring(i, j + 1);
}
}
}
return null;
} | 5 |
private void setupUndoRedo() {
// Listen for undo and redo events
doc.addUndoableEditListener(new UndoableEditListener() {
public void undoableEditHappened(UndoableEditEvent evt) {
undo.addEdit(evt.getEdit());
}
});
// Create an undo action and add it to the text component
lyricBox.getActionMap().put("Undo",
new AbstractAction("Undo") {
/**
*
*/
private static final long serialVersionUID = 1565063027867235847L;
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canUndo()) {
undo.undo();
}
} catch (CannotUndoException e) {
}
}
});
// Bind the undo action to ctl-Z
lyricBox.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");
// Create a redo action and add it to the text component
lyricBox.getActionMap().put("Redo",
new AbstractAction("Redo") {
/**
*
*/
private static final long serialVersionUID = -4202651192510434020L;
public void actionPerformed(ActionEvent evt) {
try {
if (undo.canRedo()) {
undo.redo();
}
} catch (CannotRedoException e) {
}
}
});
// Bind the redo action to ctl-Y
lyricBox.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");
} | 4 |
double test7( ) throws MiniDB_Exception{
double points = 0;
// IN_SOLUTION_START
MiniDB db = new MiniDB( "minidb.test7" );
BufMgr bm = db.getBufMgr();
int size = 8;
BPlusTree bpt = db.createNewBPlusTreeIndex( "table", "val", 8 );
int iters = 300;
java.util.Hashtable val2blk = new java.util.Hashtable();
MiniDB_Record insertedRecords[] = new MiniDB_Record[iters];
System.out.println( "At start, " + db.numBlocksInDB() + " blocks " );
// add a bunch of values
for (int i=0; i<iters; i++){
//long value = -i*2;
long value = ((int)Math.pow(-1, i))*i*2;
int blockID = (i+1)*100;
MiniDB_Record rec = new MiniDB_Record(blockID, value);
bpt.insertRecord(value, blockID);
val2blk.put( value, blockID );
insertedRecords[i] = new MiniDB_Record(blockID, value );
System.out.println( "insert " + rec );
System.err.println( "insert " + i + ") of " + iters + ", " + rec );
// System.out.println( "After " + (i+1) + ", " + db.numBlocksInDB() + " blocks " );
//
//System.out.println( "i is " + i + ", Inserted value " + value + ", block " + blockID );
}
System.out.println( "+ 0.5 points for not crashing so far" );
System.err.println( "+ 0.5 points for not crashing so far" );
points = 0.5;
int expectedVal = 84;
int testVal = db.numBlocksInDB();
System.out.println( "Number of blocks in DB is " + testVal + ", expected " + expectedVal );
if( expectedVal == testVal ){ points++; System.out.println( " +1" ); }else{ System.out.println( " incorrect" ); }
BPlusTreeNode nodes[] = bpt.getPathForValue( 0 );
expectedVal = nodes.length;
testVal = 4;
System.out.println( "Height of tree is " + testVal + ", expected " + expectedVal );
if( expectedVal == testVal ){ points++; System.out.println( " +1" ); }else{ System.out.println( " incorrect" ); }
MiniDB_Block blk = bpt.getRootNode();
expectedVal = MiniDB_Block.BLOCK_TYPE_BPT_INTERNAL;
testVal = blk.getBlockType();
System.out.println( "Block type is " + testVal + ", expected " + expectedVal );
if( expectedVal == testVal ){ System.out.println( " +1" ); points++; }else{ System.out.println( " incorrect" ); }
// get all values
Arrays.sort( insertedRecords );
Vector vValues = new Vector();
Vector vBlkIDs = new Vector();
bpt.getAll( vValues, vBlkIDs );
int numCorrect = 0;
for (int i=0; i<iters; i++){
Long lVal = (Long)vValues.get(i);
Integer iblockID = (Integer)vBlkIDs.get(i);
MiniDB_Record recGot = new MiniDB_Record( iblockID, lVal );
MiniDB_Record recExp = insertedRecords[i];
System.out.println( "expected " + recExp + ", got " + recGot );
if( recGot.equals( recExp ) ){
numCorrect++;
}
else{
}
}
double pointsPart2 = 10.0* (numCorrect / (double)iters);
System.out.println( " " + points + " for structure checks " );
System.out.println( " + " + pointsPart2 + " for getting " + numCorrect + " of " + iters + " lookups correct." );
points += pointsPart2;
System.out.println( " totl for split() test --> " + points );
// IN_SOLUTION_END
return points;
} | 6 |
public void cargarArbol() {
int count = 0;
int aux = 1;
int entre = 0;
Enumeration e = root1.breadthFirstEnumeration();
while (e.hasMoreElements()) {
parent1 = (DefaultMutableTreeNode) e.nextElement();
if (count >= aux) {
CLS_ITEM_CONTA objChildren = (CLS_ITEM_CONTA) parent1.getUserObject();
//consigo los hijos de idparent
System.out.println(objChildren.Descripcion);
vecChildren = clsConta.getChildrenC(objChildren.Id);
for (int k = 0; k < vecChildren.size(); k++) {
CLS_ITEM_CONTA hijo = (CLS_ITEM_CONTA) vecChildren.get(k);
//hijo.setDescrip(hijo.getCodigo_PC()+"-"+hijo.getNombre_C());
System.out.println(" -> "+hijo.Descripcion);
childnode = new DefaultMutableTreeNode(hijo);
modelo1.insertNodeInto(childnode, parent1, parent1.getChildCount());
}
}
//Pregunto si llego al fin.
if (e.hasMoreElements() == false) {
int toEle = totalElementos(root1.breadthFirstEnumeration());
System.out.println(">>> ENTRE EN HASMORE toEle: "+toEle+" bcount: "+bcount+" count: "+count);
if (bcount < toEle) {
System.out.println("-----------------");
if (entre==0){
aux = count;
count = -2;
entre+=1;
}
else{
aux = count+1;
count = -2;
}
e = root1.breadthFirstEnumeration();
bcount = toEle;
} else {
// JOptionPane.showMessageDialog(this, "Ya no hay mas hijos");
break;
}
}
count++;
}
} | 6 |
private void addClassesInFolder(List<String> classes, File folder, String packageName, boolean recurse) {
for (File f : folder.listFiles()) {
if (!f.isDirectory()) {
if (f.getName().endsWith(".class")) {
classes.add(packageName + "." + f.getName().substring(0, f.getName().length() - 6));
}
} else if (f.isDirectory() && recurse) {
addClassesInFolder(classes, f, packageName + "." + f.getName(), recurse);
}
}
} | 5 |
@Override
public Rule getSimmilarRule(Rule rule) {
List<Rule> possibleResults = new ArrayList<Rule>();
for (Rule r : rules) {
if (r.isSimmilar(rule)) {
possibleResults.add(r);
}
}
if (possibleResults.isEmpty()) {
return rule;
} else {
return possibleResults.get((new Random()).nextInt(possibleResults.size()));
}
} | 3 |
private HashMap<String, String> transformAttributes(String string)
{
// Prepare the attribute-map!
HashMap<String, String> map = new HashMap<String, String>(2);
// Consume the String word by word...
while(string.length() > 0)
{
// Trim whitespaces, if there are any.
string = string.trim();
// Possible words we may encounter:
// property_key
// =
// "a literal value !"
// property_key> (Mind the '>'!)
// Find the end of the next word
int endOfTheWord = this.findEndOfAttributeWord(string);
// temporary key field
String key = null;
// Cut out the next word! (which is a 'key')
{
String word = string.substring(0, endOfTheWord);
string = string.substring(endOfTheWord).trim();
key = word;
}
if(string.length() == 0)
{
// key only: Treat the key as a 'flag'-attribute (which has no content other than itself).
map.put(key, "");
break;
}
if(string.charAt(0) == '=')
{
// key/value
string = string.substring(1).trim();
String value = null;
// Find the end of the value word!
int endOfTheWord2 = this.findEndOfAttributeWord(string);
{
String word = string.substring(0, endOfTheWord2);
string = string.substring(endOfTheWord2).trim();
value = word;
}
// If the value is surrounded by '"' on both start and end, cut them away.
if((value.length() >= 2) && (value.charAt(0) == '"') && (value.charAt(value.length()-1) == '"'))
{
value = value.substring(1, value.length()-1);
}
map.put(key, value);
}
else
{
// key only: Treat the key as a 'flag'-attribute (which has no content other than itself).
map.put(key, key);
}
}
// If there is nothing inside the map, throw it away and return null!
if(map.size() == 0)
{
return null;
}
// Return the attributes for further usage.
return map;
} | 7 |
private void searchJyusyo1(String jyusyo1) {
comboTodoufuken.removeAllItems();
comboTodoufuken.addItem("絞り込み");
comboTodoufuken.setSelectedIndex(0);
lstM.clear();
//CSVファイルの読み込み
File csv = null;
try {
csv = new File("KEN_ALL.CSV");
BufferedReader br; // close 忘れずに!!!
br = new BufferedReader(new InputStreamReader(new FileInputStream(csv), "MS932"));
String line = "";
boolean find = false;
while ((line = br.readLine()) != null) {
String[] strArr = line.split(",");
//System.err.println(strArr[2]);
String zipcode = strArr[2].replaceAll("\"", "");
//System.err.println(zipcode);
if (line.indexOf(jyusyo1) >= 0) {
// textJyusyo1.setText(strArr[6].replaceAll("\"", "") + strArr[7].replaceAll("\"", ""));
// textJyusyo2.setText(strArr[8].replaceAll("\"", ""));
lstM.addElement(line);
//都道府県絞り込み用コンボボックス設定
String ken = strArr[6].replaceAll("\"", "");
boolean todo = false;
for (int i = 0; i < comboTodoufuken.getItemCount(); i++) {
if (comboTodoufuken.getItemAt(i).equals(ken)) {
todo = true;
}
}
if (!todo) {
comboTodoufuken.addItem(ken);
}
find = true;
}
}
br.close();
if (!find) {
JOptionPane.showMessageDialog(this, "指定された住所が郵便番号CSVに見つかりません。");
}
} catch (FileNotFoundException e) {
// Fileオブジェクト生成時の例外捕捉
e.printStackTrace();
JOptionPane.showMessageDialog(this, "郵便番号CSVファイルがありません。\n" + csv.getAbsolutePath());
} catch (IOException e) {
// BufferedReaderオブジェクトのクローズ時の例外捕捉
e.printStackTrace();
JOptionPane.showMessageDialog(this, "エラーが発生しました");
}
} | 8 |
public void setHistoryLocation(int i) {
this.history_location = i;
if (this.history_location <= 0) {
this.prevButton.setEnabled(false);
} else {
this.prevButton.setEnabled(true);
}
//System.out.println(this.history_location + ":" + history.getSize());
if (this.history_location >= history.getSize() - 1) {
this.nextButton.setEnabled(false);
} else {
this.nextButton.setEnabled(true);
}
} | 2 |
@Override
public void update(long deltaMs) {
switch(firingMode) {
case FIRE_AT_ACTOR_MODE:
targetActor();
break;
case FIRE_AT_LOCATION_MODE:
targetLocation();
break;
}
} | 2 |
public static void exhaustiveAntiGoalRefineAnalysis(RequirementGraph req_model, ActorAssociationGraph actor_model, int visual_type, int scope) throws IOException, ScriptException {
// first empty the potential security goal set.
req_model.ag_elems.clear();
req_model.ag_links.clear();
String expression_file = req_model.generateFormalExpressionToFile(scope);
String security_model_file = InfoEnum.current_directory+"/dlv/models/security_model_"+req_model.getLayer().toLowerCase()+".dl ";
String threat_knowledge = InfoEnum.current_directory+"/dlv/anti_goal_rules/threat_knowledge.rule ";
String refine_rule = "";
refine_rule = InfoEnum.current_directory+"/dlv/dlv -silent -nofacts "
+ InfoEnum.current_directory+"/dlv/anti_goal_rules/refine_all.rule "
+ InfoEnum.current_directory+"/dlv/models/asset_model.dl "
+ expression_file + security_model_file + threat_knowledge;
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(refine_rule);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
// parse inference results
while ((line = input.readLine()) != null) {
line = line.substring(1, line.length() - 1);
String[] result = line.split(", ");
//Assign all security goals with ordered numbers, which are just used as identifiers.
int number = 1;
for (String s : result) {
// only consider related security goals
if (s.startsWith("ex_refined_anti_goal") && !s.contains("unknown")) {
// parse facts
s = s.replaceAll("ex_refined_anti_goal\\(", "");
s = s.replaceAll("\\)", "");
String[] ag = s.split(",");
// create two anti goals, and the refinement relation between them.
AntiGoal child_ag = req_model.findExhausiveAntiGoalByAttributes(ag[0], ag[1], ag[2], ag[3]);
AntiGoal parent_ag = req_model.findExhausiveAntiGoalByAttributes(ag[4], ag[5], ag[6], ag[7]);
//add elements to the anti goal graph
if (child_ag == null) {
child_ag = new AntiGoal(ag[0], ag[1], ag[2], ag[3],
InfoEnum.RequirementElementType.ANTI_GOAL.name(), req_model.getLayer());
child_ag.setId(String.valueOf(number));
number++;
req_model.ag_elems.add(child_ag);
}
if (parent_ag == null) {
parent_ag = new AntiGoal(ag[4], ag[5], ag[6], ag[7],
InfoEnum.RequirementElementType.ANTI_GOAL.name(), req_model.getLayer());
parent_ag.setId(String.valueOf(number));
number++;
req_model.ag_elems.add(parent_ag);
}
// create the new refinement link (by default is "and")
RequirementLink new_and_refine = new RequirementLink(
InfoEnum.RequirementLinkType.AND_REFINE.name(), child_ag, parent_ag);
new_and_refine.refine_type = ag[8];
// change the type of the link, if necessary
if(new_and_refine.refine_type.contains("o_")){
new_and_refine.setType(InfoEnum.RequirementLinkType.REFINE.name());
}
//the refinement links should always be added, as there may be several elements that refine/be refined to one element.
if(!req_model.ag_links.contains(new_and_refine)){
req_model.ag_links.add(new_and_refine);
}
//add the refinement link to the target anti goal
if(new_and_refine.getType().equals(InfoEnum.RequirementLinkType.AND_REFINE.name())){
parent_ag.and_refine_links.add(new_and_refine);
} else{
parent_ag.refine_links.add(new_and_refine);
}
child_ag.parent = parent_ag;
child_ag.parent_link = new_and_refine;
}
}
}
//visualize exhaustive refinements via Graphviz
// if(visual_type==InfoEnum.GRAPHVIZ){
// // graphviz can generate the three view separately
// visualizeGraph(req_model, actor_model, InfoEnum.GRAPHVIZ, InfoEnum.INITIAL_VIEW);
// visualizeGraph(req_model, actor_model, InfoEnum.GRAPHVIZ, InfoEnum.HIGHLIGHT_VIEW);
// visualizeGraph(req_model, actor_model, InfoEnum.GRAPHVIZ, InfoEnum.SIMPLIFIED_VIEW);
// }else if (visual_type == InfoEnum.CANVAS){
// // we only provide one view in the canvas
visualizeEAGGraph(req_model, actor_model, InfoEnum.CANVAS, InfoEnum.INITIAL_VIEW);
// // the highlight and simpliefied view are put together in one view
// visualizeGraph(req_model, actor_model, InfoEnum.CANVAS, InfoEnum.HIGHLIGHT_VIEW);
// }
// else{
// CommandPanel.logger.warning("Visualization type error!");
// }
} | 9 |
private void loop(){
while(true){
try{
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
if(totalTime > 1000){
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
beginTime = System.currentTimeMillis();
//Draw the buffer.
Constants.getGameCanvas().draw();
timeTaken = System.currentTimeMillis() - beginTime;
timeLeft = (UPDATE_PERIOD - timeTaken);
if(timeLeft < 10) timeLeft = 10;
try {
Thread.sleep(timeLeft);
}catch(InterruptedException ex){break;}
}catch(Exception e){}
}
} | 5 |
String checkSecurity(int iLevel, javax.servlet.http.HttpSession session, javax.servlet.http.HttpServletResponse response, javax.servlet.http.HttpServletRequest request){
try {
Object o1 = session.getAttribute("UserID");
Object o2 = session.getAttribute("UserRights");
boolean bRedirect = false;
if ( o1 == null || o2 == null ) { bRedirect = true; }
if ( ! bRedirect ) {
if ( (o1.toString()).equals("")) { bRedirect = true; }
else if ( (new Integer(o2.toString())).intValue() < iLevel) { bRedirect = true; }
}
if ( bRedirect ) {
response.sendRedirect("Login.jsp?querystring=" + toURL(request.getQueryString()) + "&ret_page=" + toURL(request.getRequestURI()));
return "sendRedirect";
}
}
catch(Exception e){};
return "";
} | 7 |
protected void processWindowEvent(
WindowEvent event )
{
if ( event.getID() == WindowEvent.WINDOW_CLOSING )
actionExit();
super.processWindowEvent(event);
} | 1 |
private static NodeList getNodeList() {
NodeList nList = null;
try {
File fXmlFile = new File(path);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
nList = doc.getElementsByTagName(galleryTagName);
} catch (Exception ex) {
ex.printStackTrace();
}
return nList;
} | 1 |
public void connect() throws ConnectionException, IOException {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(playlist)));
}
catch(IOException e) {
throw new ConnectionException(e);
}
String filename;
while((filename = bufferedReader.readLine()) != null) {
filename = filename.trim();
// ignore comments
if(!filename.startsWith("#")) {
filenames.add(filename);
}
}
if(filenames.isEmpty())
throw new ConnectionException("The playlist is empty");
boolean noFileFound = true;
while(noFileFound) {
try {
switchInputStream();
noFileFound = false;
}
catch(IOException e) {
Fluid.error(e);
}
}
if(filenames.isEmpty())
throw new ConnectionException("None of the files in the playlist could be found");
connected = true;
} | 7 |
@Override
public void run() {
int found = 0;
int number = 11;
int answer = 0;
while(found < 11) {
if(PrimeUtil.isPrime(number)) {
String num = String.valueOf(number);
boolean allPrimes = true;
int i = 1;
while(i < num.length()) {
if(!PrimeUtil.isPrime(Long.valueOf(num.substring(i)).longValue())) {
allPrimes = false;
}
i++;
}
i = num.length() - 1;
while(i > 0) {
if(!PrimeUtil.isPrime(Long.valueOf(num.substring(0, i)).longValue())) {
allPrimes = false;
}
i--;
}
if(allPrimes) {
answer += number;
System.out.println(number);
found++;
}
}
number += 2;
}
setAnswer(String.valueOf(answer));
} | 7 |
public static void RememberMeSave(boolean state, int ID, String Username, int Code, String Password, String Ticks, String Destination){
Code = Code/LoginWindow.verificationcode;
String gameFolderPath, gameFilePath;
gameFolderPath = System.getenv().get("APPDATA") + "\\TFrame";
gameFilePath = gameFolderPath + "\\RememberMe.txt";
File gameFolder = new File(gameFolderPath);
if (!gameFolder.exists()) {
// Folder doesn't exist. Create it
if (gameFolder.mkdir()) {
// Folder created
File gameFile = new File(gameFilePath);
if (!gameFile.exists()) {
// File doesn't exists, create it
try {
if (gameFile.createNewFile()) {
// mGameFile created in %APPDATA%\myGame !
}
else {
// Error
}
} catch (IOException ex) {
// Handle exceptions here
}
}
else {
// File exists
}
}
else {
// Error
}
}
else {
// Folder exists
}
File file = new File(gameFilePath);
PrintWriter writer = null;
try {
writer = new PrintWriter(new FileWriter(file, true));
writer.println(DataCrypter.encrypt3(String.valueOf(state)));
writer.println(DataCrypter.encrypt3(String.valueOf(ID)));
writer.println(DataCrypter.encrypt3(Username));
writer.println(DataCrypter.encrypt3(String.valueOf(Code)));
writer.println(DataCrypter.encrypt3(Password));
writer.println(DataCrypter.encrypt3(Ticks));
writer.println(DataCrypter.encrypt3(Destination));
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
writer.close();
}
} | 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(MainMenuFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainMenuFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainMenuFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainMenuFrame.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 MainMenuFrame().setVisible(true);
}
});
} | 6 |
public LoadingFrame()
{
try {
setIconImage(ImageIO.read(new File("assets/Icon48.png")));
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
setTitle("Map of Denmark");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
requestFocus();
setLocationRelativeTo(null);
setUndecorated(true);
MigLayout migMainLayout = new MigLayout("", "10[center]10[center]10", "10[center]10[center]10");
mainContainer = new JPanel(migMainLayout);
getContentPane().add(mainContainer);
messageField = new AAJLabel("Step 1/4 - Loading nodes...");
messageField.setFont(FontLoader.getFontWithSize("Roboto-Bold", 14f));
loadingBar = new loadingComponent();
mainContainer.add(messageField, "cell 0 0");
mainContainer.add(loadingBar, "cell 0 1, width 501:501:501, height 51:51:51");
loadingBar.addMouseMotionListener(this);
revalidate();
repaint();
pack();
setLocationRelativeTo(null);
setVisible(true);
} | 1 |
public void draw(Graphics2D g, TreeNode node) {
Color c = g.getColor();
if (isSelected(node))
g.setColor(c.darker());
super.draw(g, node);
g.setColor(c);
} | 1 |
public static void main(String[] args) throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
ServerSocket server = new ServerSocket(8080);
InetSocketAddress isa = new InetSocketAddress("localhost", 8080);
SocketChannel sc1 = SocketChannel.open(isa);
SocketChannel sc2 = SocketChannel.open(isa);
Future<?> f = exec.submit(new NIOBlocked(sc1));
exec.execute(new NIOBlocked(sc2));
exec.shutdown();
TimeUnit.SECONDS.sleep(1);
// Produce an interrupt via cancel:
f.cancel(true);
TimeUnit.SECONDS.sleep(1);
// Release the block by closing the channel:
sc2.close();
} | 1 |
private static int doStatements(
DatabaseConnection connection,
String label,
Collection<String> statements,
boolean ignoreErrors,
boolean returnsNegative,
boolean expectingZero)
throws SQLException
{
int stmtC = 0;
for (String statement : statements)
{
int rowC = 0;
CompiledStatement compiledStmt = null;
try
{
compiledStmt = connection
.compileStatement(statement,
StatementType.EXECUTE,
noFieldTypes);
rowC = compiledStmt.runExecute();
logger.info("executed {} table statement changed {} rows: {}",
label,
rowC,
statement);
}
catch (SQLException e)
{
if (ignoreErrors)
{
logger.info("ignoring {} error '{}' for statement: {}",
label,
e,
statement);
}
else
{
throw SqlExceptionUtil.create("SQL statement failed: "
+ statement, e);
}
}
finally
{
if (compiledStmt != null)
{
compiledStmt.close();
}
}
// sanity check
if (rowC < 0)
{
if (!returnsNegative)
{
throw new SQLException("SQL statement "
+ statement
+ " updated "
+ rowC
+ " rows, we were expecting >= 0");
}
}
else if (rowC > 0 && expectingZero)
{
throw new SQLException("SQL statement updated "
+ rowC
+ " rows, we were expecting == 0: "
+ statement);
}
stmtC++;
}
return stmtC;
} | 8 |
protected static String getLine(int length, char c) {
StringBuilder b = new StringBuilder();
for (; length > 0; length--) {
b.append(c);
}
return b.toString();
} | 1 |
public void receive(Object obj) {
Event event = (Event) obj;
switch(event.type) {
case "assign player":
Helper.log("ConnectionToGameServer: RECEIVED ASSIGN PLAYER EVENT");
gameScreen.engine.player = (Player) event.data;
if (gameScreen.gui.user.username.equals(ThinkTankGUI.GUEST_ACCOUNT)) {
gameScreen.gui.user.username = gameScreen.engine.player.username;
} else {
gameScreen.engine.player.username = gameScreen.gui.user.username;
}
this.sendEvent(new Event("set username", gameScreen.gui.user.username));
Helper.log("Assigned Player: " + gameScreen.engine.player);
break;
case "game update":
this.gameState = (GameState) event.data;
break;
case "start game":
Helper.log("ConnectionToGameServer: RECEIVED START GAME EVENT");
gameScreen.gui.goTo(ThinkTankGUI.GameScreenPage);
gameScreen.engine.start();
break;
case "chat":
System.out.println("ConnectionToGameServer: RECEIVED CHAT EVENT");
gameScreen.chatPanel.ta.append("\n"+((ChatObject)event.data).message);
break;
case "new player":
gameScreen.chatPanel.addPlayer((String)event.data);
break;
case "player list":
Vector<Player> players = (Vector<Player>)event.data;
for (Player player:players) {
if (!gameScreen.gui.user.username.equals(player.username))
gameScreen.chatPanel.addPlayer(player.username);
}
break;
default:
Helper.log("ConnectionToGameServer: DIDN'T UNDERSTAND EVENT");
ThinkTankGUI.logger.log(Level.INFO, "Parse error. did not understand message: " + event);
}
} | 9 |
public static String displayInput(String question, String title) {
while (true) {
String s = JOptionPane.showInputDialog(null, question, title,
JOptionPane.PLAIN_MESSAGE);
if (s == null) {
System.exit(0);
}
if (s.length() > 0) {
return s;
}
}
} | 3 |
public void fine(String message) {
log(Level.FINE, message);
} | 0 |
public static Game GetGame() throws Exception
{
if(game == null)
{
throw new Exception();
}
return game;
} | 1 |
public void setTrainingId(int trainingId) {
this.trainingId = trainingId;
} | 0 |
@Test
public void testReplaceFood() {
System.out.println("replaceFood");
World instance = new World();
instance.generateRandomContestWorld();
instance.replaceFood();
int expResult = 0;
int result = instance.getFoodNum();
assertEquals(expResult, result);
} | 0 |
public Object opt(String key) {
return key == null ? null : this.map.get(key);
} | 1 |
@Override
public Connection getConnection() {
if (connection == null) {
try {
InitialContext context = new InitialContext();
DataSource ds = ((DataSource) context.lookup("30Resource"));
connection = ds.getConnection();
} catch (NamingException | SQLException ex) {
Logger.getLogger(MySqlFactory.class.getName()).log(Level.SEVERE, null, ex);
}
}
return connection;
} | 2 |
public static int runToAddressR(int limit, Gameboy gbL, Gameboy gbR, int... addresses) {
if (!gbR.onFrameBoundaries) {
int add = dualStepUntilR(gbL, gbR, 0, 0, addresses);
if (add != 0)
return add;
}
int steps = 0;
while (steps < limit) {
int add = dualStepUntilR(gbL, gbR, 0, 0, addresses);
if (add != 0)
return add;
steps++;
}
return 0;
} | 4 |
public void mouseExited(MouseEvent e) {
if (!b.isEnabled()) return;
if (b instanceof javax.swing.JToggleButton && b.isSelected())
return;
b.setBorder(inactive);
b.setBorderPainted(false);
} | 3 |
public String result(boolean gui){
if((house.isBusted()||
player.getHandValue()>house.getHandValue())
&&!player.isBusted())
return player.win();
else if(player.isBusted()||
!house.isBusted()&&
player.getHandValue()<house.getHandValue())
return player.lose();
else
return player.push();
} | 6 |
@Override
public int getRemainDays() throws ServiceException {
try {
UriBuilder builder = UriBuilder.fromPath(
baseResourceUri + REMAIN_DAYS_PATH);
URI uri = builder.build();
GetMethod getMethod = requestGetMethodFactory
.newPlainTextRequestMethod(uri);
String daysStr = null;
try {
httpClient.executeMethod(getMethod);
int status = getMethod.getStatusCode();
if (status != 200) {
throw new UnexpectedStatusException(status);
}
daysStr = getMethod.getResponseBodyAsString();
return Integer.parseInt(daysStr);
} catch (NumberFormatException ex) {
throw new ServiceException(String.format(
"NumberFormatException occurred " +
"during parsing [ %s ] with uri [ %s ]",
daysStr, getMethod.getURI().toString()), ex);
} finally {
getMethod.releaseConnection();
}
} catch (Exception ex) {
throw new ServiceException(ex);
}
} | 3 |
void processBondCrossingUnderPBC() {
if (!(model instanceof MolecularModel))
return;
MoleculeCollection molecules = ((MolecularModel) model).molecules;
if (molecules.isEmpty())
return;
double x0 = getX();
double y0 = getY();
double dx = getWidth();
double dy = getHeight();
double x1 = x0 + dx;
double y1 = y0 + dy;
Molecule mol;
Point2D p;
double delta_x, delta_y;
synchronized (molecules) {
for (Iterator it = molecules.iterator(); it.hasNext();) {
mol = (Molecule) it.next();
delta_x = 0.0;
delta_y = 0.0;
p = mol.getCenterOfMass2D();
if (p.getX() < x0)
delta_x = dx;
if (p.getX() > x1)
delta_x = -dx;
if (p.getY() < y0)
delta_y = dy;
if (p.getY() > y1)
delta_y = -dy;
if (Math.abs(delta_x) > 0.001 || Math.abs(delta_y) > 0.001)
mol.translateBy(delta_x, delta_y);
}
}
} | 9 |
public void csvImport(String filename) {
try {
log.info("Importing from file \"{}\"", filename);
int inserted = 0, updated = 0;
db.beginTransaction();
try (CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(filename), "UTF-8"))) {
String[] line = reader.readNext();
log.debug("Parsing header: {}", Arrays.toString(line));
parseHeader(line);
while ((line = reader.readNext()) != null) {
Map<String, String> values = map(line);
Person p = db.getPerson(values.get("timestamp"));
if (p == null) {
db.insertPerson(values);
inserted++;
} else {
p.setPayment(values.get("payment"));
updated++;
}
}
if (confirm(inserted, updated)) {
db.commitTransaction();
log.info("Inserted {} and updated {} record(s) in the database.", inserted, updated);
} else {
db.rollbackTransaction();
log.info("Import aborted by user. No data has been changed.");
}
} catch (IOException ioe) {
log.error("Failed to read CSV file", ioe);
db.rollbackTransaction();
return;
} catch (NoSuchElementException nsee) {
log.error("Failed to parse CSV file header;", nsee);
db.rollbackTransaction();
}
} catch (SQLException ex) {
log.error("Database error during import: {}", ex);
try {
db.rollbackTransaction();
} catch (SQLException e) {
log.error("Failed to rollback transaction after failed import: ", e);
}
}
} | 7 |
public StrictBounds<OrderedElement<T>> findNewBound(Iterable<T> stream, long kOrder, Bounds<OrderedElement<T>> oldBounds) {
ArrayList<OrderedElement<T>> current = new ArrayList<>(levelSize);
List<ArrayList<OrderedElement<T>>> levels = new ArrayList<>(levelSize);
long elementOrder = 0;
long elementSmallerThanBound = 0;
OrderedElement<T> mostUpperElement = null;
OrderedElement<T> mostLowerElement = null;
for (T unorderedElement : stream) {
OrderedElement<T> element = new OrderedElement<>(unorderedElement, elementOrder++);
elementSmallerThanBound = oldBounds.updateNumberOfElementsLower(element, comparator, elementSmallerThanBound);
if (!oldBounds.isInBounds(element, comparator)) {
continue;
}
mostUpperElement = max(mostUpperElement, element);
mostLowerElement = min(mostLowerElement, element);
if (isLevelFull(current)) {
current = mergeUp(current, levels);
Preconditions.checkArgument(current.isEmpty());
}
current.add(element);
}
finalizeTree(current, levels);
Preconditions.checkArgument(kOrder < elementOrder, "K-order is bigger than stream size!");
Preconditions.checkArgument(mostUpperElement != null && mostLowerElement != null);
Preconditions.checkArgument(kOrder >= elementSmallerThanBound,
"DEBUG: element before: " + elementSmallerThanBound + " order: " + kOrder);
kOrder -= elementSmallerThanBound;
if (levels.size() == 1) {
OrderedElement<T> element = levels.get(0).get((int) kOrder);
return new StrictBounds<>(element, element);
}
List<OrderedElement<T>> upperLevel = levels.get(levels.size() - 1);
assert comparator.isOrdered(upperLevel);
int lowerIndex = (int) ((kOrder ) / powerOfTwo(levels.size() - 1));
int upperIndex = (int) ((kOrder ) / powerOfTwo(levels.size() - 1)) + levels.size() - 1;
OrderedElement<T> lowerElement = lowerIndex >= 0 ?
upperLevel.get(lowerIndex) : mostLowerElement;
OrderedElement<T> upperElement = upperIndex < levelSize && !upperLevel.get(upperIndex).isInfinity() ?
upperLevel.get(upperIndex) : mostUpperElement;
System.gc();
return new StrictBounds<>(
lowerElement,
upperElement);
} | 8 |
public AnnotationVisitor visitParameterAnnotation(final int parameter,
final String desc, final boolean visible) {
if (!ClassReader.ANNOTATIONS) {
return null;
}
ByteVector bv = new ByteVector();
if ("Ljava/lang/Synthetic;".equals(desc)) {
// workaround for a bug in javac with synthetic parameters
// see ClassReader.readParameterAnnotations
synthetics = Math.max(synthetics, parameter + 1);
return new AnnotationWriter(cw, false, bv, null, 0);
}
// write type, and reserve space for values count
bv.putShort(cw.newUTF8(desc)).putShort(0);
AnnotationWriter aw = new AnnotationWriter(cw, true, bv, bv, 2);
if (visible) {
if (panns == null) {
panns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length];
}
aw.next = panns[parameter];
panns[parameter] = aw;
} else {
if (ipanns == null) {
ipanns = new AnnotationWriter[Type.getArgumentTypes(descriptor).length];
}
aw.next = ipanns[parameter];
ipanns[parameter] = aw;
}
return aw;
} | 5 |
private boolean instrucaoRetorno() {
/*
<inst_retorno> ::= “retorno” <argumento_retorno> “;”
<argumento_retorno> ::= <valor> | <argumento> | “vazio”
//<valor> ::= <numero> | <booleano> | <char> | <cadeia>
<numero> ::= <inteiro> | <real>
<argumento> ::= <id> <compl_tipo_parametro>
<compl_tipo_parametro> ::= <acesso_campo_registro> | <acesso_matriz>
| <chamada_funcao> | λ
<acesso_campo_registro> ::= ”.” <id>
<acesso_matriz> ::= “[“ <indice> “]” <acesso_matriz> | λ
<indice> ::= <inteiro> | <id>
*/
boolean erro = false;
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[0].equals("Palavra Reservada")) {
if (tipoDoToken[1].equals(" retorno")) {
System.out.println("Entrei em retorno");
if (!acabouListaTokens()) {
nextToken();
erro = false;
if (tipoDoToken[0].equals("Palavra Reservada")) {
if (tipoDoToken[1].equals(" vazio")) {
erro = false;
if (!acabouListaTokens()) {
nextToken();
if (tipoDoToken[1].equals(" ;")) {
System.out.println("TERMINEI RETORNO RETORNANDO VAZIO");
listaDeBlocos.add("retorno tipo vazio: sem ");
erro = false;
} else {
erro = true;
//erro fim de retorno tipo vazio faltando o ponto e virgula ;
errosSintaticos.erroSemPontoVirgulaRetorno(tipoDoToken[3], tipoDoToken[1]);
}
} else {
erro = true;
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "retorno");
zerarTipoToken();
}
} else {
erro = true;
//erro tipo de retorno1 quando retorna vazio
}
} else if (tipoDoToken[0].equals("Identificador")) {
//retornar valor e registro aqui
} else {
erro = true;
//erro
}
} else {
erro = true;
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "retorno");
zerarTipoToken();
}
} else {
erro = true;
//erro a ser tratado
}
} else {
erro = true;
//erro a ser tratado
}
} else {
erro = true;
errosSintaticos.erroFimDeArquivo(tipoDoToken[3], tipoDoToken[1], "retorno");
zerarTipoToken();
}
return true;
// return erro;
} | 9 |
int insertKeyRehash(double val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
} | 9 |
protected void drawShape(DrawableItem di, Graphics2D g) {
Stroke oldstrk = null;
if (di.getIsSelected()) {
oldstrk = g.getStroke();
g.setStroke(new BasicStroke(2));
if (di instanceof PathItem) {
g.setStroke(new BasicStroke(((PathItem) di).getThickness()));
}
}
g.setColor(di.getOutline());
g.draw(di.getShape());
if (di instanceof Panel && di.getIsSelected()) {
g.draw(((Panel) di).getFirstCorner());
g.draw(((Panel) di).getSecondCorner());
g.draw(((Panel) di).getThirdCorner());
g.draw(((Panel) di).getFourthCorner());
}
if (oldstrk != null) {
g.setStroke(oldstrk);
}
} | 5 |
public static void main(String[] args)
{
EdgeWeightedDigraph G = new EdgeWeightedDigraph(new In(args[0]));
int s = Integer.parseInt(args[1]);
AcyclicLP sp = new AcyclicLP(G, s);
for (int t = 0; t < G.V(); t++)
{
System.out.print(s + " to " + t + " ("
+ String.format("%.2f", sp.distTo(t)) + ") : ");
if (sp.hasPathTo(t))
for (WeightedDirectedEdge e : sp.pathTo(t))
System.out.print(e + " ");
System.out.println();
}
} | 3 |
public GenericDAO<Assignment> getAssignmentsDAO()
{
if (_assignmentsDAO == null)
{
_assignmentsDAO = new GenericDAO<Assignment>(Assignment.class);
}
return _assignmentsDAO;
} | 1 |
public static void addToTeam(TeamType type, Player player) {
if (isInGameTeam(player)) {
ChatUtils.send(player, "Du bist schon in einem Team!");
return;
}
switch (type) {
case LOBBY:
lobby.add(player.getName());
break;
case INNOCENT:
lobby.remove(player.getName());
innocents.add(player.getName());
ChatUtils.send(player, "Du bist " + ChatColor.GREEN + "Innocent");
break;
case TRAITOR:
lobby.remove(player.getName());
if (traitors.size() == 2) {
ChatUtils.send(player, "Du bist " + ChatColor.GREEN
+ "Innocent");
innocents.add(player.getName());
break;
}
traitors.add(player.getName());
ChatUtils.send(player, "Du bist " + ChatColor.RED + "TRAITOR");
break;
case SPECTATOR:
spectators.add(player.getName());
player.getInventory().addItem(new ItemStack(Material.COMPASS));
ChatUtils.send(player, "Du bist jetzt in der Spectate Lobby");
break;
}
} | 6 |
private Rama_Hoja buscarSacarEntreDesconectado(String pID){
Rama_Hoja resp = null;
for(Nodo<Rama_Hoja> iteradorTree = _compuertasDesconectadas.getHead(); iteradorTree != null; iteradorTree = iteradorTree.getSiguiente()){
if(iteradorTree.getDato().getIdentificador() == pID)
resp = iteradorTree.getDato();
break;
}
return resp;
} | 2 |
public SecuredMessageTriggerBean executeProblem(SecuredMessageTriggerBean message) throws GranException {
String text = message.getDescription();
SecuredTaskBean task = message.getTask();
EggBasket<SecuredUDFValueBean, SecuredTaskBean> refs = AdapterManager.getInstance().getSecuredIndexAdapterManager().getReferencedTasksForTask(task);
SecuredUDFBean relatedUdf = AdapterManager.getInstance().getSecuredFindAdapterManager().findUDFById(task.getSecure(), INCIDENT_RELATED_PROBLEM_UDFID);
if (refs!=null )
{
for (Entry<SecuredUDFValueBean, List<SecuredTaskBean>> entry : refs.entrySet()){
if (entry.getKey().getUdfId().equals(relatedUdf.getId())){
List<SecuredTaskBean> incidentsInvolved = entry.getValue();
if (incidentsInvolved != null) {
for (SecuredTaskBean p : incidentsInvolved) {
executeOperation(INCIDENT_DECLINE_OPERATION, p, text, message.getUdfValues());
}
}
}
}
}
return message;
} | 5 |
public String getUrl(){
return url;
} | 0 |
private static void gerarProfilesSeriais(List<Profile> profilesSeriais, List<File> listaTxt, List<File> listaBin, List<String> listaZip) {
long inicio;
long fim10;
long fim50;
long fim100;
Profile p;
for (int i = 0; i < ITERACOES; i++) {
for (File txt : listaTxt) {
inicio = Calendar.getInstance().getTimeInMillis();
p = new Profile(i+1, txt.getName(), "TXT", String.valueOf(txt.length()/1024.0), "Serial");
for (int j = 0; j < QT_100; j++) {
String path = ZIP_FILE_PATH+File.separator+"txt-"+p.getNome()+"-"+i+"-"+j+".zip";
listaZip.add(path);
FileUtils.compressFile(path, txt.getName(), txt.getAbsolutePath());
if(j+1 == QT_10){
fim10 = Calendar.getInstance().getTimeInMillis();
p.setTempo10((fim10 - inicio) / 1000.0);
}
if(j+1 == QT_50){
fim50 = Calendar.getInstance().getTimeInMillis();
p.setTempo50((fim50 - inicio) / 1000.0);
}
}
fim100 = Calendar.getInstance().getTimeInMillis();
p.setTempo100((fim100 - inicio) / 1000.0);
profilesSeriais.add(p);
p.toString();
}
FileUtils.deleteFiles(listaZip);
listaZip = new ArrayList<String>();
for (File bin : listaBin) {
p = new Profile(i+1, bin.getName(), "BIN", String.valueOf(bin.length()/1024.0), "Serial");
inicio = Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < QT_100; j++) {
String path = ZIP_FILE_PATH+File.separator+"bin-"+p.getNome()+"-"+i+"-"+j+".zip";
listaZip.add(path);
FileUtils.compressFile(path, bin.getName(), bin.getAbsolutePath());
if(j+1 == QT_10){
fim10 = Calendar.getInstance().getTimeInMillis();
p.setTempo10((fim10 - inicio) / 1000.0);
}
if(j+1 == QT_50){
fim50 = Calendar.getInstance().getTimeInMillis();
p.setTempo50((fim50 - inicio) / 1000.0);
}
}
fim100 = Calendar.getInstance().getTimeInMillis();
p.setTempo100((fim100 - inicio) / 1000.0);
profilesSeriais.add(p);
p.toString();
}
FileUtils.deleteFiles(listaZip);
listaZip = new ArrayList<String>();
}
} | 9 |
private int ssMedian5 (final int Td, final int PA, int v1, int v2, int v3, int v4, int v5) {
final int[] SA = this.SA;
final byte[] T = this.T;
int T_v1 = T[Td + SA[PA + SA[v1]]] & 0xff;
int T_v2 = T[Td + SA[PA + SA[v2]]] & 0xff;
int T_v3 = T[Td + SA[PA + SA[v3]]] & 0xff;
int T_v4 = T[Td + SA[PA + SA[v4]]] & 0xff;
int T_v5 = T[Td + SA[PA + SA[v5]]] & 0xff;
int temp;
int T_vtemp;
if (T_v2 > T_v3) {
temp = v2;
v2 = v3;
v3 = temp;
T_vtemp = T_v2;
T_v2 = T_v3;
T_v3 = T_vtemp;
}
if (T_v4 > T_v5) {
temp = v4;
v4 = v5;
v5 = temp;
T_vtemp = T_v4;
T_v4 = T_v5;
T_v5 = T_vtemp;
}
if (T_v2 > T_v4) {
temp = v2;
v2 = v4;
v4 = temp;
T_vtemp = T_v2;
T_v2 = T_v4;
T_v4 = T_vtemp;
temp = v3;
v3 = v5;
v5 = temp;
T_vtemp = T_v3;
T_v3 = T_v5;
T_v5 = T_vtemp;
}
if (T_v1 > T_v3) {
temp = v1;
v1 = v3;
v3 = temp;
T_vtemp = T_v1;
T_v1 = T_v3;
T_v3 = T_vtemp;
}
if (T_v1 > T_v4) {
temp = v1;
v1 = v4;
v4 = temp;
T_vtemp = T_v1;
T_v1 = T_v4;
T_v4 = T_vtemp;
temp = v3;
v3 = v5;
v5 = temp;
T_vtemp = T_v3;
T_v3 = T_v5;
T_v5 = T_vtemp;
}
if (T_v3 > T_v4) {
return v4;
}
return v3;
} | 6 |
public int getMove() {
int currentMove = BASE_MOVE;
if (hasStatus(UnitStatus.Type.HASTED)) {
currentMove += Ability.HASTE.getProperty(Ability.Property.MOVE_BONUS);
}
if (hasStatus(UnitStatus.Type.SLOWED)) {
currentMove -= Ability.SLOW.getProperty(Ability.Property.MOVE_PENALTY);
}
return currentMove;
} | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.