method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
882eb0e6-38fc-4a6e-b131-9bfa6d5badc6 | 9 | private Particle parseGroup() throws PrologSyntaxException {
Particle g = new Particle(Particle.GROUP);
g.particles = new Vector();
new AtomParser(db, as, pp, g).parseParticles();
int n = g.particles.size();
int flags = 0;
for (int i = 0; i < n; i++) {
switch (((Particle)g.particles.elementAt(i)).type) {
case Particle.GROUP:
flags |= Entity.GROUP_CONTAINS_GROUP;
break;
case Particle.CONNECT_OR:
flags |= Entity.GROUP_CONTAINS_OR;
break;
case Particle.CONNECT_SEQ:
flags |= Entity.GROUP_CONTAINS_SEQ;
break;
case Particle.PCDATA:
flags |= Entity.GROUP_CONTAINS_PCDATA;
break;
case Particle.ELEMENT_NAME:
flags |= Entity.GROUP_CONTAINS_ELEMENT_NAME;
break;
case Particle.NMTOKEN:
flags |= Entity.GROUP_CONTAINS_NMTOKEN;
break;
}
}
for (int i = 0; i < n; i++) {
Particle p = (Particle)g.particles.elementAt(i);
if (p.type == Particle.REFERENCE)
p.entity.groupFlags |= flags;
}
return g;
} |
8756d889-7e78-498f-96d8-1488b0b217f8 | 9 | public Spinner(int x, int y, int size, int min, int max, int val, int step, GuiRotation rot) {
this.x = x;
this.y = y;
if (rot == GuiRotation.HORIZONTAL) {
width = size;
height = HEIGHT;
} else {
width = HEIGHT;
height = size;
}
value = val;
this.min = min;
this.max = max;
this.step = step;
this.rot = rot;
titles = new String[max - min];
minus = new ArrowButton(x, y + ((rot == GuiRotation.HORIZONTAL) ? 0 : height - ArrowButton.HEIGHT), (rot == GuiRotation.HORIZONTAL) ? ArrowButton.MINUS_HOR
: ArrowButton.MINUS_VER);
minus.setClickEvent(new IGuiEvent() {
@Override
public void trigger() {
value = (value >= Spinner.this.min + Spinner.this.step) ? value - Spinner.this.step : Spinner.this.min;
if (clickEvent != null) clickEvent.trigger();
}
});
plus = new ArrowButton(x + ((rot == GuiRotation.HORIZONTAL) ? width - ArrowButton.WIDTH : 0), y, (rot == GuiRotation.HORIZONTAL) ? ArrowButton.PLUS_HOR : ArrowButton.PLUS_VER);
plus.setClickEvent(new IGuiEvent() {
@Override
public void trigger() {
value = (value < Spinner.this.max - Spinner.this.step) ? value + Spinner.this.step : Spinner.this.max - 1;
if (clickEvent != null) clickEvent.trigger();
}
});
} |
83af3758-b11a-4d07-a73f-0580bb44264a | 1 | protected void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que deseja cancelar?")== 0){
dispose();
}
}//GEN-LAST:event_btnCancelarActionPerformed |
04a84a5c-1b83-4d8d-994d-f7d01219df5c | 8 | public static int firstMissingPositive(int[] A) {
int len = A.length;
if(len == 0) {
return 1;
}
for(int i=0;i<len;i++) {
int current = A[i];
if(current < 1 || current > len) {
A[i] = 0;
} else if(current != (i+1)){
int tmp = A[current-1];
if(tmp != current) {
A[current-1] = current;
A[i] = tmp;
i--;
}
}
}
for(int i=0;i<len;i++) {
int current = A[i];
if(current != (i+1)) {
return i+1;
}
}
return len+1;
} |
52dbf033-bf1f-4298-9f54-ecdea6afdc39 | 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(Tensiometer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Tensiometer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Tensiometer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Tensiometer.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 Tensiometer().setVisible(true);
}
});
} |
dcc6d89d-ca86-42a8-8caf-b23ee0cc924a | 4 | private static int sumOfDivs(int n){
int divSum = 1;
for(int i=2;i<=Math.sqrt(n);i++){
if (i==Math.sqrt(n) && n%i==0) divSum+=i;
else if (n%i==0) divSum+=i+n/i;
}
return divSum;
} |
c7a0d06c-4fde-442c-8afb-c4bbeda0e697 | 7 | private static Instances clusterInstances(Instances data) {
XMeans xmeans = new XMeans();
Remove filter = new Remove();
Instances dataClusterer = null;
if (data == null) {
throw new NullPointerException("Data is null at clusteredInstances method");
}
//Get the attributes from the data for creating the sampled_data object
ArrayList<Attribute> attrList = new ArrayList<Attribute>();
Enumeration attributes = data.enumerateAttributes();
while (attributes.hasMoreElements()) {
attrList.add((Attribute) attributes.nextElement());
}
Instances sampled_data = new Instances(data.relationName(), attrList, 0);
data.setClassIndex(data.numAttributes() - 1);
sampled_data.setClassIndex(data.numAttributes() - 1);
filter.setAttributeIndices("" + (data.classIndex() + 1));
//int numberOfEnsembles = model.ensembleSizeOption.getValue();
data.remove(0);//In Wavelet Stream of MOA always the first element comes without class
try {
filter.setInputFormat(data);
dataClusterer = Filter.useFilter(data, filter);
String[] options = new String[4];
options[0] = "-L"; // max. iterations
options[1] = Integer.toString(noOfClassesInPool - 1);
if (noOfClassesInPool > 2) {
options[1] = Integer.toString(noOfClassesInPool - 1);
xmeans.setMinNumClusters(noOfClassesInPool - 1);
} else {
options[1] = Integer.toString(noOfClassesInPool);
xmeans.setMinNumClusters(noOfClassesInPool);
}
xmeans.setMaxNumClusters(data.numClasses() + 1);
System.out.println("No of classes in the pool: " + noOfClassesInPool);
xmeans.setUseKDTree(true);
//xmeans.setOptions(options);
xmeans.buildClusterer(dataClusterer);
System.out.println("Xmeans\n:" + xmeans);
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println("Assignments\n: " + assignments);
ClusterEvaluation eval = new ClusterEvaluation();
eval.setClusterer(xmeans);
try {
eval.evaluateClusterer(data);
int classesToClustersMap[] = eval.getClassesToClusters();
//check the classes to cluster map
int clusterNo = 0;
for (int i = 0; i < data.size(); i++) {
clusterNo = xmeans.clusterInstance(dataClusterer.get(i));
//Check if the class value of instance and class value of cluster matches
if ((int) data.get(i).classValue() == classesToClustersMap[clusterNo]) {
sampled_data.add(data.get(i));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return ((Instances) sampled_data);
} |
8bb41d26-82e7-43df-8aba-79fd548c9135 | 9 | private static BytesRef pack(byte[]... point) {
if (point == null) {
throw new IllegalArgumentException("point must not be null");
}
if (point.length == 0) {
throw new IllegalArgumentException("point must not be 0 dimensions");
}
if (point.length == 1) {
return new BytesRef(point[0]);
}
int bytesPerDim = -1;
for(byte[] dim : point) {
if (dim == null) {
throw new IllegalArgumentException("point must not have null values");
}
if (bytesPerDim == -1) {
if (dim.length == 0) {
throw new IllegalArgumentException("point must not have 0-length values");
}
bytesPerDim = dim.length;
} else if (dim.length != bytesPerDim) {
throw new IllegalArgumentException("all dimensions must have same bytes length; got " + bytesPerDim + " and " + dim.length);
}
}
byte[] packed = new byte[bytesPerDim*point.length];
for(int i=0;i<point.length;i++) {
System.arraycopy(point[i], 0, packed, i*bytesPerDim, bytesPerDim);
}
return new BytesRef(packed);
} |
358f1616-efe7-4a8e-870c-97eb46478aff | 8 | @Test
public void reTest2() {
userInput.add("hi");
userInput.add("my name is meng meng");
userInput.add("can you tell me about hamburger");
userInput.add("ingredients");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("errorhandling");
userInput.add("handle the error");
userInput.add("handle the error somehow");
userInput.add("handle this error");
userInput.add("no");
this.runMainActivityWithTestInput(userInput);
assertTrue((nlgResults.get(4).contains("again") || nlgResults.get(4).contains("repeat"))
&& (nlgResults.get(6).contains("again") || nlgResults.get(6).contains("repeat"))
&& nlgResults.get(7).contains("rephrase")
&& nlgResults.get(9).contains("rephrase")
&& nlgResults.get(10).contains("hamburger")
&& (nlgResults.get(11).contains("again") || nlgResults.get(11).contains("repeat")));
} |
107f66bb-3175-47d0-b821-c0df123cf884 | 3 | @Override
public List<Convenio> listByNome(String nome) {
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
List<Convenio> convenio = new ArrayList<>();
try{
con = ConnectionFactory.getConnection();
pstm = con.prepareStatement(LISTBYNOME);
pstm.setString(1, "%" + nome + "%");
rs = pstm.executeQuery();
while(rs.next()){
//(nome, login, senha, telefone, celular, endereco, cidade, estado)
Convenio f = new Convenio();
f.setNome(rs.getString("nome"));
f.setCodigo(rs.getInt("codigo"));
convenio.add(f);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao pesquisar convenio: " + e.getMessage());
}finally{
try{
ConnectionFactory.closeConnection(con, pstm, rs);
}catch(Exception e){
JOptionPane.showMessageDialog(null,"Erro ao fechar conexão de pesquisar convenio: " + e.getMessage());
}
}
return convenio;
} |
a37c1f7f-b5d8-4c19-8fab-343489b1c523 | 8 | public void displaychapter(int framenum, int labelnum) throws IOException
{
chapdispframenum = framenum;
labelnumber = labelnum;
BufferedImage testimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
File file = new File(filename);
InputStream is = new FileInputStream(file);
int seeknumRead=0;
long frameoffset = chapdispframenum*sizeofframe;
is.skip(frameoffset);
int numRead = 0;
int k = 0;
byte[] bytes = new byte[(int)sizeofframe];
if((numRead=is.read(bytes, 0, sizeofframe)) >=0) {
// VideoFrame[framenum] = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
byte a = 0;
byte r = bytes[k];
byte g = bytes[k+height*width];
byte b = bytes[k+height*width*2];
int pix = 0xff000000 | ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
//int pix = ((a << 24) + (r << 16) + (g << 8) + b);
testimg.setRGB(x,y,pix);
k++;
}//end of for x
}//end of for y
// ImageIcon imgicon = new ImageIcon(testimg);
Image simg = testimg.getScaledInstance( 100, 100, java.awt.Image.SCALE_SMOOTH ) ;
ImageIcon imgiconscaled = new ImageIcon(simg);
int chapnum = framenum;//(framenum/Vplayer.chapterspan);
int untilchapnum = framenum+(Vplayer.chapterspan-1);
switch(labelnumber)
{
case 1:Vplayer.chapLabel1.setIcon(imgiconscaled);
Vplayer.jFormattedTextField1.setText(""+chapnum+"-"+untilchapnum);
Vplayer.chapLabel1_frameno = framenum; break;
case 2:Vplayer.chapLabel2.setIcon(imgiconscaled);
Vplayer.chapLabel2_frameno = framenum;
Vplayer.jFormattedTextField2.setText(""+chapnum+"-"+untilchapnum);
break;
case 3:Vplayer.chapLabel3.setIcon(imgiconscaled);
Vplayer.chapLabel3_frameno = framenum;
Vplayer.jFormattedTextField3.setText(""+chapnum+"-"+untilchapnum);
break;
case 4:Vplayer.chapLabel4.setIcon(imgiconscaled);
Vplayer.chapLabel4_frameno = framenum;
Vplayer.jFormattedTextField4.setText(""+chapnum+"-"+untilchapnum);
break;
case 5:Vplayer.chapLabel5.setIcon(imgiconscaled);
Vplayer.chapLabel5_frameno = framenum;
Vplayer.jFormattedTextField5.setText(""+chapnum+"-"+untilchapnum);
break;
//case 6:Vplayer.videolabel.setIcon(imgicon); break; //this one is for main frame
default: break;
}
}//end of if
else
{
System.out.println("Something went wrong. number of bytes read = numRead= "+numRead);
}
// System.out.println("END OF DISPLAY CHAPTER THREAD: chapter displayed ="+chapdispframenum+"on label:"+labelnumber);
} |
aa4059f1-3817-4197-8e6e-d368d13fda91 | 7 | public static float idealNestPop(
Species species, Venue site, World world, boolean cached
) {
final Nest nest = (cached && site instanceof Nest) ?
(Nest) site : null ;
if (nest != null && nest.idealPopEstimate != -1) {
return nest.idealPopEstimate ;
}
// TODO: Repeating the sample has no particular benefit in the case of
// predator nests, and is still unreliable in the case of browser nests.
// Consider doing a brute-force flood-fill check instead?
float estimate = 0 ; for (int n = NEW_SITE_SAMPLE ; n-- > 0 ;) {
estimate += idealPopulation(site, species, world) / NEW_SITE_SAMPLE ;
}
if (nest != null && nest.idealPopEstimate == -1) {
nest.idealPopEstimate = estimate ;
}
return estimate ;
} |
87ddde72-1b97-4201-be96-e6f01c249885 | 8 | public static void main(String[] args) {
long time = System.nanoTime();
for (int n = 0; n < TEST_SIZE; n++) {
vt = System.currentTimeMillis();
}
System.out.println("volatile write:");
System.out.println((System.nanoTime() - time));
time = System.nanoTime();
for (int n = 0; n < TEST_SIZE; n++) {
i = System.currentTimeMillis();
}
System.out.println("normal write:");
System.out.println((System.nanoTime() - time));
for (int n = 0; n < TEST_SIZE; n++) {
synchronized (PerformanceTest.class) {
}
}
System.out.println("sync .class block time:");
System.out.println(-time + (time = System.nanoTime()));
for (int n = 0; n < TEST_SIZE; n++) {
vt++;
}
System.out.println("voltaile ++ time:");
System.out.println(-time + (time = System.nanoTime()));
for (int n = 0; n < TEST_SIZE; n++) {
vt = i;
}
System.out.println(-time + (time = System.nanoTime()));
for (int n = 0; n < TEST_SIZE; n++) {
i = vt;
}
System.out.println(-time + (time = System.nanoTime()));
for (int n = 0; n < TEST_SIZE; n++) {
i++;
}
System.out.println(-time + (time = System.nanoTime()));
for (int n = 0; n < TEST_SIZE; n++) {
i = n;
}
System.out.println(-time + (time = System.nanoTime()));
} |
fda719cc-3a09-48dd-9e6e-012f7978edd5 | 9 | public ServerGUI() {
field = new JTextField("6060",10);
field.setHorizontalAlignment(JTextField.RIGHT);
field.setBorder(BorderFactory.createTitledBorder("Inserisci la porta"));
field.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (! (c>='0' && c <='9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)) {
getToolkit().beep();
e.consume();
}
}
});
portDatagram = new JTextField("-1",10);
portDatagram.setHorizontalAlignment(JTextField.RIGHT);
portDatagram.setBorder(BorderFactory.createTitledBorder("Inserisci la porta datagram"));
portDatagram.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (! (c>='0' && c <='9') || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE)) {
getToolkit().beep();
e.consume();
}
}
});
start = new JButton("Avvio server");
start.setVerticalTextPosition(AbstractButton.CENTER);
start.setHorizontalTextPosition(AbstractButton.LEADING);
stop = new JButton("Stop Server");
stop.setVerticalTextPosition(AbstractButton.BOTTOM);
stop.setHorizontalTextPosition(AbstractButton.CENTER);
label = new JLabel("Status: da avviare");
enableHttps = new JCheckBox("Enable Https",true);
enableAuthentication = new JCheckBox("Enable Authentication",true);
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int port = Integer.parseInt(field.getText());
int portDatagramInt = Integer.parseInt(portDatagram.getText());
boolean enableHttpsB = enableHttps.isSelected();
boolean enableAuthenticationB = enableAuthentication.isSelected();
server = new Server(port,enableAuthenticationB,enableHttpsB,portDatagramInt);
server.start();
label.setText("Status: avviato");
} catch (Exception e1) {
label.setText(e1.getMessage());
e1.printStackTrace();
}
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
server.stop();
server = null;
label.setText("Status: stoppato");
}
});
//Listen for actions on buttons 1 and 3.
//Add Components to this container, using the default FlowLayout.
add(field);
add(portDatagram);
add(enableHttps);
add(enableAuthentication);
add(start);
add(stop);
add(label);
} |
4994e203-1dcc-4f50-9ba5-3a8ddfb6231a | 6 | public void exportSolution() {
int steps = model.getMoves().size();
File file = new File(basePath + player + "/" + FOLDER_SOLUTIONS + "/"
+ levelName + ".sol");
// Create the file, if it doesn't already exist
try {
if (file.createNewFile()) {
try {
FileWriter fw = new FileWriter(file);
fw.write("9999999:dummy");
fw.close();
} catch (Exception ex2) {
ex2.printStackTrace();
}
}
} catch (Exception ex) {
}
String fileContent = new String();
try {
fileContent = new String(Files.readAllBytes(Paths.get(file
.toString())));
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println(fileContent);
String[] content = fileContent.split(":");
// Check if the current solution is better than the existing.
if (Integer.parseInt(content[0]) > steps) {
String playerPath = view.board.getPlayerPath();
String newFileContent = steps + ":" + playerPath;
try {
FileWriter fw = new FileWriter(file);
fw.write(newFileContent);
fw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} |
c8e9af3a-8fd3-4702-b3c2-761562866a1c | 4 | @Override
public T createAdaptiveExtensionProxy(final Class<T> iFaceType) {
checkAnnotation(iFaceType);
Enhancer en = new Enhancer();
en.setSuperclass(iFaceType);
en.setCallback(new MethodInterceptor() {
@Override
public Object intercept(Object arg0, Method method, Object[] params, MethodProxy arg3) throws Throwable {
Object extension = null;
for (Object param : params) {
Class<?> paramClass = param.getClass();
if (ADAPTIVE_ANALYST.containsKey(paramClass)) {
String extensionKey = ADAPTIVE_ANALYST.get(paramClass).getExtensionKey(param);
extension = SPIExtension.getExtensionLoader(iFaceType).getExtension(extensionKey);
break;
}
}
if (extension == null) {
extension = SPIExtension.getExtensionLoader(iFaceType).getDefaultExtension();
}
return method.invoke(extension, params);
}
});
return (T) en.create();
} |
031eb6fc-3280-4336-8746-9b60dead182d | 0 | @Override
public void setIndicatorState(int indicatorState) {
this.indicatorState = indicatorState;
} |
baeeb7ce-0984-4505-8a7c-bbe3e5b88bbc | 4 | static private int jjMoveStringLiteralDfa6_0(long old0, long active0)
{
if (((active0 &= old0)) == 0L)
return jjStartNfa_0(4, old0);
try { curChar = input_stream.readChar(); }
catch(java.io.IOException e) {
jjStopStringLiteralDfa_0(5, active0);
return 6;
}
switch(curChar)
{
case 110:
return jjMoveStringLiteralDfa7_0(active0, 0x200000L);
case 111:
return jjMoveStringLiteralDfa7_0(active0, 0x800000L);
default :
break;
}
return jjStartNfa_0(5, active0);
} |
dfc39f99-f0d2-4fbc-8033-1d552855ea50 | 8 | private JPanel multiLineLabelPanel(String sourceL,
int splitWidth) {
JPanel jp = new JPanel();
Vector v = new Vector();
int labelWidth = m_fontM.stringWidth(sourceL);
if (labelWidth < splitWidth) {
v.addElement(sourceL);
} else {
// find mid point
int mid = sourceL.length() / 2;
// look for split point closest to the mid
int closest = sourceL.length();
int closestI = -1;
for (int i = 0; i < sourceL.length(); i++) {
if (sourceL.charAt(i) < 'a') {
if (Math.abs(mid - i) < closest) {
closest = Math.abs(mid - i);
closestI = i;
}
}
}
if (closestI != -1) {
String left = sourceL.substring(0, closestI);
String right = sourceL.substring(closestI, sourceL.length());
if (left.length() > 1 && right.length() > 1) {
v.addElement(left);
v.addElement(right);
} else {
v.addElement(sourceL);
}
} else {
v.addElement(sourceL);
}
}
jp.setLayout(new GridLayout(v.size(), 1));
for (int i = 0; i < v.size(); i++) {
JLabel temp = new JLabel();
temp.setFont(new Font(null, Font.PLAIN, 9));
temp.setText(" "+((String)v.elementAt(i))+" ");
temp.setHorizontalAlignment(JLabel.CENTER);
jp.add(temp);
}
return jp;
} |
41731ab3-7ebd-467f-acf2-9e97f4bb3daa | 8 | public Object getValueAt( int rowIndex, int columnIndex )
{
Object back = "" ;
TLanguageFile dummy = data.getData(rowIndex) ;
if (dummy != null)
{
switch (columnIndex)
{
case -1 : // normally not used - debugging
if ( (data.getDefaultLang() != null) && (rowIndex == 0))
back = "default" ;
else back = dummy.getFullLanguageName() ;
break ;
case 2 : // visibility
back = dummy.getVisible() ;
break ;
case 1 : // language name
back = dummy.getFullLanguageName() ;
break ;
default : // language iso code
if ( (data.getDefaultLang() != null) && (rowIndex == 0))
back = "default" ;
else back = dummy.getLanguageCode() ;
}
}
return back ;
} |
9c931508-7eef-44f1-84f9-158d67f1172c | 6 | @Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TimeTable other = (TimeTable) obj;
if (this.dayOfWeek != other.dayOfWeek) {
return false;
}
if (!Objects.equals(this.time, other.time)) {
return false;
}
if (!Objects.equals(this.classroom, other.classroom)) {
return false;
}
if (!Objects.equals(this.course, other.course)) {
return false;
}
return true;
} |
3bc3f6d1-662c-41a3-9e34-7cd499de3f40 | 5 | @Around("execution(* ProfileServiceImpl.readProfile(..))")
public void aroundRead(ProceedingJoinPoint joinPoint) throws Throwable{
ProfileServiceImpl profileService = (ProfileServiceImpl)joinPoint.getTarget();
Object [] args = joinPoint.getArgs();
System.out.println(args[0] + " reads the profile of " + args[1]);
if (!profileService.getProfileMap().containsKey(args[0])){
System.out.println(args[0] + " does not exist!");
return;
}
if(!profileService.getProfileMap().containsKey(args[1])){
System.out.println(args[1] + " does not exist");
return;
}
boolean okToRead = false;
for(Profile prof : profileService.getProfileMap().get(args[0])){
if(prof.getUserId() == args[1]){
System.out.println("OK to read the profile.");
okToRead = true;
break;
}
}
if(okToRead){Object result = joinPoint.proceed();}
else{
System.out.println("Does not have the priviledge to read!");
throw new UnauthorizedException("Does not have the priviledge to read exception!");
}
} |
59a229c1-2559-4bac-ba8a-bf25f985ef3b | 5 | private final List<File> getFiles(File dir, List<File> files)
throws ClusterException {
if(dir == null)
throw new ClusterException("The directory is null");
if(files == null)
files = new ArrayList<File>();
if(dir.isDirectory() == false) {
if(dir.getName().startsWith("SONG_LL_"))
files.add(dir);
return files;
}
for (File file : dir.listFiles())
this.getFiles(file, files); //recursive approach.
return files;
} |
0ac16ade-e680-46ba-bf12-3ac14142cd56 | 2 | private double search() {
double l=mu-sigma*2;
double r=mu+sigma*2;
while (l+0.1<r){
double t1=(r-l)/3+l;
double t2=2*(r-l)/3+l;
if(f(t1) < f(t2))
l=t1;
else r=t2;
}
return (l+r)/2;
} |
af932930-4b4b-4322-ac86-66469e18d9b1 | 0 | public int size() {
return results.size();
} |
6101c232-ca80-4007-a5b5-a7cd828d66f2 | 3 | public void setReal(TReal node)
{
if(this._real_ != null)
{
this._real_.parent(null);
}
if(node != null)
{
if(node.parent() != null)
{
node.parent().removeChild(node);
}
node.parent(this);
}
this._real_ = node;
} |
3e578c44-6f4d-4bbd-8b4f-dd56501a7380 | 4 | private void consume() {
try {
if (requestSocket != null) {
while (!queue.isEmpty()) {
for (ProcessRequestData processRequestData : queue) {
queue.poll();
processCommand.processRequest(processRequestData);
}
queue.notifyAll();
}
} else {
Thread.sleep(wait);
ComvenientConsumer.getConnection();
}
} catch (InterruptedException e) {
logger.error("thread is Interrupted for the : " + e.getCause().getLocalizedMessage());
}
} |
7bbb6bf6-b088-4d99-a58d-4a432bc8f61a | 9 | public void togglePause() {
if(state.sdprint){
//Execute commands to pause
if(state.pause){
state.pause=false; //Continue and resume
addToPrintQueue(GCodeFactory.getGCode("M24",-24), false);
}else{
addToPrintQueue(GCodeFactory.getGCode("M25",-25), false);
try {
Thread.sleep(1000); //wait for printqueue to execute command before toggle pause
} catch (InterruptedException e) {
}
state.pause=true;
}
}else{
state.pause = !state.pause;
}
if (state.pause) {
if(state.debug){
cons.appendText(showDebugData());
}
cons.appendText("Pause at line "+ state.lineidx);
//Move to 0:0 on pause, set a recoverypoint to return to last coord when continue
if(homexypause){
//cons.appendText(state.lastgcode.toString());
setRecoverPoint();
if(state.activeExtr == 0){
// cons.appendText("Pause Extr0");
addToPrintQueue(GCodeFactory.getGCode("G1 X0 Y0", -128), true);
}else{
//assume that the extruder offset prevents us from moving to 0:0
// cons.appendText("Pause Extr1");
addToPrintQueue(GCodeFactory.getGCode("G1 X25 Y25", -128), true);
}
}
} else {
cons.appendText("Continue");
}
if(state.printing){
if(state.pause){
cons.updateState(States.PAUSED,States.NONE , -1);
}else{
cons.updateState(States.PRINTING,States.NONE , -1);
}
}
} |
194ccf60-e85e-4b31-9c36-86703fa676b6 | 5 | private boolean ignoreScan(String intf)
{
if (scanPackages != null)
{
for (String scan : scanPackages)
{
// do not ignore if on packages to scan list
if (intf.startsWith(scan + "."))
{
return false;
}
}
return true; // didn't match whitelist, ignore
}
for (String ignored : ignoredPackages)
{
if (intf.startsWith(ignored + "."))
{
return true;
}
else
{
//System.out.println("NOT IGNORING: " + intf);
}
}
return false;
} |
1ba8aed2-78cd-453c-bf68-5c477e8aec8b | 0 | public FSATransitionCreator(AutomatonPane parent) {
super(parent);
} |
5daec423-6bd3-4aef-b648-63fcf575c918 | 7 | private boolean isFunctionOver(){
if(this.token.length()>0){
String tmp=this.token;
int leftBracketCount=0;
int rightBracketCount=0;
char T[]=tmp.toCharArray();
for(int i=0;i<T.length;++i){
if(T[i]=='('){
leftBracketCount++;
}else if(T[i]==')'){
rightBracketCount++;
}
}
if(leftBracketCount>0||rightBracketCount>0){
if(leftBracketCount==rightBracketCount){
return true;
}
}
}
return false;
} |
bc52a583-5e77-46b1-992a-fafa8936bdd6 | 1 | @Override
public void Connect(Server server) {
this.server = server;
try {
Class.forName(DRIVER).newInstance();
connection = DriverManager.getConnection(getURL() + DB, username, pass);
} catch (Exception e) {
e.printStackTrace();
}
} |
f26d4185-6ac3-46ba-8819-4ef8f8fce486 | 3 | protected void setCell(CellSnapshot cellSnapshot) {
if ( (cellSnapshot.id != this.cellSnapshot.id)
|| (cellSnapshot.row != this.cellSnapshot.row)
|| (cellSnapshot.positionInRow != this.cellSnapshot.positionInRow)
) {
this.cellSnapshot = cellSnapshot;
this.repaint();
}
} |
1d9fafac-42fa-4c6f-88a9-012cd9179772 | 8 | private int findSize(int type) {
int size = 1;
int edgeCount;
if (type % 2 == 0) {
edgeCount = 3;
} else {
edgeCount = 4;
}
size += edgeCount;
if ((type / 2) % 2 == 1)
size += 1; /* Material */
if ((type / 4) % 2 == 1)
size += 1; /* Face UV */
if ((type / 8) % 2 == 1)
size += edgeCount; /* Face Vertex UV */
if ((type / 16) % 2 == 1)
size += 1; /* Face normal */
if ((type / 32) % 2 == 1)
size += edgeCount; /* Face vertex normal */
if ((type / 64) % 2 == 1)
size += 1; /* Face color */
if ((type / 128) % 2 == 1)
size += edgeCount; /* Face vertex color */
return size;
} |
852ea053-7647-403e-8827-3f675bf16ede | 7 | public IMessage decrypter(IMessage crypte, String key) {
/*
* Les caractres sont dcods un un via oprations elementaires
* Les caractres ne correspondant pas des lettres sont ajouts tel quels.
*/
long d=new Date().getTime();
int k=Integer.parseInt(key);
char[] c=new char[crypte.taille()];
for(int i=0;i<crypte.taille();i++) {
if(crypte.getChar(i)>=65 && crypte.getChar(i)<=90) {
if((crypte.getChar(i)-65-k)<0) {
c[i]=(char)(65+26+((crypte.getChar(i)-65-k)));
}
else {
c[i]=(char)(65+((crypte.getChar(i)-65-k)));
}
}
else {
if(crypte.getChar(i)>=97 && crypte.getChar(i)<=122) {
if((crypte.getChar(i)-97-k)<0) {
c[i]=(char)(97+26+((crypte.getChar(i)-97-k)));
}
else {
c[i]=(char)(97+((crypte.getChar(i)-97-k)));
}
}
else{
c[i]=crypte.getChar(i);
}
}
}
this.time=new Date().getTime()-d;
return Fabrique.fabriquerMessage(c);
} |
562254be-d5ac-48ae-b631-35e59a25a4a9 | 5 | private boolean sendGridlet(String errorMsg, int gridletId, int userId,
int resourceId, double delay, int tag, boolean ack)
{
boolean valid = validateValue(errorMsg, gridletId, userId, resourceId);
if (!valid || delay < 0.0) {
return false;
}
int size = 14; // size of having 3 ints + 2 bytes overhead
int[] array = new int[ARRAY_SIZE];
array[0] = gridletId;
array[1] = userId;
array[2] = NOT_FOUND; // this index is only used by gridletMove()
// if an ack is required, then change the tag
int newTag = tag;
if (ack)
{
switch (tag)
{
case GridSimTags.GRIDLET_PAUSE:
newTag = GridSimTags.GRIDLET_PAUSE_ACK;
break;
case GridSimTags.GRIDLET_RESUME:
newTag = GridSimTags.GRIDLET_RESUME_ACK;
break;
default:
break;
}
}
// send this Gridlet
send(super.output, delay, newTag, new IO_data(array, size, resourceId));
return true;
} |
24415af9-22e2-4b73-95d3-0f07cffb51a1 | 1 | protected long getChecksumStream(InputStream in) throws ClassNotFoundException,
InstantiationException, IllegalAccessException, IOException {
CheckedInputStream cis = new CheckedInputStream(in, createChecksumObject());
byte[] buff = new byte[128];
while (cis.read(buff) >= 0) {
}
return cis.getChecksum().getValue();
} |
0f56211f-d05b-4224-95c6-0e030e95043b | 2 | @Override
public void resetAllProperties() {
Iterator it = getKeys();
while (it.hasNext()) {
String key = (String) it.next();
if (propertyDefaultExists(key)) {
setProperty(key, getPropertyDefault(key));
} else {
removeProperty(key);
}
}
} |
d21b1d5b-ee6d-4b6c-a23a-4dbf33e207b2 | 5 | public OperationExpression combineConstInput() {
Operator newOp;
if (left instanceof BooleanConstant) {
if (((BooleanConstant) left).getConst()) { // true const
newOp = ((PrimitiveOperator) op).oneLeft();
} else {
newOp = ((PrimitiveOperator) op).zeroLeft();
}
return new BinaryOpExpression(newOp, middle, right);
}
if (middle instanceof BooleanConstant) {
if (((BooleanConstant) middle).getConst()) { // true const
newOp = ((PrimitiveOperator) op).oneMid();
} else {
newOp = ((PrimitiveOperator) op).zeroMid();
}
return new BinaryOpExpression(newOp, left, right);
}
// right IS instanceof BooleanConstant
if (((BooleanConstant) right).getConst()) { // true const
newOp = ((PrimitiveOperator) op).oneRight();
} else {
newOp = ((PrimitiveOperator) op).zeroRight();
}
return new BinaryOpExpression(newOp, left, middle);
} |
30ea6db6-90d7-4aed-9b8b-9dd6c0d38475 | 8 | public manajData1() {
initComponents();
conn = new DBconn();
getDataFromDb();
System.out.println(queryPendaftar.length +" | "+ queryPendaftar[0].length);
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][1], x, 0);
}
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][2], x, 1);
}
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][4], x, 2);
}
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][6], x, 3);
}
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][7], x, 4);
}
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][8], x, 5);
}
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][9], x, 6);
}
for(int x=0; x<queryPendaftar.length; x++){
jTable1.setValueAt(queryPendaftar[x][1], x, 0);
}
} |
bb964837-dba1-48f7-8b1c-383f34ff7d57 | 0 | public QueuePublisherThread(BlockingQueue<Integer> queue) {
this.queue = queue;
} |
be57592f-e77b-4718-a742-28172ba1fb01 | 9 | private void readLuminance() {
int type = sourceImage.getType();
if (type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB) {
int[] pixels = (int[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
int p = pixels[i];
int r = (p & 0xff0000) >> 16;
int g = (p & 0xff00) >> 8;
int b = p & 0xff;
data[i] = luminance(r, g, b);
}
} else if (type == BufferedImage.TYPE_BYTE_GRAY) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xff);
}
} else if (type == BufferedImage.TYPE_USHORT_GRAY) {
short[] pixels = (short[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
for (int i = 0; i < picsize; i++) {
data[i] = (pixels[i] & 0xffff) / 256;
}
} else if (type == BufferedImage.TYPE_3BYTE_BGR) {
byte[] pixels = (byte[]) sourceImage.getData().getDataElements(0, 0, width, height, null);
int offset = 0;
for (int i = 0; i < picsize; i++) {
int b = pixels[offset++] & 0xff;
int g = pixels[offset++] & 0xff;
int r = pixels[offset++] & 0xff;
data[i] = luminance(r, g, b);
}
} else {
throw new IllegalArgumentException("Unsupported image type: " + type);
}
} |
86aa68f2-d2d1-4433-9e4b-a1a7fb749427 | 5 | public static <T> List<T> simpleFind(String sql,ResultSetBeanMapping<T> mapping)
throws SQLException{
Connection con = null;
Statement smt = null;
try {
con = DBManager.getConnection();
smt = con.createStatement();
ResultSet rs = smt.executeQuery(sql);
List<T> list = new ArrayList<T>();
while(rs.next()){
T bean = mapping.createFormResultSet(rs);
list.add(bean);
}
return list;
} finally {
if(smt != null){
try {
smt.close();
} catch (SQLException ignore) {}
}
if(con != null){
try {
con.close();
} catch (SQLException ignore) {}
}
}
} |
93c1c086-b576-418e-b192-4b9a7c9e2076 | 7 | @Override
public boolean addPriceReserveAlert(boolean value,AuctionBean auctionBean) {
ObjectComparator objectComparator=new ObjectComparator();
//Si l'utilisateur est acheteur, ou un acheteur vendeur
if(this.getRole().equals(RoleEnum.BUYER)|| this.getRole().equals(RoleEnum.SELLER_BUYER)){
//il faut que l'enchere ne sois pas a l'utilisateur
if(this.getListAuctionBean().get(auctionBean.getAuctionId())==null){
if(value){
AlertObserver userAlertObserver=new AlertObserver(new Object(),this,AlertType.ALERT_PRICE_RESERVE);
auctionBean.addAlertObserver(userAlertObserver);
System.out.println(Messages.ALERT_ADD);
return true;
}else{
for (AlertObserver alert : auctionBean.getListObserverAlert()) {
if (objectComparator.compare(alert.getAlertUser(), this) == 0 && alert.getAlertType().equals(AlertType.ALERT_PRICE_RESERVE)) {
auctionBean.deleteObserver(alert);
}
}
System.out.println(Messages.ALERT_REMOVE);
return true;
}
}else{
System.out.println(Messages.AUCTION_BELONG_TO_USER);
return false;
}
}else{
System.out.println(Messages.NO_RIGHT_ADD_ALERT_AUCTION);
return false;
}
} |
a33e1c11-7319-410c-8f65-aca0090e103e | 4 | @Override
public HantoPiece getPieceAt(HantoCoordinate where) {
HantoPiece ret = null;
HantoCoordinate zero = new BasicCoordinate(0, 0);
if(where.getX() == 0 && where.getY() == 0) {
ret = new BasicHantoPiece(HantoPieceType.BUTTERFLY, HantoPlayerColor.BLUE);
}
else if(isAdjacent(zero, where) && currentTurn == HantoPlayerColor.RED) {
ret = new BasicHantoPiece(HantoPieceType.BUTTERFLY, HantoPlayerColor.RED);
}
return ret;
} |
4ad3d307-43da-42c7-8286-e11a66f115d0 | 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?!!");
} |
85f32687-f93e-4cae-99e7-568a295bf0fe | 9 | private void savePrefs()
{
for (int i = 0; i < Math.min(cmbFilter.getItemCount(), 20); i++)
prefs.put(PREFS_KEY_FILTER + i, cmbFilter.getItemAt(i));
if (tblClasses.getRowSorter().getSortKeys().size() > 0)
{
int i = tblClasses.getRowSorter().getSortKeys().get(0).getColumn() + 1;
SortOrder order = tblClasses.getRowSorter().getSortKeys().get(0).getSortOrder();
prefs.putInt(PREFS_KEY_CLASS_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
}
else
prefs.putInt(PREFS_KEY_CLASS_SORT, 1);
if (tblMethods.getRowSorter().getSortKeys().size() > 0)
{
int i = tblMethods.getRowSorter().getSortKeys().get(0).getColumn() + 1;
SortOrder order = tblMethods.getRowSorter().getSortKeys().get(0).getSortOrder();
prefs.putInt(PREFS_KEY_METHOD_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
}
else
prefs.putInt(PREFS_KEY_METHOD_SORT, 1);
if (tblParams.getRowSorter().getSortKeys().size() > 0)
{
int i = tblParams.getRowSorter().getSortKeys().get(0).getColumn() + 1;
SortOrder order = tblParams.getRowSorter().getSortKeys().get(0).getSortOrder();
prefs.putInt(PREFS_KEY_PARAM_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
}
else
prefs.putInt(PREFS_KEY_PARAM_SORT, 1);
if (tblFields.getRowSorter().getSortKeys().size() > 0)
{
int i = tblFields.getRowSorter().getSortKeys().get(0).getColumn() + 1;
SortOrder order = tblFields.getRowSorter().getSortKeys().get(0).getSortOrder();
prefs.putInt(PREFS_KEY_FIELD_SORT, order == SortOrder.DESCENDING ? i * -1 : i);
}
else
prefs.putInt(PREFS_KEY_FIELD_SORT, 1);
} |
c216e36d-b720-4b18-85cd-ddb9370f6fda | 7 | public static void main(String[] args) throws Exception{
SOP("==========Chapter 5 Bit Manipulation===");
SOP("To run: java c5 [function name] [function arguments]");
SOP("Example: java c5 q1");
SOP("");
SOP("Possible functions:");
SOP("q1\tQuestion 1");
SOP("q2\tQuestion 2");
SOP("q3\tQuestion 3");
SOP("q4\tQuestion 4");
SOP("q5\tQuestion 5");
SOP("q6\tQuestion 6");
SOP("===============================");
SOP("");
if(args.length < 1){
SOP("ERROR: Must specify function to run");
return;
}
String function = args[0];
if(function.equals("q1")) q1(args);
else if(function.equals("q2")) q2(args);
else if(function.equals("q3")) q3(args);
else if(function.equals("q4")) q4(args);
else if(function.equals("q5")) q5(args);
else if(function.equals("q6")) q6(args);
else SOP("ERROR: Unknown function");
} |
87e6761f-f0e2-4388-82ec-3a49bd45be02 | 2 | public static void main(String[] args) {
try {
throw new LoggingException();
} catch (LoggingException e) {
System.err.println("Catch " + e);
}
try {
throw new LoggingException();
} catch (LoggingException e) {
System.err.println("Catch " + e);
}
} |
b0308a25-4fef-43ab-b55c-64717f45a709 | 0 | public int getScaledHeight() {
return HEIGHT;
} |
0bdcdb6d-9380-4d51-b52a-2bb376981fe6 | 4 | public static int arrayMinIndex(float[] array, int startInd, int endInd){
if(array == null || array.length == 0)
return 0;
float min = array[startInd];
int minInd = startInd;
for(int i=startInd; i<endInd;i++){
if(array[i] < min){
min = array[i];
minInd = i;
}
}
return minInd;
} |
28175c79-a910-4101-bd7b-b33911c3c3de | 4 | @Override
public void init()
{
super.init();
int cch = ByteTools.readShort( getByteAt( 0 ), getByteAt( 1 ) );
int pos = 1;
if( cch > 0 )
{
//A - fHighByte (1 bit): A bit that specifies whether the characters in rgb are double-byte characters.
// 0x0 All the characters in the string have a high byte of 0x00 and only the low bytes are in rgb.
// 0x1 All the characters in the string are saved as double-byte characters in rgb.
// reserved (7 bits): MUST be zero, and MUST be ignored.
byte encoding = getByteAt( ++pos );
byte[] tmp = getBytesAt( ++pos, (cch) * (encoding + 1) );
try
{
if( encoding == 0 )
{
namedRange = new String( tmp, DEFAULTENCODING );
}
else
{
namedRange = new String( tmp, UNICODEENCODING );
}
}
catch( UnsupportedEncodingException e )
{
log.warn( "encoding PivotTable name in DCONNAME: " + e, e );
}
}
cchFile = ByteTools.readShort( getByteAt( pos + cch ), getByteAt( pos + cch + 1 ) );
// either 0 or >=2
if( cchFile > 0 )
{
log.warn( "PivotTable: External Workbooks for Named Range Source are Unsupported" );
}
log.debug( "DCONNAME: namedRange:" + namedRange + " cchFile: " + cchFile );
} |
a0f4c4b1-957d-4e30-84bc-1e6c60695a02 | 3 | public float[] bowl(boolean firstRound){
float[] averageBowl = new float[NUM_FRUIT_TYPES];
float[] platter = platter();
System.out.println(Arrays.toString(platter));
bowlScoreStats = new Stats();
for (int i = 0; i < 1000; i++) {
float[] tempPlatter = platter.clone();
float[] tempBowl = simulateBowl(tempPlatter);
for (int j = 0; j < NUM_FRUIT_TYPES; j++) {
averageBowl[j] += tempBowl[j];
}
bowlScoreStats.addData(Vectors.dot(tempBowl, prefs));
}
for (int i = 0; i < NUM_FRUIT_TYPES; i++) {
averageBowl[i] = averageBowl[i] / 1000;
}
return averageBowl;
} |
cfecf83b-0483-4e6b-9ed4-35687d6baff5 | 0 | public int size() {
return this.equivalenceList.size();
} |
7e1b93d1-26c5-4fea-9ee1-67eaf8268b80 | 1 | @Override
public Word get(Word word){
if(!base.containsKey(word.getWord())){
return null;
}
return new Word(base.ceilingKey(word.getWord()),base.get(base.ceilingKey(word.getWord())));
} |
b51ee27c-bc8c-43d2-8a0c-e586e8508f9c | 3 | @Override
public void execute(CommandSender sender, String worldName, List<String> args) {
this.sender = sender;
if (worldName == null) {
error("No world given.");
reply("Usage: /gworld load <worldname>");
} else if (!hasWorld(worldName)) {
reply("Unknown world: " + worldName);
} else {
if (getWorld(worldName).isLoaded()) {
reply("World " + worldName + " already loaded.");
} else {
getWorld(worldName).load();
reply("Loaded world " + worldName);
}
}
} |
1d92ef53-80a1-4921-a633-d7fa30326e17 | 9 | public static void main(String[] args) {
// TODO Auto-generated method stub
Map<String, Integer> map= new HashMap<String,Integer>();
map.put("Ling", 0);map.put("Yi", 1);map.put("Er", 2);map.put("San", 3);map.put("Si", 4);
map.put("Wu", 5);map.put("Liu", 6);map.put("Qi", 7);map.put("Ba", 8);map.put("Jiu", 9);
map.put("Shi", 10);map.put("Bai", 100);map.put("Qian", 1000);map.put("Wan", 10000);
Scanner sc = new Scanner(System.in);
String str=sc.nextLine();
//处理字符串
String finalStr="";
int i=0;
//声明一个数组
int[] array=new int[5];
Stack<Integer> st=new Stack<Integer>();
int numint=0;
while(i < str.length())
{
String temp="";
temp+=str.charAt(i);
i++;
while(!Character.isUpperCase(str.charAt(i)))
{
temp+=str.charAt(i);
i++;
if(i >= str.length())
break;
}
st.push(map.get(temp).intValue());
}
int i1=0;
int size=st.size();
int finalint=0;
int gewei=0;
while(i1 < size)
{
int m=st.pop();
if(i1 ==0 && m < 10){
if(st.peek()==0)
finalint+=m;
gewei=m;
}
if(m >=10)
{
int tint=m;
m=st.pop();
i1++;
if(finalint == 0)
finalint+=gewei*tint/10;
finalint+=m*tint;
}
i1++;
}
System.out.println(finalint);
} |
b104524c-749c-441e-84d4-8f99eb8f64e1 | 3 | private CellGui cellGuiAt(int row, int col){
for (CellGui cell : cells){
if (cell.underlying().row == row && cell.underlying().column == col) return cell;
}
throw new RuntimeException("unable to find cell at "+row+", "+col+" in next shape gui");
} |
bab2dffe-a43a-4871-8616-a82f1766826b | 7 | @Override
public MapObject doNextAction(MapEngine engine, double s_elapsed) {
if (can_growl && growl_cooldown_left < 0.0) {
registerGrowler(engine);
}
MultipleObject created_objects = new MultipleObject();
if (!is_exploded) {
if (firing_cannon && shields >= 0) {
if (volley_reload_time_left < 0.0) {
--shots_left_in_volley;
if (shots_left_in_volley < 1) {
firing_cannon = false;
}
else {
volley_reload_time_left = VOLLEY_RELOAD_TIME;
}
created_objects.addObject(handleFiringCannon(engine));
}
}
}
created_objects.addObject(super.doNextAction(engine, s_elapsed));
return created_objects;
} |
1980fac3-c7b6-4c12-abcb-be14c4d9c4a2 | 1 | private EntityManager() {
entityList = new LinkedList<Entity>();
registeredComponents = new HashMap<Class<? extends IComponent>, HashMap<Entity, IComponent>>();
} |
2f58b402-c23d-4b11-8bda-61cf1f572347 | 3 | @Override
public void virusAttack(int iterationNum) {
if (updateInfectionStatus && iterationNum != this.timeOfUpdate) {
this.infectionStatus = true;
} else {
if (random.getResult()) {
this.updateInfectionStatus = true;
this.timeOfUpdate = iterationNum;
}
}
} |
600fd755-09b9-4ced-9492-7263e0150749 | 2 | private double average() {
double sum = 0, number = 0;
for (Patient p : this.allPatients) {
if (!p.isHospitalized()) {
sum += p.getTotalTime();
number++;
}
}
return sum / number;
} |
04a1d5e7-3c2a-4d9a-b019-42375b4d545a | 2 | @Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (value instanceof TmpCounterParty) {
cell.setForeground(Color.GREEN);
} else if (value instanceof CounterParty) {
cell.setForeground(Color.RED);
} else {
cell.setForeground(Color.BLACK);
}
return cell;
} |
a5991f05-779f-4654-9038-76feb5f1a321 | 3 | private ASPlayer setCurOnline(ASPlayer data, TableType table, int value) {
switch(table) {
case DAY: data.curDay.online = value;
break;
case WEEK: data.curWeek.online = value;
break;
case MONTH: data.curMonth.online = value;
break;
default: plugin.severe("Invalid Type in setCurOnline");
}
return data;
} |
c51d61d3-8146-473c-94a6-6bdfdfa35375 | 4 | public boolean estPositionValide(Position unePosition)
{
if (unePosition.obtenirCoordonneesEnX() >= 0
&& unePosition.obtenirCoordonneesEnX() < NOMBRE_DE_COLONNES)
if (unePosition.obtenirCoordonneesEnY() >= 0
&& unePosition.obtenirCoordonneesEnY() < NOMBRE_DE_LIGNES)
return true;
return false;
} |
ae001291-e9a8-439b-ba7e-1f419e3b9fcb | 5 | private static void merge(Comparable[] a, Comparable[] aux, int lo,
int mid, int hi) {
for (int k = lo; k <= hi; k++)
aux[k] = a[k];
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
if (i > mid)
a[k] = aux[j++];
else if (j > hi)
a[k] = aux[i++];
else if (less(aux[j], aux[i]))
a[k] = aux[j++];
else
a[k] = aux[i++];
}
} |
fe2aae89-7219-46e5-b552-e5f4ceac4d20 | 3 | @SuppressWarnings({ "unchecked", "rawtypes" })
static ArrayList generateCustomers(Class documentClass) throws Exception {
ArrayList<HashMap<String,Object>> customers = new ArrayList<HashMap<String,Object>>();
for (int i=0;i<documentCount;i++) {
HashMap<String,Object> customer = (HashMap<String, Object>) documentClass.newInstance();
customer.put("name",randomName());
customer.put("ssn",randomSSN());
customer.put("dob",randomDate());
customer.put("age",randomInt(18,99));
customer.put("home phone",randomPhone());
if (i % 3 == 0) {
customer.put("cell phone",randomPhone());
customer.put("services",new String[]{"ATM","Direct Deposit","Checking","Savings"});
} else {
if (i % 2 == 0) {
customer.put("services",new String[]{"ATM","Savings"});
} else {
customer.put("services",new String[]{"CD","Investment"});
}
}
customer.put("address",generateAddress(documentClass));
customer.put("account",generateAccount(i,documentClass));
customers.add(customer);
}
return customers;
} |
93547aaf-a2ed-4a65-9563-754b9b6671a1 | 0 | public void stopLoad() {
isRun = false;
} |
9dc57330-8d36-4615-a195-4342f4956947 | 6 | private boolean LoadKerning(String line)
{
try
{
Scanner s = new Scanner(line);
Kerning newKerning = new Kerning();
int id = 0;
while(s.hasNext())
{
StringTokenizer st = new StringTokenizer(s.next(), "=");
String command = st.nextToken();
if (command.equals("first"))
{
id = Integer.parseInt(st.nextToken());
}
else if (command.equals("second"))
{
newKerning.otherChar = Integer.parseInt(st.nextToken());
}
else if (command.equals("amount"))
{
newKerning.amount = Integer.parseInt(st.nextToken());
}
}
BitmapCharacter c = GetCharacter(id);
if (c != null)
c.kernings.add(newKerning);
return true;
}
catch(Exception e)
{
return false;
}
} |
ecb72a1c-235a-4ef1-a731-c596cc8b1765 | 4 | public void setDirection(int dir)
{
this.direction = dir;
switch(direction) {
case SOUTH :
setRotation(90);
break;
case EAST :
setRotation(0);
break;
case NORTH :
setRotation(270);
break;
case WEST :
setRotation(180);
break;
default :
break;
}
} |
f1b21aca-b6b2-4246-903b-e3ccab3b2bc0 | 6 | double getRowLength(double row) {
if (row <= 0) {
return 0;
}
if (row <= n) {
return 6 * row;
}
if (row <= 2 * n) {
return 3 * n + 3 * row;
}
if (row <= 3 * n) {
return 9 * n;
}
if (row <= 4 * n) {
return 18 *n - 3 * row;
}
if (row < 5 * n) {
return 30 *n - 6 * row;
}
return 0;
} |
fe9f815d-79b4-4adb-bb60-39c94c284574 | 7 | public static void pauseSchedule(){
// used for loops
int i;
// Used to access the specific methods associated with a video player
VideoPlayer currentVideoPlayer;
// Used to access the specific methods associated with a audio player
AudioPlayer currentAudioPlayer;
// Used to access the specific methods associated with a midi player
MidiPlayer currentMidiPlayer;
// Test to see if the schedule is running
if (slideTimer != null)
{
// Cancel Slide Schedule;
slideTimer.cancel();
// Reset slideTimer
slideTimer = null;
//Set the playPause flag
playPause = false;
// Check to see if the slide has any content.
if ( null!= entityPlayers )
{
// Pause All Video,Midi,Audio Playing
for(i =0;i <entityPlayers.size(); i++)
{
// Only pause media if they are active
if (entityPlayers.get(i).getIsActive())
{
if (entityPlayers.get(i) instanceof VideoPlayer)
{
currentVideoPlayer = (VideoPlayer) entityPlayers.get(i);
currentVideoPlayer.pauseMedia();
}
if (entityPlayers.get(i) instanceof AudioPlayer)
{
currentAudioPlayer = (AudioPlayer) entityPlayers.get(i);
currentAudioPlayer.pauseMedia();
}
if (entityPlayers.get(i) instanceof MidiPlayer)
{
currentMidiPlayer = (MidiPlayer) entityPlayers.get(i);
currentMidiPlayer.pause();
}
}
}
}
}
} |
71486e87-4b7a-40c5-8067-cdc7d3d02b11 | 9 | public void quickSort(int[] data, int start, int end){
int i = start;
int j = end;
int p = (start + end)/2;
int pivot = data[p];
while(i < j){
while(i < p && pivot >= data[i]){
++i;
}
if(i < p){
data[p] = data[i];
p = i;
}
while(j > p && pivot <= data[j]){
--j;
}
if(j > p){
data[p]= data[j];
p = j;
}
}
data[p] = pivot;
if(p - start > 1){
quickSort(data, start, p - 1);
}
if(end - p > 1){
quickSort(data, p + 1, end);
}
} |
d1aab7fa-6d3e-4d31-bb4a-ea93e5dc4bca | 2 | @Override
public int hashCode() {
int result;
long temp;
result = itemId;
result = 31 * result + (name != null ? name.hashCode() : 0);
temp = percent != +0.0d ? Double.doubleToLongBits(percent) : 0L;
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
} |
c1483a73-8edf-4c5c-b92a-7cc092789ffe | 0 | private void menuShowHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuShowHelpActionPerformed
formHelp fh = new formHelp();
fh.setAlwaysOnTop(true);
fh.setVisible(true);
// TODO add your handling code here:
}//GEN-LAST:event_menuShowHelpActionPerformed |
9d5f5daf-6a4c-404e-b1a6-5e40ec65bc29 | 8 | private Object js_unescape(Object[] args)
{
String s = ScriptRuntime.toString(args, 0);
int firstEscapePos = s.indexOf('%');
if (firstEscapePos >= 0) {
int L = s.length();
char[] buf = s.toCharArray();
int destination = firstEscapePos;
for (int k = firstEscapePos; k != L;) {
char c = buf[k];
++k;
if (c == '%' && k != L) {
int end, start;
if (buf[k] == 'u') {
start = k + 1;
end = k + 5;
} else {
start = k;
end = k + 2;
}
if (end <= L) {
int x = 0;
for (int i = start; i != end; ++i) {
x = Kit.xDigitToInt(buf[i], x);
}
if (x >= 0) {
c = (char)x;
k = end;
}
}
}
buf[destination] = c;
++destination;
}
s = new String(buf, 0, destination);
}
return s;
} |
c68302dd-95b7-46e7-b516-1c0758d42dc6 | 6 | public static TimeDuration stringToTimeDuration(String duration) {
{ int nDays = 0;
int nMillis = 0;
boolean negativeP = Native.stringSearch(duration, "minus", 0) != Stella.NULL_INTEGER;
int dayStartPosition = 0;
int dayEndPosition = 0;
int msStartPosition = 0;
int msEndPosition = 0;
if (negativeP) {
dayStartPosition = 6;
}
else if (Native.stringSearch(duration, "plus", 0) != Stella.NULL_INTEGER) {
dayStartPosition = 5;
}
else {
dayStartPosition = 0;
}
dayEndPosition = Native.stringSearch(duration, "days", dayStartPosition);
if (dayEndPosition == Stella.NULL_INTEGER) {
return (null);
}
else {
nDays = ((int)(Native.stringToInteger(Native.string_subsequence(duration, dayStartPosition, dayEndPosition - 1))));
}
msStartPosition = Native.string_position(duration, ' ', dayEndPosition);
if (msStartPosition != Stella.NULL_INTEGER) {
msEndPosition = Native.stringSearch(duration, "ms", msStartPosition);
if (msEndPosition != Stella.NULL_INTEGER) {
nMillis = ((int)(Native.stringToInteger(Native.string_subsequence(duration, msStartPosition + 1, msEndPosition - 1))));
}
}
if (negativeP) {
return (TimeDuration.makeTimeDuration(0 - nDays, 0 - nMillis));
}
else {
return (TimeDuration.makeTimeDuration(nDays, nMillis));
}
}
} |
758ed595-c63c-478c-9fbe-b5f7bc0b7633 | 8 | public BareBonesWhile(String[] Lines, String[] CurrentLineParts, LineReference currentLine, HashMap<String, Integer> Variables) throws BareBonesSyntaxException, BareBonesCompilerException
{
super(Lines, currentLine, Variables);
if(!CurrentLineParts[0].equalsIgnoreCase("while")) throw new BareBonesCompilerException("The compiler isn't working, shouldn't be creating a while statement");
if(CurrentLineParts.length != 5) throw new BareBonesSyntaxException("Expecting four arguments for while, variableName not 0 do");
if(!CurrentLineParts[2].equalsIgnoreCase("not") || !CurrentLineParts[3].equalsIgnoreCase("0") || !CurrentLineParts[4].equalsIgnoreCase("do")) throw new BareBonesSyntaxException("Expecting \"variableName not 0 do\" for while statement");
variableName = CurrentLineParts[1];
String lineToRead = "";
boolean hasFinished = false;
do
{
currentLine.increment();
if(currentLine.getLineNumber() >= Lines.length)
{
currentLine.setLineNumber(Lines.length-1);
throw new BareBonesSyntaxException("End expected, but EOF reached");
}
lineToRead = Lines[currentLine.getLineNumber()];
hasFinished = BareBonesInterpreter.removeWhitespace(lineToRead).equalsIgnoreCase("end");
if(!hasFinished)
{
innerStatements.add(BareBonesInterpreter.InterpretLine(Lines, currentLine, Variables));
}
} while(!hasFinished);
} |
bb30ddf3-d6f1-4333-8e45-092c32014996 | 1 | public static String removeNewLine(String text) {
do {
text = text.replaceAll("\n", "");
} while (text.contains("\n"));
return text;
} |
284cefec-b287-4ce6-bef0-103c989dd0a9 | 6 | public double getSimilarity(String s1, String s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
int[] costs = new int[s2.length() + 1];
for (int i = 0; i <= s1.length(); i++) {
int lastValue = i;
for (int j = 0; j <= s2.length(); j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
int newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length()] = lastValue;
}
return costs[s2.length()];
} |
d0745ac9-46e8-4ad8-a9e9-9c2df10fe19c | 2 | public void menuCadastrarHorario(String disci, String dia, int numero,
int hI, int hF) {
try {
Disciplina disciplina = sistemaFrontEnd.pesquisaDisciplina(disci);
try {
sistemaFrontEnd.pesquisaTurma(disci, numero);
sistemaFrontEnd
.cadastraHorarioTurma(disci, numero, dia, hI, hF);
} catch (TurmaInexistenteException e) {
front.exibirMsg("Turma Inexistente!!");
}
} catch (DisciplinaInexistenteException e) {
front.exibirMsg("Disciplina Inexistente!!");
}
} |
ea9afd24-2337-4e15-8298-e5ba56ac8eec | 3 | private int addGNoise(int pixel, Random random) {
int v, ran;
boolean inRange = false;
do {
double nextGaussian = 0;
//nextGaussian = random.nextGaussian();
nextGaussian = getGaussianNoise(this.mean,this.getVariance());
ran = (int) Math.round(nextGaussian * noiseFactor);
v = pixel + ran;
// check whether it is valid single channel value
inRange = (v >= 0 && v <= 255);
if (inRange)
pixel = v;
// if(r++%10000==0)System.out.println(r+": "+inRange);
} while (!inRange);
return pixel;
} |
15a1baed-a020-4aa9-a9b9-e02609e99889 | 4 | public static Dimension sanitizeSize(Dimension size) {
if (size.width < 0) {
size.width = 0;
} else if (size.width > MAXIMUM_SIZE) {
size.width = MAXIMUM_SIZE;
}
if (size.height < 0) {
size.height = 0;
} else if (size.height > MAXIMUM_SIZE) {
size.height = MAXIMUM_SIZE;
}
return size;
} |
ed04aaf5-d051-4cff-9240-1072ee36ec34 | 2 | @Override
public final void mousePressed(MouseEvent mouseevent) {
int x = mouseevent.getX();
int y = mouseevent.getY();
if (frame != null) {
x -= 4;
y -= 22;
}
idleTime = 0;
clickX = x;
clickY = y;
clickTime = System.currentTimeMillis();
if (mouseevent.isMetaDown()) {
clickMode1 = 2;
clickMode2 = 2;
} else {
clickMode1 = 1;
clickMode2 = 1;
}
} |
4ca5e967-3174-4493-9300-53db9d1fde66 | 1 | public Type getCanonic() {
int types = possTypes;
int i = 0;
while ((types >>= 1) != 0) {
i++;
}
return simpleTypes[i];
} |
247985d4-26ef-4903-acb1-ceb42bfe87dd | 6 | public static Cons javaTranslateCondition(Cons condition, boolean symbolcasep) {
{ Cons translatedactions = Cons.cons(Stella.SYM_STELLA_JAVA_STATEMENTS, Cons.javaTranslateListOfTrees(condition.rest).concatenate(Stella.NIL, Stella.NIL));
Stella_Object keys = condition.value;
Stella_Object translatedkeys = null;
Cons translatedkeyslist = Stella.NIL;
if (symbolcasep) {
if (Stella_Object.consP(keys)) {
{
{ Stella_Object key = null;
Cons iter000 = ((Cons)(keys));
Cons collect000 = null;
for (;!(iter000 == Stella.NIL); iter000 = iter000.rest) {
key = iter000.value;
if (collect000 == null) {
{
collect000 = Cons.cons(Stella.javaYieldSymbolIdForm(((IntegerWrapper)(key)).wrapperValue), Stella.NIL);
if (translatedkeyslist == Stella.NIL) {
translatedkeyslist = collect000;
}
else {
Cons.addConsToEndOfConsList(translatedkeyslist, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(Stella.javaYieldSymbolIdForm(((IntegerWrapper)(key)).wrapperValue), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
translatedkeys = translatedkeyslist;
}
}
else {
translatedkeys = Stella.javaYieldSymbolIdForm(((IntegerWrapper)(keys)).wrapperValue);
}
}
else {
translatedkeys = (Stella_Object.consP(keys) ? Cons.javaTranslateListOfTrees(((Cons)(keys))) : Stella_Object.javaTranslateATree(keys));
}
return (Cons.cons(translatedkeys, Cons.cons(translatedactions, Stella.NIL)));
}
} |
38078bc0-d3ae-40d3-a0b1-7bdff0a8345e | 6 | public Matrix3D plus(Matrix3D B) {
Matrix3D A = this;
if (B.M != A.M || B.N != A.N || B.K != A.K) throw new RuntimeException("Illegal matrix dimensions.");
Matrix3D C = new Matrix3D(M, N, K);
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
for (int l = 0; l < K; l++)
C.data[i][j][l] = A.data[i][j][l] + B.data[i][j][l];
return C;
} |
f1d99d8c-b65c-42e1-8c29-2b74e73ddd8d | 0 | @Basic
@Column(name = "level_debt")
public double getLevel_debt() {
return level_debt;
} |
3c012673-22a0-49e4-bbe2-5f8ad3dcfc34 | 6 | public static void main(String[] args) {
PlayGame play = new PlayGame();
int in = 0;
Game game = null;
while (in != 4) {
switch (in = play.userInput()) {
case 1:
game = new Game(new HumanPlayer(), new ComputerPlayer());
break;
case 2:
game = new Game(new HumanPlayer(), new HumanPlayer());
break;
case 3:
game = new Game(new ComputerPlayer(), new ComputerPlayer());
break;
case 4:
System.out.println(" Good Bye");
break;
default:
System.out.println("Wrong input, try again");
}
if (in != 4) {
game.startGame();
}
}
} |
8f6edc1b-2df5-42fc-bdb0-b40e72acb579 | 3 | private void createPrinterCombo() {
PrintService[] services = PrinterJob.lookupPrintServices();
if (services.length == 0) {
services = new PrintService[] { new DummyPrintService() };
}
WrappedPrintService[] serviceWrappers = new WrappedPrintService[services.length];
int selection = 0;
for (int i = 0; i < services.length; i++) {
serviceWrappers[i] = new WrappedPrintService(services[i].getName(), services[i]);
if (services[i] == mService) {
selection = i;
}
}
mServices = new JComboBox<>(serviceWrappers);
mServices.setSelectedIndex(selection);
UIUtilities.setOnlySize(mServices, mServices.getPreferredSize());
mServices.addActionListener(this);
mService = services[selection];
LinkedLabel label = new LinkedLabel(PRINTER, mServices);
add(label, new PrecisionLayoutData().setEndHorizontalAlignment());
add(mServices);
} |
6b22139d-2d7b-457d-bd75-a71f7ee0eb1c | 8 | private boolean find(char[][] board, boolean[][] visited, int i, int j) {
if (i - 1 < 0 || i + 1 >= board.length || j - 1 < 0 || j + 1 >= board[0].length) {
return false;
}
int[] rowStep = {-1, 1, 0, 0};
int[] colStep = {0, 0, -1, 1};
for (int t = 0; t < 4; t++) {
if (visited[i + rowStep[t]][j + colStep[t]] == false &&
board[i + rowStep[t]][j + colStep[t]] == 'O') {
visited[i + rowStep[t]][j + colStep[t]] = true;
boolean result = find(board, visited, i + rowStep[t], j + colStep[t]);
if (result == true) {
board[i + rowStep[t]][j + colStep[t]] = 'X';
} else {
return false;
}
}
}
return true;
} |
746a97b0-e16b-4c0f-b48d-a91a4c6ef8e2 | 6 | public boolean sincronizarModelComView(Servico model) {
if (!txtItendificador.getText().equals("")) {
model.setId(Integer.parseInt(txtItendificador.getText()));
}else{
model.setId(null);
}
if (!cbClientes.getSelectedItem().equals("Selecione")) {
model.setCliente((Cliente) cbClientes.getSelectedItem());
} else {
JOptionPane.showMessageDialog(null, "O cliente é obrigatório");
return false;
}
if (!cbServicos.getSelectedItem().equals("Selecione")) {
model.setTipoDeServico((TipoDeServico) cbServicos.getSelectedItem());
} else {
JOptionPane.showMessageDialog(null, "O tipo de serviço é obrigatório");
return false;
}
if (!txtData.getText().equals("")) {
model.setDataDoServico(formatarData(txtData.getText()));
} else {
JOptionPane.showMessageDialog(null, "A data é obrigatória");
return false;
}
if (!txtNumeroDoServico.getText().equals("")) {
model.setNumeroDoServico(Integer.parseInt(txtNumeroDoServico.getText()));
} else {
JOptionPane.showMessageDialog(null, "O numero do serviço é obrigatório");
return false;
}
if (!txtValor.getText().equals("")) {
model.setValorDoServico(Double.parseDouble(txtValor.getText().replace(",", ".")));
} else {
JOptionPane.showMessageDialog(null, "O valor do serviço é obrigatório");
return false;
}
return true;
} |
b93fa8f1-bd26-4471-b78d-25df655fd3ec | 1 | public void setTotalHrsForYear(double totalHrsForYear) {
if (totalHrsForYear < 0){
throw new IllegalArgumentException("Hour total must be greater than or equal to zero");
}
this.totalHrsForYear = totalHrsForYear;
} |
b1b4d2ef-b171-473c-8e6d-60eb14d83438 | 0 | public Point getPosition()
{
return recognizer.centroid;
} |
c61c5a5b-c601-4c27-8de0-5867de5ca81b | 5 | public void createUser(){
String email, nombre, pass, tipo;
boolean ciclo;
if(activo.validateTipo(Usuario.ADMINISTRADOR) && counterOfUsers < 50){
do{ System.out.print("Ingrese su email: ");
email = scan.next();
ciclo = false;
for (int x=0; x<counterOfUsers; x++) {
if(users[x].getEmail().equals(email)){
ciclo = true;
System.out.println("\033[31mEse email ya existe");
}
}
}while(ciclo);
System.out.print("Ingrese su nombre completo: ");
nombre = scan.next();
System.out.print("Ingrese el password: ");
pass = scan.next();
tipo = Usuario.selectUserType();
users[counterOfUsers++] = new Usuario(email, pass, nombre, tipo);
}
else{
System.out.println("\033[31mNo se permite ingresar un nuevo usuario");
}
} |
6151dcd6-3652-462c-8dd2-4dd8e9717f0f | 8 | private void importData(String tableName, String query,
List<TableField> fieldsList, Connection bizConn, Connection memConn)
throws Exception {
// 共多少行
int totalRowNum = 0;
// 共多少页
int totalPage = 0;
// 相同字段
List<String> joinFieldList = null;
PreparedStatement pst = null;
try {
memConn.setAutoCommit(false);
Dialect dialect = Dialect.getInstance(bizConn);
// 相同字段
joinFieldList = sortingFields(query, fieldsList, bizConn);
StringBuffer sbJoin = new StringBuffer();
for (int i = 0; i < joinFieldList.size(); i++) {
if (sbJoin.length() > 0) {
sbJoin.append(",");
}
sbJoin.append(joinFieldList.get(i));
}
String querySql = "SELECT " + sbJoin.toString() + " FROM (" + query
+ ") queryTmpView ";
totalRowNum = dialect.getMaxRowNum(querySql, bizConn);
totalPage = dialect.totalPage(totalRowNum, chunkSize);
if (totalPage > 0) {
StringBuffer fieldSB = new StringBuffer();
StringBuffer fieldSBV = new StringBuffer();
for (int i = 0; i < joinFieldList.size(); i++) {
String fieldName = joinFieldList.get(i);
if (fieldSB.length() > 0) {
fieldSB.append(",");
fieldSBV.append(",");
}
fieldSB.append(fieldName);
fieldSBV.append("?");
}
StringBuffer sb = new StringBuffer();
sb.append("INSERT INTO ");
sb.append(tableName);
sb.append(" (");
sb.append(fieldSB);
sb.append(") ");
sb.append(" VALUES ");
sb.append("(");
sb.append(fieldSBV);
sb.append(")");
pst = memConn.prepareStatement(sb.toString(),
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
}
for (int i = 0; i < totalPage; i++) {
try {
memConn.setAutoCommit(false);
String sql = dialect.getLimitString(querySql,
i * chunkSize, chunkSize);
ResultSet rs = util.getResultSetBySql(bizConn, sql);
int batchSize = chunkUpdate(rs, pst, joinFieldList);
System.out.println("导入数据量:" + batchSize);
util.close(rs);
memConn.commit();
} catch (Exception e) {
memConn.rollback();
throw e;
}
}
} catch (Exception e) {
throw e;
} finally {
util.close(pst);
}
} |
f9c8cd2b-5192-4b85-9f4b-90dad052fff4 | 1 | public static List<String> toSortedKeyList(Set<Object> keys) {
List<String> list = new ArrayList<String>();
for (Object key : keys) {
list.add(key.toString());
}
Collections.sort(list);
return list;
} |
35b85faa-1759-421e-81a5-2360cac6ffd8 | 4 | public boolean equals(Object other) {
if ( (this == other ) ) return true;
if ( (other == null ) ) return false;
if ( !(other instanceof RelMarchaProcesionId) ) return false;
RelMarchaProcesionId castOther = ( RelMarchaProcesionId ) other;
return (this.getIdmarcha()==castOther.getIdmarcha())
&& (this.getIdprocesion()==castOther.getIdprocesion());
} |
5ab8f88a-c9c4-4d2e-975a-f77c84636a99 | 5 | public void run() {
try {
Thread.sleep(5000L);
if(NetworkManager.getReadThread(this.netManager).isAlive()) {
try {
NetworkManager.getReadThread(this.netManager).stop();
} catch (Throwable var3) {
;
}
}
if(NetworkManager.getWriteThread(this.netManager).isAlive()) {
try {
NetworkManager.getWriteThread(this.netManager).stop();
} catch (Throwable var2) {
;
}
}
} catch (InterruptedException var4) {
var4.printStackTrace();
}
} |
ddaf0302-c0f1-483c-bf61-45501df83908 | 1 | public static int getTypeSize(String typeSig) {
return usingTwoSlots(typeSig.charAt(0)) ? 2 : 1;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.