method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
a36f98b4-a302-48ea-a68c-2dda42fdbdff | 1 | public void testWithFieldAddWrapped5() {
Partial test = createHourMinPartial();
try {
test.withFieldAddWrapped(DurationFieldType.days(), 6);
fail();
} catch (IllegalArgumentException ex) {}
check(test, 10, 20);
} |
e788433c-b4cc-4c7e-9cb8-e5337cb84618 | 8 | @Override
public void keyReleased(KeyEvent e) {
//MOVEMENT KEYS
if (e.getKeyCode() == KeyEvent.VK_W){
// up = false;
}
if (e.getKeyCode() == KeyEvent.VK_A){
left = false;
}
if (e.getKeyCode() == KeyEvent.VK_S){
// down = false;
}
if (e.getKeyCode() == KeyEvent.VK_D){
right = false;
}
//SHOOT KEYS
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
leftShoot = false ;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
rightShoot = false ;
}
if (e.getKeyCode() == KeyEvent.VK_UP) {
upShoot = false ;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
downShoot = false ;
}
} |
d58a8d46-5744-439f-b5c3-bb64634d5e36 | 5 | private void setHistoryData(){
try {
Share [] sharebuffer = super.getAvailableShare();
for (int i = 0; i < sharebuffer.length; i++){
List<Long> values = new ArrayList<Long>();
BufferedReader in = new BufferedReader(new FileReader("../Java_Boersenmanager/data/" + sharebuffer[i].name));
String file = "";
String buffer = "";
while(true){
buffer = in.readLine();
if(buffer == null)
break;
file = file + buffer + "\n";
}
String[] fileSplit = file.split("\n");
for(int c = 0; c < fileSplit.length; c++){
values.add(Long.parseLong(fileSplit[c]));
}
historyData.put(sharebuffer[i].name, values);
in.close();
}
} catch (IOException e){
;
}
} |
f3933a1e-11c8-4249-8aba-22473e7c7d41 | 0 | private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed
//Récupération de la méthode contrôleur 'close'
((CtrlVisiteurs)controleur).close();
}//GEN-LAST:event_jButtonCloseActionPerformed |
7a77e911-6cb0-433b-a4b1-cb13e41c67fa | 2 | public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
Spel spel = new Spel();
List<logic.Onderwerp> onderwerpen = spel.getOnderwerpen();
spel.setOnderwerp(onderwerpen.get(2));
List<logic.Onderdeel> ondrln = spel.getOnderdelen();
List<logic.Onderdeel> ondrln2 = new ArrayList<logic.Onderdeel>();
ondrln2.add(ondrln.get(0)); // 0
ondrln2.add(ondrln.get(1)); // 1
ondrln2.add(ondrln.get(2)); // 2
ondrln2.add(ondrln.get(3)); // 3
ondrln2.add(ondrln.get(4)); // 4
ondrln2.add(ondrln.get(5)); // 5
ondrln2.add(ondrln.get(6)); // 6
ondrln2.add(ondrln.get(7)); // 7
ondrln2.add(ondrln.get(8)); // 8
for (logic.Onderdeel o : ondrln2) {
spel.volgendeOnderdeel();
spel.kiesOnderdeel(o);
}
SpeelScherm speelscherm = new SpeelScherm(spel);
spel.zetJokersIn(0);
spel.getTimer().stop();
spel.openPanel(speelscherm);
speelscherm.openResultaten();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
73e7f916-db77-487c-98ec-6dda46f63535 | 6 | @Override
public int doEndTag() throws JspException {
if (query == null && bodyContent != null) {
query = bodyContent.getString();
}
if (query == null || "".equals(query)) {
throw new JspException(
"Query must be provided, as an attribute or as BodyContent.");
}
final JspWriter out = pageContext.getOut();
Connection conn = null;
Statement statement = null;
JspException exceptionToThrow = null;
try {
conn = getConnection();
statement = conn.createStatement();
resultSet = statement.executeQuery(query);
SQLUtils.resultSetToHTML(resultSet, new PrintWriter(out),
style1, style1, style2, pkey, link);
} catch (SQLException e) {
exceptionToThrow = new JspException("Database error", e);
} finally {
SQLUtils.cleanup(resultSet, statement, conn);
if (exceptionToThrow != null) {
throw exceptionToThrow;
}
}
resetFields();
return EVAL_PAGE;
} |
371b33f4-0947-492e-8348-fdc58d591081 | 1 | public void saveConfigFile() {
try {
FileTools.dumpStringToFile(new File(Outliner.FIND_REPLACE_FILE), prepareConfigFile(), "UTF-8");
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null, GUITreeLoader.reg.getText("message_could_not_save_find_replace_config") + ": " + ioe.getMessage());
}
} |
be62bceb-8169-4884-8501-64af0d1aef67 | 1 | public static void main(String args[])
{
In in = new In(args[0]);
try
{
Graph g = new Graph(in);
System.out.println(g.toString());
}
catch (Exception e)
{
System.out.println(e);
System.exit(1);
}
} |
feb2da56-bc32-4f45-883d-63533bf44e24 | 4 | @Override
public void onDraw(Graphics G, int viewX, int viewY) {
if (X>viewX&&X<viewX+300&&Y>viewY&&Y<viewY+300)
{
G.setColor(Color.BLACK);
int deg = r.nextInt(360);
G.fillArc((int)(X-1)-viewX, (int)(Y-1)-viewY, 2, 2, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-2)-viewX, (int)(Y-2)-viewY, 4, 4, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-3)-viewX, (int)(Y-3)-viewY, 6, 6, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-4)-viewX, (int)(Y-4)-viewY, 8, 8, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-5)-viewX, (int)(Y-5)-viewY, 10, 10, deg, 60);
deg = r.nextInt(360);
G.fillArc((int)(X-8)-viewX, (int)(Y-8)-viewY, 16, 16, deg, 60);
}
} |
bb4c0e87-1273-451c-90e2-57be4addc2eb | 3 | @Test
public void testCrossUncrossableEdgeInvalid(){
try {
testEdgeUncrossable.cross(testTile1, null);
fail("IllegalArgumentException Expected");
}
catch (IllegalArgumentException e){
//exception expected
}
try {
testEdgeUncrossable.cross(null, testCharacter);
fail("IllegalArgumentException Expected");
}
catch (IllegalArgumentException e){
//exception expected
}
//Illegal now since key has been removed
testCharacter.dropItem(testKey);
try {
testEdgeUncrossable.cross(testTile1, testCharacter);
fail("IllegalArgumentException Expected");
}
catch (IllegalArgumentException e){
//exception expected
}
} |
2556b40c-7442-44a3-94f9-6eacee620692 | 5 | public char[][] fill_grille(int[] position,String plain)
{
assert(position.length==4);
assert(plain.length()<=16);
int total_len=plain.length();
char[][] result=new char[4][4];
int[] cur_holes=new int[4];
for (int i=0;i<4;i++)
{
cur_holes[i]=position[i];
//System.err.println(cur_holes[i]);
}
int str_pos=0;//string position
for(int i=0;i<4;i++)
{
//compute each position and fill the hole
//fill the hole
for(int j=0;j<4;j++)
{
int cur_row=(cur_holes[j])/4;
int cur_col=(cur_holes[j])%4;
if(str_pos<total_len)
{
result[cur_row][cur_col]=plain.charAt(str_pos);
str_pos++;
}
else
{
break;
}
int temp=cur_row;
//turn 90 degrees clockwise
cur_row=cur_col;
cur_col=4-1-temp;
int pos=cur_row*4+cur_col;
cur_holes[j]=pos;
}
if(str_pos>=total_len)
{
break;
}
Arrays.sort(cur_holes);
/* if(i<plain.length())
{
result[cur_row][cur_col]=plain.charAt(i);
}*/
/*for(int j=0;j<3;j++)
{
int temp=cur_row;
//turn 90 degrees clockwise
cur_row=cur_col;
cur_col=4-1-temp;
int cur_pos=i+4*(j+1);
if(cur_pos<plain.length())
{
result[cur_row][cur_col]=plain.charAt(cur_pos);
}
}*/
}
return result;
} |
9b598ece-0a6f-4b16-a61d-63b3c6bfe8dd | 0 | public Set<AndroidMethod> getSinks() {
return sinks;
} |
4c677275-870b-481e-b129-0f9cda2c53b7 | 9 | public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
} |
f433fea3-c857-4e57-ab0e-734a3569433b | 2 | private boolean alreadyListed (String[] list, String value) {
for (String valueListed : list) {
if (value.equals(valueListed)) {
return true;
}
}
return false;
} |
1102cd4a-e2a3-4efa-884a-c61cfbbcaf8e | 0 | public void setG(byte[] value) {
this.g = value;
} |
d07a607c-52f9-4370-a476-b8fbb17bafe0 | 1 | public static MainWindow getInstance() {
if (instance == null)
instance = new MainWindow();
return instance;
} |
4bcf7b15-93cc-4846-924d-3a46e2d288f3 | 2 | public final void grow(int wantedSize) {
if (written)
throw new IllegalStateException("adding to written ConstantPool");
if (tags.length < wantedSize) {
int newSize = Math.max(tags.length * 2, wantedSize);
int[] tmpints = new int[newSize];
System.arraycopy(tags, 0, tmpints, 0, count);
tags = tmpints;
tmpints = new int[newSize];
System.arraycopy(indices1, 0, tmpints, 0, count);
indices1 = tmpints;
tmpints = new int[newSize];
System.arraycopy(indices2, 0, tmpints, 0, count);
indices2 = tmpints;
Object[] tmpobjs = new Object[newSize];
System.arraycopy(constants, 0, tmpobjs, 0, count);
constants = tmpobjs;
}
} |
f93de537-a4c2-4fbd-96d4-edaed28fe760 | 9 | @Override
public void onBlockBreak(BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
List<PlanArea> areas = new ArrayList<PlanArea>(planAreas);
for (PlanArea area : areas) {
if (Config.isFloorInvincible() && area.isFloorBlock(event.getBlock())) {
event.setCancelled(true);
return;
}
if (area.fenceContains(event.getBlock()) || event.getBlock().equals(area.getSignBlock())) {
if (!area.checkPermission(event.getPlayer(), OpType.DESTROY)) {
event.setCancelled(true);
return;
}
if (area.isLocked()) {
event.getPlayer().sendMessage("Area is locked: " + area.getLockReason());
event.setCancelled(true);
return;
}
BuildingPlanner.info("Destroying Plan");
final PlanArea destroyArea = area;
Thread planDestroyThread = new Thread("Plan destroy thread") {
public void run() {
destroyArea.destroyArea();
for (PlanAreaListener listener : listeners) {
listener.destroy(destroyArea);
}
};
};
planDestroyThread.setDaemon(true);
planDestroyThread.start();
continue;
}
}
} |
7cad02d7-d4a2-4ac7-8508-f31bf9428c7a | 5 | private void cargarCampos(int numAsiento){
try {
r_con.Connection();
ResultSet rs=r_con.Consultar("select * from borrador_asientos where ba_nro_asiento="+numAsiento);
Asiento asiento=null;
renglon=0;
BigDecimal debeTotal=new BigDecimal(0);
BigDecimal haberTotal=new BigDecimal(0);
while(rs.next()){
renglon++;
asiento=new Asiento(rs.getInt(1),rs.getInt(2),rs.getDate(3).toString(),
rs.getDate(6).toString(),rs.getDate(7).toString(),
rs.getString(4),rs.getInt(5),rs.getString(8),
rs.getString(9),rs.getFloat(10),rs.getFloat(11),
rs.getBoolean(12),rs.getBoolean(13));
modelo.addRow(asiento.getRenglonModelo());
jTable1.setModel(modelo);
BigDecimal asDebe=convertirEnBigDecimal(asiento.getDebe()+"");
debeTotal=sumarBigDecimal(debeTotal+"",asDebe+"");
BigDecimal asHaber=convertirEnBigDecimal(asiento.getHaber()+"");
haberTotal=sumarBigDecimal(haberTotal+"",asHaber+"");
}
jTextField9.setText(debeTotal+"");
jTextField11.setText(haberTotal+"");
BigDecimal saldo=sumarBigDecimal(debeTotal+"","-"+haberTotal);
jTextField10.setText(saldo+"");
if(asiento!=null){
campoFecha.setText(fecha.convertirBarras(asiento.getFecha_contable()));
jTextField2.setText(++renglon+"");
if(asiento.getTipo().equals("Asiento Apertura")){
jRadioButton1.setSelected(true);
}
else{
if(asiento.getTipo().equals("Asiento Normal")){
jRadioButton2.setSelected(true);
}
else{
jRadioButton3.setSelected(true);
}
}
}
r_con.cierraConexion();
} catch (SQLException ex) {
r_con.cierraConexion();
Logger.getLogger(GUI_Cargar_Asiento.class.getName()).log(Level.SEVERE, null, ex);
}
} |
740dc695-46f3-4be2-b3cb-08f9212031cf | 7 | public void createModuleTable() {
try {
moduleNum = Integer.parseInt(numtf.getText());
if (moduleNum < 1 || moduleNum > MAX_MODULE_NUM) {
JOptionPane.showMessageDialog(null, "模块数量超出范围!");
numtf.setText("");
} else {
for (int i = 0; i <= moduleNum; i++) {
for (int j = 0; j < 4; j++) {
moduleTable[i][j].setVisible(true);
}
}
for (int i = moduleNum + 1; i < MAX_MODULE_NUM + 1; i++) {
for (int j = 0; j < 4; j++) {
moduleTable[i][j].setVisible(false);
}
}
}
validate();
} catch (NumberFormatException excep) {
JOptionPane.showMessageDialog(null, "您输入的数字格式不正确!");
numtf.setText("");
}
} |
1774ee50-dfcc-43fc-adb9-b6dd17a47efd | 2 | public static void main(String[] args) {
Random num = new Random();
//the array frequency can store 7 indexes.
//but we only want indexes one through six for the dice we roll.
int freq[] = new int[7];
//this just loops this 1000 times.
for(int roll = 1; roll <1000; roll++){
//we are adding one index each time we do the counter and we
//are keeping count of how many times. we're also adding one to whichever
//index is called
++freq[1 + num.nextInt(6)];
}
System.out.println("Face\tFrequency");
//print out what each face was rolled and the amount of times it was rolled
for(int i = 1; i < freq.length; i++){
System.out.println(i + "\t" + freq[i]);
}
} |
81ee4242-f953-4e89-b8b4-b27806eb1a26 | 7 | private JSONWriter append(String s) throws JSONException {
if (s == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(s);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
bb8d7a01-70ea-4966-b6d7-56f5dc58eaec | 3 | public void runServer() {
while (true) {
try {
final Socket clientSocket = serverSock.accept();
myThreadPool.execute(new Runnable() {
public void run() {
StreamServerHandler handler = streamHandlerFactory.getHandler(serverSock, clientSocket);
try {
handler.handle(clientSocket);
} catch (IOException e) {
handleError(e);
}
}
});
} catch (IOException e) {
handleError(e);
}
}
} |
c214a0fb-4f00-42b4-a96a-eca1a107c3ba | 1 | public void display() {
//Setting theme
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch(Exception ex) {
logger.warn(ex);
}
SwingUtilities.invokeLater(() -> frame.setVisible(true));
} |
8ca2950a-a7e1-4821-af0a-e2408eb54177 | 0 | public static int sumWithCondition(List<Integer> numbers, Predicate<Integer> predicate) {
return numbers.parallelStream()
.filter(predicate)
.mapToInt(i -> i)
.sum();
} |
e3665955-daf4-49f6-9fc1-624b9cedcb11 | 9 | private static void checkTermRanges(String field, int maxDoc, Terms terms, long numTerms) throws IOException {
// We'll target this many terms in our interval for the current level:
double currentInterval = numTerms;
FixedBitSet normalDocs = new FixedBitSet(maxDoc);
FixedBitSet intersectDocs = new FixedBitSet(maxDoc);
//System.out.println("CI.checkTermRanges field=" + field + " numTerms=" + numTerms);
while (currentInterval >= 10.0) {
//System.out.println(" cycle interval=" + currentInterval);
// We iterate this terms enum to locate min/max term for each sliding/overlapping interval we test at the current level:
TermsEnum termsEnum = terms.iterator();
long termCount = 0;
Deque<BytesRef> termBounds = new LinkedList<>();
long lastTermAdded = Long.MIN_VALUE;
BytesRefBuilder lastTerm = null;
while (true) {
BytesRef term = termsEnum.next();
if (term == null) {
break;
}
//System.out.println(" top: term=" + term.utf8ToString());
if (termCount >= lastTermAdded + currentInterval/4) {
termBounds.add(BytesRef.deepCopyOf(term));
lastTermAdded = termCount;
if (termBounds.size() == 5) {
BytesRef minTerm = termBounds.removeFirst();
BytesRef maxTerm = termBounds.getLast();
checkSingleTermRange(field, maxDoc, terms, minTerm, maxTerm, normalDocs, intersectDocs);
}
}
termCount++;
if (lastTerm == null) {
lastTerm = new BytesRefBuilder();
lastTerm.copyBytes(term);
} else {
if (lastTerm.get().compareTo(term) >= 0) {
throw new RuntimeException("terms out of order: lastTerm=" + lastTerm.get() + " term=" + term);
}
lastTerm.copyBytes(term);
}
}
//System.out.println(" count=" + termCount);
if (lastTerm != null && termBounds.isEmpty() == false) {
BytesRef minTerm = termBounds.removeFirst();
BytesRef maxTerm = lastTerm.get();
checkSingleTermRange(field, maxDoc, terms, minTerm, maxTerm, normalDocs, intersectDocs);
}
currentInterval *= .75;
}
} |
b655b233-45b5-446f-a395-0d13dd251b0e | 1 | private static void addFontStyle(PacketBuilder buffer, char weight, int size) {
if (weight != 'p') {
buffer.writeByte(weight);
}
buffer.writeByte('g');
addSize(buffer, size);
} |
8c3df833-194d-4786-86b9-29d1cb49d879 | 0 | public void setRGB(int red, int green, int blue)
{
this.red = red;
this.green = green;
this.blue = blue;
} |
ad4d7bd5-45e0-462e-b054-b58bf4692363 | 3 | @Override
public ACTIONS act(StateObservation stateObs, ElapsedCpuTimer elapsedTimer) {
double worstCase = 10;
double avgTime = 10;
double totalTime = 0;
double iteration = 0;
int bestAction = -1;
TreeNode root = new TreeNode(stateObs, null);
while(elapsedTimer.remainingTimeMillis() > 2 * avgTime && elapsedTimer.remainingTimeMillis() > worstCase){
ElapsedCpuTimer temp = new ElapsedCpuTimer();
//treeSelect
TreeNode node = root.SelectNode();
//Simulate
double value = node.ExploreNode();
//RollBack
node.UpdateNode(value);
//Get the best action
bestAction = root.GetBestChild();
totalTime += temp.elapsedMillis();
iteration += 1;
avgTime = totalTime / iteration;
}
if(bestAction == -1){
System.out.println("Out of time choosing random action");
bestAction = random.nextInt(actions.length);
}
return actions[bestAction];
} |
23b72b4c-6583-4cd8-a626-9f5b25931649 | 9 | public ILevelPack chooseLevelPack(final Integer levelStage) {
if (isLevelStageNotValid(levelStage) || getLevelPacks(levelStage) == null) {
return null;
}
if (getLevelPacks(levelStage).size() == 0) {
return null;
} else if (getLevelPacks(levelStage).size() == 1) {
regLvlPckSpfcContent(getLevelPacks(levelStage).get(0));
return getLevelPacks(levelStage).get(0);
}
Integer poll = null;
Printer.print(Settings_Output.OUT_OPTION_HEAD, "Please choose a level pack to play");
printLevelPacks(levelStage);
while (poll == null || poll < 0 || poll >= getLevelPacks(levelStage).size()) {
poll = InputReader.readInteger();
if (poll < 0 || poll >= getLevelPacks(levelStage).size()) {
Printer.print(Settings_Output.OUT_ERROR, "Option Error", 0, "Option Error",
"Level Pack out of index");
continue;
}
}
final ILevelPack levelPack = getLevelPacks(levelStage).get(poll);
regLvlPckSpfcContent(levelPack);
return levelPack;
} |
b245db3d-d74c-46ae-89a5-8a7dadaf9595 | 3 | public void increment(int symbol) {
if (symbol < 0 || symbol >= frequencies.length)
throw new IllegalArgumentException("Symbol out of range");
if (frequencies[symbol] == Integer.MAX_VALUE)
throw new RuntimeException("Arithmetic overflow");
total = checkedAdd(total, 1);
frequencies[symbol]++;
cumulative = null;
} |
5d18b77e-09d9-40db-a551-322e6cdfd68d | 6 | private void injectMembers(Class<? extends Object> clazz, final Object instance) throws SecurityException, InstantiationException, IllegalAccessException {
Field[] fields = clazz.getDeclaredFields();
for (final Field field : fields) {
if (field.isAnnotationPresent(Selectable.class)) {
Object value = newElement(field, instance);
if (value != null) {
injectIntoField(instance, field, value);
}
}
}
Class<? extends Object> superclass = clazz.getSuperclass();
if (superclass != null) {
injectMembers(superclass, instance);
}
} |
8570e9bd-86b1-4523-81bc-01be0d3cff58 | 6 | @Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
paintBackground(g);
if (graphComponent != null)
{
// Creates or destroys the triple buffer as needed
if (tripleBuffered)
{
checkTripleBuffer();
}
else if (tripleBuffer != null)
{
destroyTripleBuffer();
}
// Updates the dirty region from the buffered graph image
if (tripleBuffer != null)
{
if (repaintBuffer)
{
repaintTripleBuffer(null);
}
else if (repaintClip != null)
{
repaintClip.grow(1 / scale);
repaintClip.setX(repaintClip.getX() * scale + translate.x);
repaintClip.setY(repaintClip.getY() * scale + translate.y);
repaintClip.setWidth(repaintClip.getWidth() * scale);
repaintClip.setHeight(repaintClip.getHeight() * scale);
repaintTripleBuffer(repaintClip.getRectangle());
}
mxUtils.drawImageClip(g, tripleBuffer, this);
}
// Paints the graph directly onto the graphics
else
{
paintGraph(g);
}
paintForeground(g);
}
} |
d3f8e9dd-a0dc-4a45-b981-390524660b38 | 7 | @Override
public void refresh(RefreshEvent event) {
boolean haveToRefresh = false;
Class evClass = event.getClass();
if (evClass == ResizeEvent.class) {
ResizeEvent ev = (ResizeEvent) event;
this.resize(ev.getHeight() * ev.getWidth());
haveToRefresh = false;
} else if (evClass == TotalGameRefreshEvent.class) {
haveToRefresh = true;
} else if (evClass == EndGameEvent.class) {
haveToRefresh = true;
}
if (haveToRefresh) {
WorldModel wm = (WorldModel) event.getSource();
int width = wm.width();
int height = wm.height();
RefreshEvent ev;
Iterator<TextCellView> iterator = this.cells.iterator();
TextCellView cell;
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
ev = new LocalGameRefreshEvent(wm, i, j);
cell = iterator.next();
cell.refresh(ev);
}
System.out.println();
}
String message = wm.getMessage();
if (message.length() > 0) {
System.out.println(message);
}
int time = wm.getTime();
System.out.println("Time : " + time / 60 + ":" + time % 60);
System.out.println();
this.listenToUser();
}
} |
bc9f7d45-0b99-453a-bb82-fdb2a87b6bf9 | 5 | @Override
public void apply(Person person)
{
if (opponent != null)
{
if (opponent.getHealth() < person.getEquipment().getDamage()*person.getLvlBonus() -
opponent.getEquipment().getStandUp()*opponent.getLvlBonus())
{
opponent.setHealth(0);
opponent.setStatus(PersonState.Died);
person.addExp(100);
if (person.getProfession() == Profession.Robber)
{
person.addMoney(opponent.takeAllMoney());
if (person.getEquipment().equipCompare(opponent.getEquipment().getWeapon()))
person.getEquipment().сhangeWeapon(opponent.getEquipment().getWeapon());
if (person.getEquipment().equipCompare(opponent.getEquipment().getArmor()))
person.getEquipment().сhangeArmor(opponent.getEquipment().getArmor());
}
person.setStatus(PersonState.LastActionCompleted);
person.setOpponent(null);
opponent.setOpponent(null);
}
else
{
opponent.changeHp(-(person.getEquipment().getDamage() * person.getLvlBonus() -
opponent.getEquipment().getStandUp() * opponent.getLvlBonus()));
person.getEquipment().weaponUsed();
opponent.getEquipment().armorUsed();
}
}
} |
4b859f5b-82a2-49f9-9fea-c3c10db857f3 | 7 | private static <AnyType extends Comparable<? super AnyType>>
void merge( AnyType [ ] a, AnyType [ ] tmpArray, int leftPos, int rightPos, int rightEnd )
{
int leftEnd = rightPos - 1;
int tmpPos = leftPos;
int numElements = rightEnd - leftPos + 1;
// Main loop
while( leftPos <= leftEnd && rightPos <= rightEnd )
if( a[ leftPos ].compareTo( a[ rightPos ] ) <= 0 )
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
else
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
while( leftPos <= leftEnd ) // Copy rest of first half
tmpArray[ tmpPos++ ] = a[ leftPos++ ];
while( rightPos <= rightEnd ) // Copy rest of right half
tmpArray[ tmpPos++ ] = a[ rightPos++ ];
// Copy tmpArray back
for( int i = 0; i < numElements; i++, rightEnd-- )
a[ rightEnd ] = tmpArray[ rightEnd ];
} |
3f926414-6a1f-4a4c-9ba3-70e21a315bc7 | 3 | public Entity collidedWith(Environment enviro){
int entityAmount = enviro.getEntityAmount();
for(int i = 0; i < entityAmount; i++){
Entity indexedEnt = enviro.getEntity(i);
if(indexedEnt != this){
if(isCollidedWith(indexedEnt)){
return indexedEnt;
}
}
}
return null;
} |
d25dfe0f-0d1b-4fcf-a620-d211bb7d9d9d | 6 | public Unit findTeacher(Unit student) {
if (getSpecification().getBoolean(GameOptions.ALLOW_STUDENT_SELECTION))
return null; // No automatic assignment
for (Building building : getBuildings()) {
if (building.canTeach()) {
for (Unit unit : building.getUnitList()) {
if (unit.getStudent() == null
&& student.canBeStudent(unit)) return unit;
}
}
}
return null;
} |
1b60b4c2-14d3-483a-8407-61e602fb079d | 4 | private void fillParameterMap(List<UIComponent> components) {
for (UIComponent child : components) {
if (child instanceof UIInput) {
UIInput input = (UIInput) child;
if (!parameterMap
.containsKey(getPropertyNameByUIComponent(input))) {
String propertyName = getPropertyNameByUIComponent(child);
parameterMap.put(propertyName, input.getValue());
}
}
// Recurse the elements children
if (child.getChildCount() > 0) {
fillParameterMap(child.getChildren());
}
}
} |
9b3cb06b-7de9-444f-a366-f1408df32a56 | 6 | public FormPanel (){
Dimension dim = getPreferredSize();
dim.width = 250;
setPreferredSize(dim);
nameLabel = new JLabel("Nombre: ");
occupationLabel = new JLabel ("Edad: ");
nacLabel = new JLabel("Nacionalidad: ");
modLabel = new JLabel("ID del campo a modificar");
nameField = new JTextField(10);
occupationField = new JTextField(10);
nacField = new JTextField(10);
modField = new JTextField(5);
modField.setEnabled(false);
empCombo = new JComboBox();
nacCombo = new JComboBox();
tipoCombo = new JComboBox();
ocuCombo = new JComboBox();
cbMexicano = new JCheckBox("Mexicano",false);
modCheck = new JCheckBox("Modificar por ID",false);
maleRadio = new JRadioButton("Masculino");
maleRadio.setActionCommand("Masculino");
femaleRadio = new JRadioButton("Femenino");
femaleRadio.setActionCommand("Femenino");
otherRadio = new JRadioButton("Otro");
otherRadio.setActionCommand("Gaaaaay");
genderGroup = new ButtonGroup();
maleRadio.setSelected(true);
genderGroup.add(maleRadio);
genderGroup.add(femaleRadio);
genderGroup.add(otherRadio);
ageList=new JList();
DefaultListModel ageModel = new DefaultListModel();
ageModel.addElement(new AgeCategory(23,"18 - 35"));
ageModel.addElement(new AgeCategory(34,"36 - 55"));
ageModel.addElement(new AgeCategory(45,"Mas de 56"));
ageList.setModel(ageModel);
ageList.setPreferredSize(new Dimension(110,70));
ageList.setBorder(BorderFactory.createEtchedBorder());
ageList.setSelectedIndex(0);
///// Nacionalidad ComboBox////////////////
String sql = "select * from nacionalidad";
ArrayList<Nacionalidad> nacList = dbl.resultQueryNac(sql);
DefaultComboBoxModel nacModel = new DefaultComboBoxModel();
for(Nacionalidad f:nacList){
nacModel.addElement(new Nacionalidad(f.getId(),f.getNacionalidad()));
}
nacCombo.setModel(nacModel);
nacCombo.setSelectedIndex(0);
///// Tipo Empleado ComboBox////////////////
sql = "select * from tipoempleado";
ArrayList<Empleado> tipoList = dbl.resultQueryType(sql);
DefaultComboBoxModel typeModel = new DefaultComboBoxModel();
for(Empleado f:tipoList){
typeModel.addElement(new Empleado(f.getId(),f.getTipoEmpleado()));
}
tipoCombo.setModel(typeModel);
tipoCombo.setSelectedIndex(0);
/////Ocupacion ComboBox/////////////////////
sql = "select * from ocupacion";
ArrayList<Ocupacion> ocuList = dbl.resultQueryOcup(sql);
DefaultComboBoxModel ocuModel = new DefaultComboBoxModel();
for(Ocupacion f:ocuList){
ocuModel.addElement(new Ocupacion(f.getId(),f.getOcupacion()));
}
ocuCombo.setModel(ocuModel);
ocuCombo.setSelectedIndex(0);
cbMexicano.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (cbMexicano.isSelected()){
nacField.setEnabled(false);
}
else{
nacField.setEnabled(true);
}
}
});
modCheck.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (modCheck.isSelected()){
modField.setEnabled(true);
actButton.setEnabled(true);
delButton.setEnabled(true);
}
else{
modField.setEnabled(false);
actButton.setEnabled(false);
delButton.setEnabled(false);
}
}
});
delButton = new JButton("Borrar");
delButton.setEnabled(false);
delButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
String sql = "delete from trabajador where idTrabajador="+modField.getText();
dbl.delQuery(sql);
}
});
actButton = new JButton("Actualizar");
actButton.setEnabled(false);
actButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
String name = nameField.getText();
int occupation = ocuCombo.getSelectedIndex()+1;
AgeCategory ageCat = (AgeCategory)ageList.getSelectedValue();
int edad = Integer.parseInt(occupationField.getText());
int empTipo = tipoCombo.getSelectedIndex()+1;
String gender = genderGroup.getSelection().getActionCommand();
System.out.println(gender);
FormEvent ev = new FormEvent(this,name,occupation,edad,empTipo,gender,nacCombo.getSelectedIndex()+1);
String indice = modField.getText();
dbl.actQuery(ev,indice);
}
});
okBtn = new JButton("OK");
okBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
String name = nameField.getText();
int occupation = ocuCombo.getSelectedIndex()+1;
int edad = Integer.parseInt(occupationField.getText());
int empId= 0;
int empTipo = tipoCombo.getSelectedIndex()+1;
String gender = genderGroup.getSelection().getActionCommand();
int naci =nacCombo.getSelectedIndex();
FormEvent ev = new FormEvent(this,name,occupation,edad,empId,empTipo,gender,naci+1);
if(formListener != null){
formListener.formEventOcurred(ev);
}
}
});
Border innerBorder = BorderFactory.createTitledBorder("Agregar Persona");
Border outerBorder = BorderFactory.createEmptyBorder(5,5,5,5);
setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
//////////////////////First ROW////////////////////////////////
gc.weightx =1;
gc.weighty = 0.1;
gc.gridx = 0;
gc.gridy = 0;
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.LINE_END;
gc.insets = new Insets(0,0,0,5);
add(nameLabel,gc);
gc.gridx = 1;
gc.gridy = 0;
gc.insets = new Insets(0,0,0,0);
gc.anchor = GridBagConstraints.LAST_LINE_START;
add(nameField,gc);
////////////////Second ROW///////////////////////////////
gc.weightx =1;
gc.weighty =0.1;
gc.gridy = 1;
gc.gridx = 0;
gc.insets = new Insets(0,0,0,5);
gc.anchor = GridBagConstraints.LINE_END;
add(occupationLabel,gc);
gc.gridy = 1;
gc.gridx = 1;
gc.insets = new Insets(0,0,0,0);
gc.anchor = GridBagConstraints.LINE_START;
add(occupationField,gc);
///////////////Third ROW/////////////////////
gc.weightx = 1;
gc.weighty = 0.2;
gc.gridy = 2;
gc.gridx = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(ocuCombo,gc);
gc.gridy=5;
gc.gridx=1;
add(okBtn,gc);
/////////////////Fourth ROW//////////////////
gc.weightx = 1;
gc.weighty = 0.3;
gc.gridy = 2;
gc.gridx = 0;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(tipoCombo,gc);
////////////////Fifth ROW//////////////////////
gc.weightx = 1;
gc.weighty = 0.5;
gc.gridy = 6;
gc.gridx = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(modField,gc);
//gc.gridy++;
//add(okBtn,gc);
////////////////Sixth ROW///////////////////////
gc.weightx = 1;
gc.weighty = 0.2;
gc.gridy = 3;
gc.gridx = 0;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(maleRadio,gc);
gc.gridy++;
add(femaleRadio,gc);
gc.gridy++;
add(otherRadio,gc);
gc.gridy++;
add(modCheck,gc);
gc.gridy=7;
add(delButton,gc);
gc.gridx++;
add(actButton,gc);
////////////////Seventh ROW/////////////////////
gc.weightx = 1;
gc.weighty = 0.2;
gc.gridy = 3;
gc.gridx = 1;
gc.anchor = GridBagConstraints.FIRST_LINE_START;
gc.insets = new Insets(0, 0, 0, 0);
add(nacCombo,gc);
/////////////////
} |
7cf7bf3b-0af1-42f1-951e-85d480f44b04 | 5 | @Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cell other = (Cell) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
} |
8389725e-f6ee-4cc1-b9a3-ea8cd463718a | 0 | public SHSMemberEntity getAccount() {
return account;
} |
e9f4d084-86f6-434d-abd3-d3bd6d74708c | 0 | public void setStatus(Status status) {
this.status = status;
} |
16c1c02b-9283-4b67-8df4-50bac522b269 | 0 | public LightingSword(){
this.name = Constants.LIGHTING_SWORD;
this.attackScore = 50;
this.attackSpeed = 20; // 20 %
this.money = 4000;
} |
3da2da81-45a3-4d01-bc54-6bd44779f785 | 0 | public void setName(String value) {
this._name = value;
} |
a660456c-5688-49e7-b7a0-0a1eb58f380a | 2 | public void Log (String str) {
if (str.length() > 0) {
try {
cal = Calendar.getInstance();
timestamp = timestampformat.format(cal.getTime());
writer.write(timestamp);
writer.write(str);
writer.newLine();
writer.flush();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
} |
afa364ab-ac99-424f-b534-194aae2c7f6c | 3 | public void readInputStream() {
try {
int buffersize;
if ((buffersize = msgSocket.getSocketInput().available()) != 0) { // is any msg available?
char buffer[] = new char[buffersize];
int count = 0;
while(msgSocket.getSocketInput().available() != 0) {
count = msgSocket.input().read(buffer, 0, buffersize);
System.out.println("< Server: ");
String fromServer = new String(buffer, 0, count);
System.out.println(fromServer);
System.out.println(" verfügbare Zeichen " + buffersize);
}
}
} catch (IOException e) {
e.printStackTrace();
}
} |
36416494-a4b3-4bb9-a157-549761ca4ff1 | 0 | public String getLicenseDate() {
return licenseDate;
} |
c891af8b-3292-46a5-9389-acef35f49743 | 1 | public void actionPerformed(ActionEvent e) {
Grammar g = environment.getGrammar(UnrestrictedGrammar.class);
if (g == null)
return;
UserControlParsePane userPane = new UserControlParsePane(environment, g);
environment.add(userPane, "User Control Parser", new CriticalTag() {
});
environment.setActive(userPane);
} |
111528e7-0b3e-4bd7-ba5f-46075f7e2320 | 3 | public void addElement(Element element) {
if (element == null)
throw new IllegalArgumentException("Element can't be null!");
if (elements.contains(element))
throw new IllegalArgumentException("The argument is already on the grid!");
if (!validPosition(element.getPosition()))
throw new IllegalArgumentException("The argument hasn't got a valid positon!");
elements.add(element);
} |
a2bbfbd8-6686-4f77-ba88-3d378b79327e | 3 | public PropertySheet(Class[] types, Object[] values)
{
this.values = values;
editors = new PropertyEditor[types.length];
setLayout(new FormLayout());
for (int i = 0; i < values.length; i++)
{
JLabel label = new JLabel(types[i].getName());
add(label);
if (Grid.class.isAssignableFrom(types[i]))
{
label.setEnabled(false);
add(new JPanel());
}
else
{
editors[i] = getEditor(types[i]);
if (editors[i] != null)
{
editors[i].setValue(values[i]);
add(getEditorComponent(editors[i]));
}
else
add(new JLabel("?"));
}
}
} |
be1c11d7-e912-4bab-b6a6-bbb44435f117 | 9 | private boolean handleServerStream()
throws IOException , XMLStreamException, XmppException {
// Get the next XML event
int eventType = parser.getEventType();
while ( eventType != XMLStreamConstants.END_DOCUMENT ) {
// Check if the parse event is a XML start tag
if ( eventType == XMLStreamConstants.START_ELEMENT ) {
// Case 1: Stream tag
if ( parser.getLocalName().equals( "stream" ) ) {
handleStreamTag();
}
// Case 2: Features tag
else if ( parser.getLocalName().equals( "features" ) ) {
handleFeaturesTag();
}
// Case 3: Starttls Proceed tag
else if ( parser.getLocalName().equals( "proceed" ) ) {
upgradeToTls();
// We need to re-send the stream tag after TLS
return true;
}
// Case 4: Authentication Challenge tag
else if ( parser.getLocalName().equals( "challenge" ) ) {
respondToChallenge();
}
// Case 5: Authentication Success tag
else if ( parser.getLocalName().equals( "success" ) ) {
handleSuccessTag();
// We need to re-send the stream tag after SASL
return true;
}
// Case 6: Failure tag (for TLS and SASL)
else if ( parser.getLocalName().equals( "failure" ) ) {
handleFailureTag();
}
// Case 7: IQ tag (for resource ID request's response)
else if ( parser.getLocalName().equals( "iq" ) ) {
handleIQTag();
// Return, we have successfully opened the connection
return false;
}
}
// Get the next XML event from the parser
eventType = parser.next();
}
// We are done, no need to re-send the stream tag
return false;
} |
54966932-467b-4c29-beb7-ec7dc47e4745 | 2 | public int count()
{
int count = 0;
try
{
ResultSet set = read("SELECT COUNT(ID) AS COUNT FROM OPERATION");
while(set.next())
{
count = set.getInt("COUNT");
}
set.close();
}
catch(SQLException e)
{
System.out.println("SQL Fehler");
}
return count;
} |
ea46568b-65fb-4e8f-a1c3-ebe54bd40a25 | 5 | public static boolean is_same(char[] c1,char[] c2){
if(c1==null||c2==null){
return false;
}
if(c1.length!=c2.length){
return false;
}
boolean res = true;
for(int i=0;i<c1.length;i++){
if(c1!=c2)
res = false;
}
return res;
} |
10626d74-9f6d-4a51-ac98-4ab492a76cfe | 0 | @Override
public void windowIconified(WindowEvent e) {
} |
1e200005-769b-4700-bd28-081b5cd97e63 | 8 | private final Bullet setFireImpl(double power) {
if (Double.isNaN(power)) {
println("SYSTEM: You cannot call fire(NaN)");
return null;
}
if (getGunHeatImpl() > 0 || getEnergyImpl() == 0) {
return null;
}
power = min(getEnergyImpl(), min(max(power, Rules.MIN_BULLET_POWER), Rules.MAX_BULLET_POWER));
Bullet bullet;
BulletCommand wrapper;
Event currentTopEvent = eventManager.getCurrentTopEvent();
nextBulletId++;
if (currentTopEvent != null && currentTopEvent.getTime() == status.getTime() && !statics.isAdvancedRobot()
&& status.getGunHeadingRadians() == status.getRadarHeadingRadians()
&& ScannedRobotEvent.class.isAssignableFrom(currentTopEvent.getClass())) {
// this is angle assisted bullet
ScannedRobotEvent e = (ScannedRobotEvent) currentTopEvent;
double fireAssistAngle = Utils.normalAbsoluteAngle(status.getHeadingRadians() + e.getBearingRadians());
bullet = new Bullet(fireAssistAngle, getX(), getY(), power, statics.getName(), null, true, nextBulletId);
wrapper = new BulletCommand(power, true, fireAssistAngle, nextBulletId);
} else {
// this is normal bullet
bullet = new Bullet(status.getGunHeadingRadians(), getX(), getY(), power, statics.getName(), null, true,
nextBulletId);
wrapper = new BulletCommand(power, false, 0, nextBulletId);
}
firedEnergy += power;
firedHeat += Rules.getGunHeat(power);
commands.getBullets().add(wrapper);
bullets.put(nextBulletId, bullet);
return bullet;
} |
ad44386d-651a-441a-8dc6-adf51b3b3bbc | 1 | private void addPutstatic0(CtClass target, String classname,
String fieldName, String desc) {
add(PUTSTATIC);
// target is null if it represents THIS.
int ci = classname == null ? constPool.addClassInfo(target)
: constPool.addClassInfo(classname);
addIndex(constPool.addFieldrefInfo(ci, fieldName, desc));
growStack(-Descriptor.dataSize(desc));
} |
b4b38b03-c6ef-4a1a-9d81-098ab5e5382a | 8 | public DisjointSets computeEquivalence() {
computePairs();
if(DEBUG) {
System.out.println("Equivalence table: ");
for(int i = 0; i < nStates; i++) {
for(int j = 0; j < nStates; j++)
System.out.print((table[i][j] ? "1" : "0") + " ");
System.out.println();
}
}
DisjointSets uf = new DisjointSets(nStates);
for(int i = 0; i < nStates; i++)
for(int j = i + 1; j < nStates; j++)
if(areEquivalent(i, j)) {
if(DEBUG)
System.out.println(String.format("Joining %d and %d", i, j));
uf.union(i, j);
}
return uf;
} |
8bed89c8-9f99-442c-9b91-7b8850683a86 | 6 | public void move() {
List<Field> fieldList = this.getField().getNearByRoads(1);
if (fieldList.size() > 1) {
List<Integer> roadIds = new ArrayList<Integer>();
List<Field> possibleFields = new ArrayList<Field>();
// elagazashoz ertunk
this.getField().execute(this);
Random gen = new Random();
for (Field field : fieldList) {
if (field != null) {
possibleFields.add(field);
roadIds.add(fieldList.indexOf(field));
}
}
int i = gen.nextInt(possibleFields.size());
if (fieldList.size() > 1) {
this.setField(fieldList.get(i));
fieldList.get(i).addVisitable(this);
this.setRoad(roadIds.get(i));
} else {
System.out.println("Game over, character reached the end of a road. ");
}
} else {
// nem elagazas
this.getField().execute(this);
if (fieldList.size() < 1) {
System.out.println("Game over, character reached the end of a road. ");
} else {
this.setField(fieldList.get(0));
fieldList.get(0).addVisitable(this);
}
}
// speed reseteles
this.setSpeed(maxSpeed);
// csapdaba lepes visitorminta segitsegevel
for (Visitable v : this.getField().getVisitables()) {
v.accept(this);
}
} |
3a3af897-f0a1-4e0f-965a-db0dd3b33392 | 9 | @SuppressWarnings("unchecked")
public static <T, U, Y extends Collection<T>> Collection<Pair<U, Y>> chunk(Collection<T> c, Function<T, U> f, Class<?>... resultType) {
verifyArguments(c, f);
List<Pair<U, Y>> pairs = (List<Pair<U, Y>>) (resultType.length > 0 ? instantiate(resultType[0]) : new ArrayList<Pair<U, Y>>());
Y previousChunk = (Y) (resultType.length > 0 ? instantiate(resultType[0]) : new ArrayList<T>());
U previousChunkKey = null;
for (T e : c) {
U currentChunkKey = f.call(e);
if ((null == previousChunkKey) || !currentChunkKey.equals(previousChunkKey)) {
if (previousChunk.size() > 0) {
pairs.add(new Pair<U, Y>(previousChunkKey, previousChunk));
};
previousChunk = (Y) (resultType.length > 0 ? instantiate(resultType[0]) : new ArrayList<T>());
previousChunkKey = currentChunkKey;
};
previousChunk.add(e);
};
if (previousChunk.size() > 0) {
pairs.add(new Pair<U, Y>(previousChunkKey, previousChunk));
};
return pairs;
} |
267315db-3d62-43b4-8737-4fa8b9dc864b | 8 | public static void main(String[] args)
{
if (args.length < 1)
{
System.err.println("Usage: newsgroups newsserver [pattern]");
return;
}
NNTPClient client = new NNTPClient();
String pattern = args.length >= 2 ? args[1] : "";
try
{
client.connect(args[0]);
int j = 0;
try {
for(String s : client.iterateNewsgroupListing(pattern)) {
j++;
System.out.println(s);
}
} catch (IOException e1) {
e1.printStackTrace();
}
System.out.println(j);
j = 0;
for(NewsgroupInfo n : client.iterateNewsgroups(pattern)) {
j++;
System.out.println(n.getNewsgroup());
}
System.out.println(j);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (client.isConnected()) {
client.disconnect();
}
}
catch (IOException e)
{
System.err.println("Error disconnecting from server.");
e.printStackTrace();
System.exit(1);
}
}
} |
44c5f2d3-3932-4f6d-a65c-49907c93c9c8 | 5 | private void calculateG(Node node) {
Tile t = MyzoGEN.getOutput().getTile(new Point(node.x, node.y));
if (node.parent != null && t != null) {
int dir = directionFromParent(node);
if (dir == 1)
node.G = roundHeight(t.height);
else if (dir == 0)
node.G = node.parent.G + DIAGONAL_MOVE_COST;
}
if (details) System.out.println("("+node.x+","+node.y+") G = "+node.G);
} |
61228be0-e81f-43f5-b65b-9a889e449b23 | 2 | @RequestMapping(value = {"/EntidadBancaria/{idEntidadBancaria}"}, method = RequestMethod.PUT)
public void update(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idEntidadBancaria") int idEntidadBancaria, @RequestBody String json) {
try {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
EntidadBancaria entidadBancariaUpdate = entidadBancariaDAO.read(idEntidadBancaria);
EntidadBancaria entidadBancaria = (EntidadBancaria) objectMapper.readValue(json, EntidadBancaria.class);
entidadBancariaUpdate.setNombre(entidadBancaria.getNombre());
entidadBancariaUpdate.setCodigoEntidadBancaria(entidadBancaria.getCodigoEntidadBancaria());
entidadBancariaUpdate.setCif(entidadBancaria.getCif());
entidadBancariaUpdate.setTipo(entidadBancaria.getTipo());
entidadBancariaUpdate.setListaSucursalBancaria(entidadBancaria.getListaSucursalBancaria());
entidadBancariaDAO.update(entidadBancariaUpdate);
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
httpServletResponse.setContentType("application/json; charset=UTF-8");
httpServletResponse.getWriter().println(json);
} catch (Exception ex) {
noCache(httpServletResponse);
httpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
httpServletResponse.setContentType("text/plain; charset=UTF-8");
try {
noCache(httpServletResponse);
ex.printStackTrace(httpServletResponse.getWriter());
} catch (Exception ex1) {
noCache(httpServletResponse);
}
}
} |
5d6852cc-cf95-47c8-a43a-58d53e672f9f | 2 | private void render()
{
switch(menu){
case main:
break;
case Game:
RenderUtil.initGraphics();
RenderUtil.clearScreen();
game.render();
Window.render();
break;
}
} |
52e17c97-a320-40c0-9aa3-2d6043a4d1b4 | 9 | @Override
public int distance(GeneralAIUnit unit, GeneralAI ai) {
// ensure unit can build this guy
if (unit.stats.isBuilding() && !def.is_building) {
if (!unit.stats.getProduce().contains(id)) {
return GeneralAI.DISTANCE_IGNORE; // can't even build
}
} else if (!(unit.stats.isWorker() && def.is_building)){
return GeneralAI.DISTANCE_IGNORE;
}
for (int i = 0; i < def.cost.size(); i++) {
if (ai.money.get(i) < def.cost.get(i)) {
return GeneralAI.DISTANCE_IGNORE;
}
}
if (def.is_worker) {
return priority-GeneralAI.DISTANCE_IGNORE; // special priority for workers
} else if (priority == GeneralAI.DISTANCE_IGNORE) {
return GeneralAI.DISTANCE_IGNORE;
}
int distance = (unit.stats.getX()-x)*(unit.stats.getX()-x)+(unit.stats.getY()-y)*(unit.stats.getY()-y);
return (int)(priority*cost_ratio*def.produce_speed)+distance;
} |
710f8730-007e-403d-bb17-4e682e3ccc4e | 0 | public void setEncryptedValue(EncryptedDataType value) {
this.encryptedValue = value;
} |
e1729251-d281-4476-8b10-9f874bcb9700 | 9 | private void reconstructRing() {
FailureDetectorThread.handleMessage("Send Thread: reconstructRing");
checkFailedServer(); // check the failed servers
// remove failed server from the ring
for (Integer id: this.failedServer) {
if(pingPeers.containsKey(id)){
FailureDetectorThread.handleMessage("server " + id + " is out of ring!");
pingPeers.remove(id);
}
}
// there is no failed server, reconstruct normal ring
if(failedServer.size() == 0){
pingPeers.clear();
int i = 1;
for (Map.Entry<Integer, String> peer : allPeers.entrySet()){
if(i++ <= MaxServersToPing)
pingPeers.put(peer.getKey(), peer.getValue());
}
return;
}
// there is at lease one failure, reconstruct the ring if there is any live server left
for (Map.Entry<Integer, String> peer : allPeers.entrySet()) {
int id = peer.getKey();
if(failedServer.contains(id))
continue;
else{
FailureDetectorThread.handleMessage("server " + id + " is in the ring!");
pingPeers.put(id, peer.getValue());
if(pingPeers.size() >= MaxServersToPing)
return;
}
}
// if 3 servers are failed, then exit the application
if(pingPeers.isEmpty()){
FailureDetectorThread.handleMessage("EXIT! at least 3 servers are failed!");
System.exit(-1);
}
} |
f6b99e8d-6b33-4297-98f0-41a593f51d25 | 2 | @Override
public void move() {
if (alive) {
if (stomache > 0) {
addGlied();
stomache--;
}
super.move();
invertedBevoreMoves ++;
}
} |
e5961f19-691e-4aaf-b36a-6cb30dca6cb8 | 1 | public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
iXportSMS window = new iXportSMS();
window.frmIxportIphoneSms.setLocationRelativeTo(null);
window.frmIxportIphoneSms.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
} |
df8e9e4e-2caf-45a8-9202-b45e76aec9c0 | 1 | private void btnannulerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnannulerActionPerformed
//Serialisation
try{
FileOutputStream f = new FileOutputStream("sauvegarde.csv");
ObjectOutputStream s = new ObjectOutputStream(f);
s.writeObject(MainProjet.lesEntreprises);
s.writeObject(MainProjet.lesOffres);
s.close();
}
catch (IOException e) {System.out.println("Problème I/O");
System.out.println(e);}
System.exit(0);
// Permet de quitter la page lorqu'on appuie sur le bouton annuler
}//GEN-LAST:event_btnannulerActionPerformed |
dabfe98f-0e32-44c2-b3d2-2d7a3565a283 | 0 | private String readInput() throws IOException {
return this.keyboard.readLine();
} |
e0ea58c8-8db2-4b46-a707-6f287b17af7d | 3 | @Override
public void execute() {
while (true) {
showMessage();
showCurrencies();
try {
moneyDialog.execute();
currencyDialog.execute("Introduzca la divisa a convertir: ");
this.calculate.execute();
} catch (Exception ex) {
if (ex.getMessage().equalsIgnoreCase("exit"))
this.exit.execute();
}
}
} |
d7b96187-9c48-4596-8755-2ab520b19e08 | 4 | protected void redo() throws CannotRedoException {
if (insertionPoint >= maxInsertionPoint) {
throw new CannotRedoException();
}
if (insertionPoint < maxInsertionPoint) {
AbstractEdit edit = edits.get(insertionPoint);
edit.redo();
publishEdit(edit);
insertionPoint = insertionPoint + 1;
}
while ((insertionPoint < maxInsertionPoint) && (!edits.get(insertionPoint).isSignificant())) {
AbstractEdit edit = edits.get(insertionPoint);
edit.redo();
publishEdit(edit);
insertionPoint = insertionPoint + 1;
}
} |
6d3485c3-c659-4a1d-bed8-518b03ad75ae | 5 | public boolean mouseup(Coord c, int button) {
for (Widget wdg = lchild; wdg != null; wdg = wdg.prev) {
if (!wdg.visible)
continue;
Coord cc = xlate(wdg.c, true);
if (c.isect(cc, (wdg.hsz == null) ? wdg.sz : wdg.hsz)) {
if (wdg.mouseup(c.add(cc.inv()), button)) {
return (true);
}
}
}
return (false);
} |
290f0153-81a3-4fd6-95c9-f523b56c2a36 | 0 | private BeverageFactory() {
} |
9524bd23-9d65-44f5-95cf-259f50f1e93c | 7 | @Override
public void update(Observable o, Object arg) {
String sender = o.getClass().getName();
String message = (String)arg;
System.out.println("EventLogUI received ["+ arg +"] from ["+ sender +"]");
if (sender.equals("Core.Board"))
{
if (message.startsWith("List added: "))
{
List list = log.getBoard().getListById(Integer.parseInt(message.replace("List added: ", "")));
controller.addListEvent(null, list);
}
else if (message.startsWith("List deleted: "))
{
message = message.replace("List deleted: ", "");
List list = log.getListById(Integer.parseInt(message));
controller.addListEvent(list, null);
}
if (message.startsWith("Item added: "))
{
message = message.replace("Item added: ", "");
String[] array = message.split(" in: ");
List list = log.getListById(Integer.parseInt(array[1]));
Item item = list.getItemById(Integer.parseInt(array[0]));
controller.addItemEvent(null, item, list);
}
if (message.startsWith("Item deleted: "))
{
message = message.replace("Item deleted: ", "");
String[] array = message.split(" from: ");
List list = log.getListById(Integer.parseInt(array[1]));
Item item = list.getItemById(Integer.parseInt(array[0]));
controller.addItemEvent(item, null, list);
}
}
else if (sender.equals("Plugins.EventLog.EventLog"))
{
if (message.startsWith("Event added: ")) {
Event event = log.getEventById(Integer.parseInt(message.replace("Event added: ", "")));
log_zone.add(new EventUI(event, event_menu.mouse_listener), FIRST);
log_zone.revalidate();
log_zone.repaint();
}
}
} |
76d78371-ea27-4b1a-b323-0af6e3505d64 | 1 | public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int tests = Integer.parseInt(in.readLine());
while (tests > 0) {
stepsToAnagram(in.readLine());
tests--;
}
} |
bc9a1adc-4647-47bf-b4ad-9ad25406d241 | 6 | private void cycleAnnounce(int i, int milli, boolean silent) throws InterruptedException {
if (this.isCancelled()) {
return;
}
if (!silent) {
Bukkit.broadcastMessage(ChatColor.DARK_RED + ">> " + ChatColor.AQUA + "Cycling to " + ChatColor.DARK_AQUA + "[" + rotatedMap.getType().getType() + "] " + rotatedMap.getMapName() + ChatColor.AQUA + " in " + ChatColor.DARK_AQUA + i + ChatColor.AQUA + " seconds" + ChatColor.DARK_RED + " <<");
}
if (this.team != null) {
for (Entry<Player, ChatColor> set : HyperPVP.teamCycle.entrySet()) {
if (set.getValue() != this.team.getColor()) {
continue;
}
Player p = set.getKey();
ChatColor c = set.getValue();
HyperPVP.fireworkLocation.put(p.getLocation(), TeamColor.get(c));
HyperPVP.checkFirework = true;
}
}
if (this.name != null) {
Player p = name;
ChatColor c = ChatColor.GOLD;
HyperPVP.fireworkLocation.put(p.getLocation(), TeamColor.get(c));
HyperPVP.checkFirework = true;
}
Thread.sleep(milli);
} |
a6ab0eb4-c4df-435f-902a-01b80fb83a05 | 4 | public User getUser(String username) {
PreparedStatement statement = null;
Connection connection = null;
try {
try {
connection = data.getConnection();
statement = connection.prepareStatement("SELECT * FROM User WHERE username = ?");
statement.setString(1, username);
ResultSet result = statement.executeQuery();
if(result.next()) {
User user = new User(result.getString("studentNo"), result.getString("username"),
result.getString("password"), result.getString("firstName"), result.getString("lastName"));
return user;
}
else {
return null;
}
} finally {
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
}
} catch (SQLException ex) {
System.out.println("Error retrieving users");
ex.printStackTrace();
return null;
}
} |
68e81c59-10e0-4034-b71f-8e465a75703b | 3 | public static boolean isNumberType(Class<?> clazz) {
return (clazz == Number.class || clazz.getSuperclass() == Number.class || isPrimitiveNumberType(clazz));
} |
08996c36-757e-4891-8df6-c992668fdb84 | 9 | private Object makeInt()
{
Object result;
String s = image.toString();
int base = 10;
if ( s.charAt(0) == '0' )
base = (s.length() > 1 && (s.charAt(1) == 'x' || s.charAt(1) == 'X'))? 16 : 8;
if ( base == 16 )
s = s.substring(2); // Trim the 0x off the front
switch ( s.charAt(s.length()-1) ) {
case 'l': case 'L':
result = Long.valueOf( s.substring(0,s.length()-1), base );
break;
case 'h': case 'H':
result = new BigInteger( s.substring(0,s.length()-1), base );
break;
default:
result = Integer.valueOf( s, base );
break;
}
return result;
} |
3a131c56-9e52-4883-8295-009901e198c1 | 3 | * @return True, if the contents of this statement list changed.
*/
public boolean retainAll(final Collection c) {
boolean changed = false;
if (c == this) {
return false;
}
final Iterator iter = iterator();
while (iter.hasNext()) {
if (!c.contains(iter.next())) {
changed = true;
iter.remove();
}
}
return changed;
} |
16876303-68f6-41c6-b3e1-e651d4402930 | 7 | public static void main(String[] args) {
Lista lista = new Lista();
int op;
Scanner lea = new Scanner(System.in);
do{
System.out.println("1- Agregar Nodo");
System.out.println("2- Imprimir");
System.out.println("3- Borrar");
System.out.println("4- Agregar Enmedio");
System.out.println("5- Salir");
System.out.println("Escoja opcion: ");
op = lea.nextInt();
switch(op){
case 1:
System.out.println("Nombre: ");
lista.addNodo( new Nodo(lea.next()) );
break;
case 2:
lista.print();
break;
case 3:
System.out.println("Nombre a borrar: ");
if( lista.delete(lea.next()) )
System.out.println("Se borro bien");
else
System.out.println("No se pudo borrar");
break;
case 4:
System.out.println("Nombre de Nodo Nuevo: ");
Nodo obj = new Nodo(lea.next());
System.out.println("Despues de: ");
if( lista.AddInTheMiddle(obj, lea.next()) )
System.out.println("Se agrego exitosamente");
else
System.out.println("No se pudo agregar");
}
}while(op!=5);
} |
95234196-f845-435e-bcb6-74ba826331e6 | 7 | public imageEdit(){
super(new BorderLayout());
//frame = new JFrame();
//frame.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridBagLayout());
panel.setBackground(colorRGB);
//frame.setVisible(true);
//frame.setSize(500,500);
//
pp = new JPanel();
/*
JLabel orig = new JLabel(new ImageIcon(bi));
JPanel ss = new JPanel();
ss.add(orig);
*/
// �������������������� �H�U���ƪ� ��������������������
//
label1 = new JLabel("��V");
label1.setBackground(colorRGB);
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 0;
c1.gridy = 0;
c1.anchor = GridBagConstraints.WEST;
//
angleLabel = new JLabel("����");
angleLabel.setBackground(colorRGB);
GridBagConstraints c2 = new GridBagConstraints();
c2.gridx = 0;
c2.gridy = 1;
c2.anchor = GridBagConstraints.WEST;
//
angleSelect = new JComboBox(angle);
angleSelect.setSelectedIndex(0);
GridBagConstraints c3 = new GridBagConstraints();
c3.gridx = 0;
c3.gridy = 1;
c3.anchor = GridBagConstraints.EAST;
//
topDownRotate = new JCheckBox("�W�U����");
topDownRotate.setBackground(colorRGB);
GridBagConstraints c4 = new GridBagConstraints();
c4.gridx = 0;
c4.gridy = 2;
c4.anchor = GridBagConstraints.WEST;
//
leftRightRotate = new JCheckBox("���k����");
leftRightRotate.setBackground(colorRGB);
GridBagConstraints c5 = new GridBagConstraints();
c5.gridx = 0;
c5.gridy = 3;
c5.anchor = GridBagConstraints.WEST;
//
LineComponent line = new LineComponent(0, 20, 200, 20, Color.WHITE); //fx,fy,tx,ty
line.setStroke(new BasicStroke(3f));
GridBagConstraints c6 = new GridBagConstraints();
c6.gridx = 0;
c6.gridy = 4;
c6.gridwidth = 10;
c6.anchor = GridBagConstraints.WEST;
//
picLabel = new JLabel("�Ϲ��W�j:");
picLabel.setBackground(colorRGB);
GridBagConstraints c7 = new GridBagConstraints();
c7.gridx = 0;
c7.gridy = 5;
c7.anchor = GridBagConstraints.WEST;
//
reverseColor = new JRadioButton("Reverse Color");
reverseColor.setBackground(colorRGB);
GridBagConstraints c8 = new GridBagConstraints();
c8.gridx = 0;
c8.gridy = 6;
c8.anchor = GridBagConstraints.WEST;
//
reset = new JRadioButton("�^�_");
reset.setBackground(colorRGB);
GridBagConstraints c9 = new GridBagConstraints();
c9.gridx = 0;
c9.gridy = 7;
c9.anchor = GridBagConstraints.WEST;
//
picMode = new JLabel("�Ҧ�");
picMode.setBackground(colorRGB);
GridBagConstraints c10 = new GridBagConstraints();
c10.gridx = 0;
c10.gridy = 8;
c10.anchor = GridBagConstraints.WEST;
//
modeSelect = new JComboBox(mode);
modeSelect.setSelectedIndex(0);
GridBagConstraints c11 = new GridBagConstraints();
c11.gridx = 0;
c11.gridy = 8;
c11.anchor = GridBagConstraints.EAST;
//
Light = new JLabel("��G��:");
Light.setBackground(colorRGB);
GridBagConstraints c12 = new GridBagConstraints();
c12.gridx = 0;
c12.gridy = 9;
c12.anchor = GridBagConstraints.WEST;
//
light = new JSlider(-255,255,0);
light.setBackground(colorRGB);
GridBagConstraints c13 = new GridBagConstraints();
c13.gridx = 0;
c13.gridy = 10;
c13.anchor = GridBagConstraints.WEST;
//
lightText = new JTextField(10);
lightText.setText("0");
GridBagConstraints c14 = new GridBagConstraints();
c14.gridx = 0;
c14.gridy = 11;
c14.gridwidth = 3;
c14.anchor = GridBagConstraints.WEST;
//
Constract = new JLabel("����");
Constract.setBackground(colorRGB);
GridBagConstraints c15 = new GridBagConstraints();
c15.gridx = 0;
c15.gridy = 12;
c15.anchor = GridBagConstraints.WEST;
//
contract = new JSlider(-100,100,0);
contract.setBackground(colorRGB);
GridBagConstraints c16 = new GridBagConstraints();
c16.gridx = 0;
c16.gridy = 13;
c16.anchor = GridBagConstraints.WEST;
//
contractText = new JTextField(10);
contractText.setText("0");
GridBagConstraints c17 = new GridBagConstraints();
c17.gridx = 0;
c17.gridy = 14;
c17.anchor = GridBagConstraints.WEST;
//
LineComponent line2 = new LineComponent(0, 20, 200, 20, Color.WHITE); //fx,fy,tx,ty
line2.setStroke(new BasicStroke(3f));
GridBagConstraints c18 = new GridBagConstraints();
c18.gridx = 0;
c18.gridy = 15;
c18.gridwidth = 5;
c18.anchor = GridBagConstraints.WEST;
//
sharpen = new JCheckBox("�y�U��");
sharpen.setBackground(colorRGB);
GridBagConstraints c19 = new GridBagConstraints();
c19.gridx = 0;
c19.gridy = 16;
c19.anchor = GridBagConstraints.WEST;
//
blur = new JCheckBox("�ҽk��");
blur.setBackground(colorRGB);
GridBagConstraints c20 = new GridBagConstraints();
c20.gridx = 0;
c20.gridy = 17;
c20.anchor = GridBagConstraints.WEST;
// �������������������� �H�W���ƪ� ��������������������
// ���������������� �H�U���ƥ�B�z ����������������
ImageHandler handler = new ImageHandler();
topDownRotate.addItemListener(handler);
leftRightRotate.addItemListener(handler);
reverseColor.addItemListener(handler);
reset.addItemListener(handler);
sharpen.addItemListener(handler);
blur.addItemListener(handler);
angleSelect.addItemListener(handler);
modeSelect.addItemListener(handler);
light.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
lightText.setText(String.valueOf(light.getValue()));
lloffset = Integer.parseInt(String.valueOf(light.getValue()))/1.0f;
controls = 1;
//flag = 1;
pp.removeAll();
if(yytest){
TBR.ImageVFlip(controli, controlj, controlk,controls, 1, lloffset, llscaleFactor, reFlag);
pp.add(new JLabel(new ImageIcon(TBR.getImage())));
}
pp.updateUI();
}
});
light.addKeyListener(new KeyAdapter(){
@Override
public void keyPressed(KeyEvent ke) {
String typed = lightText.getText();
light.setValue(0);
if(!typed.matches("\\d+") || typed.length() > 4) {
System.out.print("ho");
return;
}
int value = Integer.parseInt(typed);
light.setValue(value);
}
});
contract.addChangeListener(new ChangeListener(){
@Override
public void stateChanged(ChangeEvent e){
contractText.setText(String.valueOf(contract.getValue()));
llscaleFactor = Integer.parseInt(String.valueOf(contract.getValue()))/100.0f;
//flag = 0;
controls = 1;
pp.removeAll();
if(yytest){
TBR.ImageVFlip(controli, controlj, controlk,controls, 0, lloffset, llscaleFactor, reFlag);
pp.add(new JLabel(new ImageIcon(TBR.getImage())));
}
pp.updateUI();
//TBR.getPanel().updateUI();
}
});
contract.addKeyListener(new KeyAdapter(){
@Override
public void keyReleased(KeyEvent ke) {
String typed = contractText.getText();
contract.setValue(0);
if(!typed.matches("\\d+") || typed.length() > 3) {
return;
}
int value = Integer.parseInt(typed);
contract.setValue(value);
}
});
// �������������������� �H�W���ƥ�B�z ��������������������
//
bgroup.add(reverseColor);
bgroup.add(reset);
panel.add(label1,c1);
panel.add(angleLabel,c2);
panel.add(angleSelect,c3);
panel.add(topDownRotate,c4);
panel.add(leftRightRotate,c5);
panel.add(line,c6);
panel.add(picLabel,c7);
panel.add(reverseColor,c8);
panel.add(reset,c9);
panel.add(picMode,c10);
panel.add(modeSelect,c11);
panel.add(Light,c12);
panel.add(light,c13);
panel.add(lightText,c14);
panel.add(Constract,c15);
panel.add(contract,c16);
panel.add(contractText,c17);
panel.add(line2,c18);
panel.add(sharpen,c19);
panel.add(blur,c20);
//
//pp.add(BW.getPanel(),"9");
//panel.updateUI();
// frame.add(pp,BorderLayout.CENTER);
//
if(yytest){
TBR = new ImageVFlipDemo(bi);
//pp.add(TBR);
}
pp.updateUI();
//frame2.setLayout(new BorderLayout());
add(panel, BorderLayout.EAST);
//frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
} |
92570e7e-9025-4fd1-8134-ffe9e95d1aab | 0 | public void setValueMAC(byte[] value) {
this.valueMAC = value;
} |
947ce450-139a-4668-b160-06bf0165c09f | 9 | public void cargaArrayAlumno(String nroLegajo , String modo , String nroClase , String nroCurso){ // cargo en un array todos los registros de la tabla alumno.
String qry = "SELECT * FROM alumnos";
if (nroLegajo != null) qry += " WHERE nroLegajo = " + nroLegajo;
if(modo != null && nroClase != null && nroCurso != null){
if(modo == "asistencia"){
qry = "SELECT * FROM alumnos INNER JOIN asistencias ON alumnos.nroLegajo = asistencias.nroLegajo ";
qry+= "WHERE asistencias.nroClase = '"+nroClase+"' AND asistencias.nroCurso = '"+nroCurso+"';";
}
}
ResultSet rs = null;
this.arrayAlumnos.clear(); // borro el array para despues cargarlo denuevo .
this.posAlumnos = 0; //reseteo la posicion a 0 por si hay menos o mas alumnos
this.openDBConnection();
try {
rs = this.executeQuery(qry);
while (rs.next()) {
Alumno a = new Alumno();
a.setNroLegajo(rs.getString(1));
a.setNombre(rs.getString(2));
a.setApellido(rs.getString(3));
a.setFechaNacimiento(rs.getString(4));
a.setNroDoc(rs.getString(5));
a.setCalle(rs.getString(6));
a.setNroCalle(rs.getString(7));
a.setPiso(rs.getString(8));
a.setDepartamento(rs.getString(9));
a.setCodPostal(rs.getString(10));
a.setLocalidad(rs.getString(11));
a.setTelFijo(rs.getString(12));
a.setTelCel(rs.getString(13));
a.seteMail(rs.getString(14));
arrayAlumnos.add(a);
}
} catch (Exception ex) {
Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
}
try {
if (rs != null) {
rs.close();
}
} catch (Exception ex) {
Logger.getLogger(Modelo.class.getName()).log(Level.SEVERE, null, ex);
}
this.closeDBConnection();
} |
87124056-2d65-42fb-b619-1def9e32b85d | 7 | public AbstractProductIon(PrecursorIon precursorIon, ProductIonType type, int position, Peptide peptide, int charge) {
//based on DefaultPeptideIon create ProductIon.
super(peptide, charge);
if (precursorIon == null) {
throw new NullPointerException("Precursor ion can not set null!");
}
if (type == null) {
throw new NullPointerException("Product ion type can not set null!");
}
// absolute the charges of precursor ion and product ion.
int precursorZ = precursorIon.getCharge() > 0 ? precursorIon.getCharge() : precursorIon.getCharge() * -1;
int productZ = charge > 0 ? charge : charge * -1;
if (precursorZ <= 0) {
throw new IllegalArgumentException("precursor ion charge should not less than zero! " + precursorIon);
}
if (productZ > 3) {
throw new IllegalArgumentException("product ion change (" + productZ + ") should not great than 3!");
}
if (productZ > precursorZ) {
throw new IllegalArgumentException("product ion change (" + productZ + ") should not great than precursor ion (" + precursorZ + ")");
}
this.precursorIon = precursorIon;
this.type = type;
this.position = position;
} |
7a558f12-0b49-416e-81a0-28382b6661b8 | 2 | public static List<CommandeFournisseur> selectCommandeFournisseur() throws SQLException {
String query = null;
List<CommandeFournisseur> Commande = new ArrayList<CommandeFournisseur>();
ResultSet resultat;
try {
query = "SELECT * from COMMANDE_FOURNISSEUR ";
PreparedStatement pStatement = (PreparedStatement) ConnectionBDD.getInstance().getPreparedStatement(query);
resultat = pStatement.executeQuery(query);
while (resultat.next()) {
CommandeFournisseur CommandeFou = new CommandeFournisseur(resultat.getInt("ID_CMDFOUR"), resultat.getInt("ID_UTILISATEUR"), resultat.getString("COMFOUREF"), resultat.getDate("COMFOUDATE"), resultat.getFloat("COMFOUREMISE"));
Commande.add(CommandeFou);
}
} catch (SQLException ex) {
Logger.getLogger(RequetesCommandeFournisseur.class.getName()).log(Level.SEVERE, null, ex);
}
return Commande;
} |
dd8249a0-2fb2-4b96-b5f1-ff6fc99a6b72 | 8 | @SuppressWarnings("unchecked")
@Test
public void testQuestion2() {
Quiz quiz = Quiz.getQuizByQuizName("Bunny Quiz");
ArrayList<Question> questions = Question.getQuestionsByQuizID(quiz.quizID);
assertEquals(questions.size(), 7);
for (int i = 0; i < questions.size(); i++) {
Question question = questions.get(i);
assertEquals(question.position, i);
if (question instanceof ResponseQuestion) {
assertEquals(((ArrayList<String>)question.answer).get(0), "Leporidae");
String userAnswer1 = "Leporidae";
String userAnswer2 = "I don't know";
assertEquals(question.getScore(userAnswer1), 10, 1e-6);
assertEquals(question.getScore(userAnswer2), 0, 1e-6);
} else if (question instanceof FillInBlankQuestion) {
assertEquals(((ArrayList<String>)question.answer).get(0), "Watership");
String userAnswer1 = "Watership";
String userAnswer2 = "Watergate";
assertEquals(question.getScore(userAnswer1), 10, 1e-6);
assertEquals(question.getScore(userAnswer2), 0, 1e-6);
} else if (question instanceof MultipleChoiceQuestion) {
assertTrue(((String)question.answer).startsWith("In Stanford tradition"));
assertEquals(((ArrayList<String>)question.question).size()-1, 3);
String userAnswer1 = "In Stanford tradition, rubbing the nose of a rabbit guarantees an A on the CS108 class project";
String userAnswer2 = "Aztec mythology includes a rabbit pantheon.";
assertEquals(question.getScore(userAnswer1), 10, 1e-6);
assertEquals(question.getScore(userAnswer2), 0, 1e-6);
} else if (question instanceof PictureQuestion) {
assertEquals(((ArrayList<String>)question.answer).size(), 2);
assertTrue(((PictureQuestion)question).questionURL.endsWith("Bugs_Bunny_Pose.PNG"));
String userAnswer1 = "Bugs";
String userAnswer2 = "Bugs Bunny";
String userAnswer3 = "Computer";
assertEquals(question.getScore(userAnswer1), 10, 1e-6);
assertEquals(question.getScore(userAnswer2), 10, 1e-6);
assertEquals(question.getScore(userAnswer3), 0, 1e-6);
} else if (question instanceof MatchingQuestion) {
ArrayList<Integer> indices = ((MatchingQuestion) question).getCorrectChoiceIndexes();
assertEquals(indices.get(0).intValue(), 3);
assertEquals(indices.get(1).intValue(), 4);
assertEquals(indices.get(2).intValue(), 1);
assertEquals(indices.get(3).intValue(), 2);
String[] userAnswerArray1 = {"Bunny answer 1", "Bunny answer 2", "Bunny answer 4", "Bunny answer 3"};
String[] userAnswerArray2 = {"Bunny answer 3", "Bunny answer 2", "Bunny answer 4", "Bunny answer 1"};
String[] userAnswerArray3 = {"Bunny answer 2", "Bunny answer 3", "Bunny answer 1"};
assertEquals(question.getScore(ArrayToList(userAnswerArray1)), 6, 1e-6);
assertEquals(question.getScore(ArrayToList(userAnswerArray2)), 3, 1e-6);
assertEquals(question.getScore(ArrayToList(userAnswerArray3)), 0, 1e-6);
} else if (question instanceof MultiAnswerQuestion) {
assertEquals(((MultiAnswerQuestion)question).answerNumber, 3);
assertEquals(((ArrayList<String>)question.answer).size(), 4);
String[] userAnswerArray1 = {"B", "C", "D"};
String[] userAnswerArray2 = {"U", "Y", "N"};
String[] userAnswerArray3 = {"B", "U", "Y"};
assertEquals(question.getScore(ArrayToList(userAnswerArray1)), 5.0/3, 1e-6);
assertEquals(question.getScore(ArrayToList(userAnswerArray2)), 5, 1e-6);
assertEquals(question.getScore(ArrayToList(userAnswerArray3)), 5, 1e-6);
} else if (question instanceof MultiChoiceMultiAnswerQuestion) {
assertEquals(((ArrayList<String>)question.question).size(), 6);
assertEquals(((ArrayList<String>)question.answer).size(), 2);
String[] userAnswerArray1 = {"This is a correct answer about Bunny.", "This is another correct answer about Bunny."};
String[] userAnswerArray2 = {"This is a correct answer about Bunny.", "This is another correct answer about Bunny.", "This is a wrong answer about Bunny."};
String[] userAnswerArray3 = {"This is a correct answer about Bunny.", "This is a third wrong answer about Bunny."};
assertEquals(question.getScore(ArrayToList(userAnswerArray1)), 15, 1e-6);
assertEquals(question.getScore(ArrayToList(userAnswerArray2)), 12, 1e-6);
assertEquals(question.getScore(ArrayToList(userAnswerArray3)), 9, 1e-6);
} else {
assertTrue(false);
}
}
quiz = Quiz.getQuizByQuizName("Cities");
questions = Question.getQuestionsByQuizID(quiz.quizID);
assertEquals(questions.size(), 6);
} |
778e54bf-8276-420b-ba9c-d9f72fd0726a | 9 | public void load() throws IOException {
boolean before = SoundStore.get().isDeferredLoading();
SoundStore.get().setDeferredLoading(false);
if (in != null) {
switch (type) {
case OGG:
target = SoundStore.get().getOgg(in);
break;
case WAV:
target = SoundStore.get().getWAV(in);
break;
case MOD:
target = SoundStore.get().getMOD(in);
break;
case AIF:
target = SoundStore.get().getAIF(in);
break;
default:
Log.error("Unrecognised sound type: "+type);
break;
}
} else {
switch (type) {
case OGG:
target = SoundStore.get().getOgg(ref);
break;
case WAV:
target = SoundStore.get().getWAV(ref);
break;
case MOD:
target = SoundStore.get().getMOD(ref);
break;
case AIF:
target = SoundStore.get().getAIF(ref);
break;
default:
Log.error("Unrecognised sound type: "+type);
break;
}
}
SoundStore.get().setDeferredLoading(before);
} |
7718b254-5939-427b-b23c-990853ecac50 | 6 | public void moverContinuamente() {
while(!gameOver) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {}
if(panel.x + panel.diametro > panel.getWidth() ||
panel.x < 0) {
incX *= -1;
}
if(panel.y + panel.diametro > panel.getHeight() ||
panel.y < 0) {
incY *= -1;
}
panel.x += incX;
panel.y += incY;
panel.repaint();
}
} |
a4dccfc4-5b4c-4ea5-82fe-e500146ce12a | 8 | public ArrayList<String> tokenize(String text) {
char[] textContent = text.toCharArray();
ArrayList<String> tokens = new ArrayList<String>();
// Initialize the execution
int begin = -1;
transducer.reset();
String word;
// Run over the chars
for(int i=0 ; i<textContent.length ; i++) {
Signal s = transducer.feedChar( textContent[i] );
switch(s) {
case start_word:
begin = i;
break;
case end_word:
word = text.substring(begin, i);
this.addToken(tokens, word);
begin = -1;
break;
case end_word_prev:
word = text.substring(begin, i-1);
this.addToken(tokens, word);
break;
case switch_word:
word = text.substring(begin, i);
this.addToken(tokens, word);
begin = i;
break;
case switch_word_prev:
word = text.substring(begin, i-1);
this.addToken(tokens, word);
begin = i;
break;
case cancel_word:
begin = -1;
break;
}
}
// Add the last one
if (begin != -1) {
word = text.substring(begin, text.length());
this.addToken(tokens, word);
}
return tokens;
} |
d7a1765a-8b96-4442-a081-e12bf08ca06a | 5 | private void createDataset() {
this.gson = new Gson();
Map<?, ?> all = this.transitionsStore.getAll();
Collection<String> allTransitions = (Collection<String>) all.values();
for (String transitionString : allTransitions) {
if(isPending(transitionString) | isACKED(transitionString)){
Object deserialized = deserialize(transitionString);
if(deserialized instanceof Transition) {
this.dataset.put(((Transition) deserialized).getTransitionId(), (Transition) deserialized);
}
}
}
} |
1b4db9e4-281d-4e3e-8f33-7db12307844b | 3 | public static void checkedAnyAttributes(Element element, String[] labels) throws SyntaxException {
for (String label : labels)
if (element.hasAttribute(label))
return;
StringBuilder labelList = new StringBuilder();
for (String label : labels)
labelList.append(label).append(", ");
String labelsAsList = labelList.toString();
labelsAsList = labelsAsList.substring(0, labelsAsList.length() - 2);
throw new SyntaxException(String.format("Tag %s missing at least one of any attribute: %s.",
element.getNodeName(), labelsAsList));
} |
c7c13d10-0ea9-478b-8c74-3d9d58a29ad4 | 2 | @Override
public void add(Credit element) {
//Добавляем запись в список
getList().add(element);
Statement statement = null;
ResultSet result = null;
try {
//Создаем изменяемую выборку
statement = getConnection().createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
//Получаем набор данных
result = statement.executeQuery(allQuery);
//Позиционируемся на добавление новой записи
result.moveToInsertRow();
//Заполняем поля
//Преобразуем обычную дату в формат sql
result.updateDate("CREDITDATE", new java.sql.Date(element.getDate().getTime()));
result.updateDouble("CREDITSUM", element.getSum());
result.updateInt("CREDITSTATUS", element.getStatus());
result.updateInt("CLIENTSID", element.getClientId());
result.updateInt("CREDITPROGRAMID", element.getCreditProgramId());
//Фиксируем изменения
result.insertRow();
} catch (SQLException ex) {
System.out.println("Ошибка при изменении таблицы");
} finally {
try {
//Закрываем открытые соединения
statement.close();
result.close();
} catch (SQLException ex) {
System.out.println("Ошибка при закрытии соединения");
}
}
} |
a6a70f99-b932-4be4-8ccb-15752170da59 | 2 | public static boolean fullName(String name){
String[] temp = name.split(" ");
if(name(temp[0])&&name(temp[1]))
return true;
return false;
} |
eb9496a4-3eef-448d-ad6b-d227c68c4b2b | 3 | public static void choque() {
if (terminochoque){
terminochoque = false;
file = new File(".");
ruta = file.getAbsolutePath();
Thread hilo = new Thread() {
@Override
public void run() {
try {
Thread.sleep(1);
FileInputStream fis;
Player player;
try{
fis = new FileInputStream(ruta + "/src/sounds/choque.mp3");
}catch(FileNotFoundException e){
fis = new FileInputStream(ruta + "/complementos/choque.mp3");
}
BufferedInputStream bis = new BufferedInputStream(fis);
player = new Player(bis);
player.play();
stop();
} catch (InterruptedException | JavaLayerException | FileNotFoundException e) {
}
}
};
hilo.start();
}
} |
29825160-a0b1-40f6-9671-0a40ae48b34f | 2 | public boolean retrack(Tracking tracking)
throws AftershipAPIException,IOException,ParseException,JSONException{
String paramRequiredFields = tracking.getQueryRequiredFields().replaceFirst("&","?");
String url = "/trackings/"+tracking.getSlug()+
"/"+tracking.getTrackingNumber()+"/retrack"+paramRequiredFields;
JSONObject response = this.request("POST","/trackings/"+tracking.getSlug()+
"/"+tracking.getTrackingNumber()+"/retrack"+paramRequiredFields,null);
if (response.getJSONObject("meta").getInt("code")==200) {
if (response.getJSONObject("data").getJSONObject("tracking").getBoolean("active")) {
return true;
}else {
return false;
}
}else {
return false;
}
} |
738cd1d6-ef80-4c11-a645-1b44954ba9d7 | 9 | public float cost(ArrayList<Pair> permutation, int[] container_classes, int[][] communication_matrix) {
//initially consider all nodes to be powered up (then reduced it on encountering [-1,-1]
num_of_powered_nodes = permutation.size();
num_of_collocated_devils = 0;
num_of_collocated_comms = 0;
//assumption : number of processes OR length of permutation is even
//assumption : number of cores per processor is 2
for (int i = 0; i < permutation.size(); i++) {
if (permutation.get(i).first == -1 || permutation.get(i).second == -1) {
if (permutation.get(i).first == -1 && permutation.get(i).second == -1)
num_of_powered_nodes--;
} else {
if (container_classes[permutation.get(i).first] == 1 && container_classes[permutation.get(i).first] == container_classes[permutation.get(i).second]) {
num_of_collocated_devils++;
}
//the communication matrix might not be symmetric.
//Hence, we need different operators
if (communication_matrix[permutation.get(i).first][permutation.get(i).second] == 1 ||
communication_matrix[permutation.get(i).second][permutation.get(i).first] == 1) {
num_of_collocated_comms++;
}
}
}
float weighted_sum = p*num_of_powered_nodes + d*num_of_collocated_devils - c*num_of_collocated_comms;
return weighted_sum;
} |
2ae0a262-3a86-4051-ada1-9a40f29d30a4 | 0 | public synchronized static ConfigManager getInstance() {
return m_instance;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.