text
stringlengths
14
410k
label
int32
0
9
@Override public boolean update(Particulier x) { Statement stm = null; try { String req = "UPDATE particulier SET \n" + "email=\""+x.getEmail()+"\",\n" + "motdepasse=\""+x.getMotDePasse()+"\",\n" + "nom=\""+x.getNom()+"\",\n" + "prenom=\""+x.getPrenom()+"\",\n" + "titre=\""+x.getTitre()+"\",\n" + "adresse=\""+x.getAdresse()+"\"\n" + "WHERE particulierid="+x.getParticulierId()+"\n" + //Les conditions suivantes empechent la requète de donner un email qui serait déjà utilisé par un autre membre (hotelier ou particulier) //Notez que MySQL ne permet pas de selectionner directement la table que l'on modifie pendant un update //c'est pourquoi les selections ont un niveau de profondeur additionnel. "and not exists ( select * from (select * from hotelier \n" + " where email = \""+x.getEmail()+"\"\n" + " )temphotelier)\n" + "and not exists ( select * from (select * from particulier \n" + " where email = \""+x.getEmail()+"\"\n" + " and particulierid<>"+x.getParticulierId()+"\n" + " )tempparticulier)"; if (cnx.createStatement().executeUpdate(req)>0) { return true; } } catch (SQLException exp) { } finally { if (stm!=null) try { stm.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return false; }
4
public void level() { level++; System.out.println("You are now level " + level + "!"); String choice = ""; while (!choice.equals("intelligence") && !choice.equals("strength")) { System.out.println("Increase intelligence or strength: "); choice = input.next().toLowerCase(); } System.out.println("Pick a new ability."); if (choice.equals("intelligence")) { printList(masterSpell); spell.add(masterSpell.get(input.nextInt() - 1)); intelligence++; healthMax += 10; healthCurrent = healthMax; } else { printList(masterMelee); melee.add(masterMelee.get(input.nextInt() - 1)); strength++; healthMax += 20; healthCurrent = healthMax; } }
3
private double calculateWavedX(double x1, double x2, double x3, double f1, double f2, double f3) throws ArithmeticException{ double r23 = Math.pow(x2, 2) - Math.pow(x3, 2), r31 = Math.pow(x3, 2) - Math.pow(x1, 2), r12 = Math.pow(x1, 2) - Math.pow(x2, 2), s23 = x2 - x3, s31 = x3 - x1, s12 = x1 - x2; // returns 0.5 * (beta) / (alpha) double beta = f1 * r23 + f2 * r31 + f3 * r12, alpha = f1 * s23 + f2 * s31 + f3 * s12; if (alpha != 0) { return 0.5 * (beta) / (alpha); } else { throw new ArithmeticException("ERROR: Divide by null by calculating waved point"); } }
1
@Override public DataTable generateDataTable (Query query, HttpServletRequest request) throws DataSourceException { DataTable dataTable = null; try (final Reader reader = new FilterCsv (new BufferedReader (new InputStreamReader (new URL (this.urlYahoo).openStream())))) { TableRow row = new TableRow (); dataTable = CsvDataSourceHelper.read(reader, this.column, false); for (int i = 0; i < dataTable.getNumberOfRows(); i++) { String lastPriceDataTable = dataTable.getCell(i, 0).toString(); String changePercentDataTable = dataTable.getCell(i, 1).toString(); if (! lastPriceDataTable.matches(".*\\d.*")) lastPriceDataTable = "0"; if (! changePercentDataTable.matches(".*\\d.*")) changePercentDataTable = "0"; String lastPriceString = this.formatter.format(Double.parseDouble(lastPriceDataTable)); String changePercentString = this.formatter.format(Double.parseDouble(changePercentDataTable)); row.addCell(lastPriceString + " (" + changePercentString + "%)"); } dataTable.addRow(row); } catch (MalformedURLException e) { System.out.println("TableIndiceAsia generateDataTable() MalformedURLException " + "URL : " + this.urlYahoo + " " + e); } catch (IOException e) { System.out.println("TableIndiceAsia generateDataTable() IOException " + e); } return dataTable; }
5
static public void main(String args[]) { String[] argv; long start = System.currentTimeMillis(); int argc = args.length + 1; argv = new String[argc]; argv[0] = "jlc"; for(int i=0;i<args.length;i++) argv[i+1] = args[i]; jlcArgs ma = new jlcArgs(); if (!ma.processArgs(argv)) System.exit(1); Converter conv = new Converter(); int detail = (ma.verbose_mode ? ma.verbose_level : Converter.PrintWriterProgressListener.NO_DETAIL); Converter.ProgressListener listener = new Converter.PrintWriterProgressListener( new PrintWriter(System.out, true), detail); try { conv.convert(ma.filename, ma.output_filename, listener); } catch (JavaLayerException ex) { System.err.println("Convertion failure: "+ex); } System.exit(0); }
4
private static ClassSignature parseSig(String sig) throws BadBytecode, IndexOutOfBoundsException { Cursor cur = new Cursor(); TypeParameter[] tp = parseTypeParams(sig, cur); ClassType superClass = parseClassType(sig, cur); int sigLen = sig.length(); ArrayList ifArray = new ArrayList(); while (cur.position < sigLen && sig.charAt(cur.position) == 'L') ifArray.add(parseClassType(sig, cur)); ClassType[] ifs = (ClassType[])ifArray.toArray(new ClassType[ifArray.size()]); return new ClassSignature(tp, superClass, ifs); }
2
private boolean r_perfective_gerund() { int among_var; int v_1; // (, line 71 // [, line 72 ket = cursor; // substring, line 72 among_var = find_among_b(a_0, 9); if (among_var == 0) { return false; } // ], line 72 bra = cursor; switch(among_var) { case 0: return false; case 1: // (, line 76 // or, line 76 lab0: do { v_1 = limit - cursor; lab1: do { // literal, line 76 if (!(eq_s_b(1, "\u0430"))) { break lab1; } break lab0; } while (false); cursor = limit - v_1; // literal, line 76 if (!(eq_s_b(1, "\u044F"))) { return false; } } while (false); // delete, line 76 slice_del(); break; case 2: // (, line 83 // delete, line 83 slice_del(); break; } return true; }
8
public void generate(){ }
0
@SuppressWarnings("StringConcatenationMissingWhitespace") private void writeObjectToStream(Object obj, Types t, String name, DataOutputStream os) throws IOException { //Write Name os.writeUTF(name); //Write Type os.writeInt(t.ordinal()); //Write Value switch(t) { case OBJECT_ARRAY: case ISAVEABLE: { ISaveAble is = (ISaveAble) obj; FileWriter fw = new FileWriter(); is.writeToFileWriter(fw); fw.writeToStream(os); break; } default: { os.writeUTF(String.valueOf(obj)); break; } } }
2
public static void Edmonds(Graph input) { input.setState(States.ARR_ADJ); Log.print(Log.system, "Edmonds algorithm:"); // init... n = input.getVertexCount(); used = new boolean[n]; blossom = new boolean[n]; mt = new int[n]; p = new int[n]; q = new int[n]; base = new int[n]; Arrays.fill(mt, -1); for (int i = 0; i < n; i++) { if (mt[i] == -1) { int v = findPath(input, i); while (v != -1) { int pv = p[v]; int ppv = mt[pv]; mt[v] = pv; mt[pv] = v; v = ppv; } } } for (int i = 0; i < n; i++) if (mt[i] != -1) if (mt[i] > i) System.out.println((mt[i] + 1) + " " + (i + 1)); }
6
public void createMaze(String filePath) { try { reader = new BufferedReader(new FileReader(filePath)); int i = 0; while ((line = reader.readLine()) != null) { parts = line.split("\\s"); for (int j = 0; j < MicromouseRun.BOARD_MAX; j++) { mazeMap[i][j] = Integer.parseInt(parts[j].trim(), RAD); } i++; } } catch (FileNotFoundException e) { System.out.println("File not found. Try again."); } catch (IOException e) { System.out.println("Oh No! Read error :("); } catch (Exception e) { System.out.println("Some other error occurred..."); } }
5
public BubbleSorter() { // TODO Auto-generated constructor stub }
0
public JPanel getBrandingMenu() { if (!isInitialized()) { IllegalStateException e = new IllegalStateException("Call init first!"); throw e; } return this.brandingMenu; }
1
public ComparisonResult findGenes(Chromosome other) { ComparisonResult comparisonResult = new ComparisonResult(); // знаю имя координаты нужного гена, найти нужный домен comparisonResult.sizeGenes = other.intervals.size(); System.out.println(other.intervals.size()); for (Interval domain: intervals) { for (Interval currentGene: other.intervals) { for (Interval otherGene: other.intervals) { if (domain.isInsideDomain(otherGene) && domain.isInsideDomain(currentGene) && !otherGene.name.equals(currentGene.name)) { comparisonResult.pairs ++; if (!comparisonResult.coupleGenes.containsKey(domain)) { comparisonResult.coupleGenes.put(domain, new ArrayList<String>()); comparisonResult.coupleGenes.get(domain).add(currentGene.name); } else if (!comparisonResult.coupleGenes.get(domain).contains(currentGene.name)) comparisonResult.coupleGenes.get(domain).add(currentGene.name); // else if (!comparisonResult.coupleGenes.get(currentGene.name).contains(otherGene.name) && !currentGene.name.equals(otherGene.name)) // comparisonResult.coupleGenes.get(currentGene.name).add(otherGene.name); } } } } // for (Interval interval : intervals) { // ArrayList<String> coordinatesDomainInside = new ArrayList<String>(); //contains two field start end // ArrayList<String> coordinatesDomainOnRight = new ArrayList<String>(); // ArrayList<String> coordinatesDomainOnLeft = new ArrayList<String>(); // for (Interval intervalDomain : other.intervals) { // if (interval.isInsideGene(intervalDomain)) { // coordinatesDomainInside.add(Integer.toString(intervalDomain.a)); // coordinatesDomainInside.add(Integer.toString(intervalDomain.b)); // comparisonResult.informationAboutGenesInside.put(interval, coordinatesDomainInside); // } else if (intervalDomain.isRightBorder(interval)) { // coordinatesDomainOnRight.add(Integer.toString(intervalDomain.a)); // coordinatesDomainOnRight.add(Integer.toString(intervalDomain.b)); // comparisonResult.informationAboutGenesRight.put(interval, coordinatesDomainOnRight); // } else if (intervalDomain.isLeftBorder(interval)) { // coordinatesDomainOnLeft.add(Integer.toString(intervalDomain.a)); // coordinatesDomainOnLeft.add(Integer.toString(intervalDomain.b)); // comparisonResult.informationAboutGenesLeft.put(interval, coordinatesDomainOnLeft); // } // } // } return comparisonResult; }
8
@SuppressWarnings("CallToThreadDumpStack") private ArrayList<FieldCandidate> split_line(ArrayList<FieldCandidate> candidates, int start, int maxFields) { ArrayList<FieldCandidate> selectedCandidates = new ArrayList<>(); try { for (int posList = start; posList < candidates.size(); posList++) { FieldCandidate candidate = candidates.get(posList); boolean mustAdd = true; for (int i = 0; i < selectedCandidates.size(); i++) { FieldCandidate selectedCandidate = selectedCandidates.get(i); if (hasIntersection(candidate, selectedCandidate)) { mustAdd = false; break; } } if (mustAdd) { if (maxFields != Integer.MAX_VALUE) { ArrayList<FieldCandidate> selectedCandidates2 = split_line(candidates, posList + 1, Integer.MAX_VALUE); if (selectedCandidates.size() + selectedCandidates2.size() < maxFields) { selectedCandidates.add(candidates.get(posList)); } } else { selectedCandidates.add(candidates.get(posList)); } } } //Call the Garbage Collector System.gc(); } catch (Exception error) { /** * Show the StackTrace error [for debug] */ error.printStackTrace(); // System.out.println("Exception: " + error); } return selectedCandidates; }
7
private void startGame() { Timer.getInstance().start(); SoundManager.getInstance().playStartSound(); }
0
public static List<ClienteDTO> convertToDTOList(List<Cliente> lsClientes){ if(lsClientes == null){ return new ArrayList<ClienteDTO>(); } List<ClienteDTO> lsClientesDTO = new ArrayList<ClienteDTO>(); for(Cliente cliente : lsClientes){ lsClientesDTO.add(convertToClienteDTO(cliente)); } return lsClientesDTO; }
2
public void setSkill(int skill, String name, int value, int cost, String description) { assert numOfSkills > skill; this.skillNames[skill] = name; this.skillValues[skill] = value; this.skillCosts[skill] = cost; this.skillDescriptions[skill] = description; }
0
@Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((firstName == null) ? 0 : firstName.hashCode()); result = PRIME * result + ((id == null) ? 0 : id.hashCode()); result = PRIME * result + ((lastName == null) ? 0 : lastName.hashCode()); return result; }
3
public String tileIDToStr(int tileid) { if (tileid==0) return ""; StringBuffer tilestr = new StringBuffer(""+(char)(tileid&255)); if (tileid >= 0x100) tilestr.append( (char)((tileid/0x100)&255)); if (tileid >= 0x10000) tilestr.append( (char)((tileid/0x10000)&255)); if (tileid>=0x1000000) tilestr.append( (char)((tileid/0x1000000)&255)); return tilestr.toString(); }
4
public List<Interval> merge(List<Interval> intervals) { if (intervals == null || intervals.size() < 2) return intervals; // First need to sort all the intervals based on the start time. // Sort with comparable. Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval i1, Interval i2) { if (i1.start < i2.start) return -1; else if (i1.start == i2.start) return 0; else return 1; } }); // Then for each interval [s1, e1], check if the next interval [s2, e2] can be merged or not. // 1) if e1 >= e2, merge the next interval, current interval unchanged. // 2) else if s2 <= e1 && e2 > e1, current interval = [s1, e2] // 3) else if s2 > e1, add current interval to result, move current interval to the next interval. Interval curr = new Interval(intervals.get(0).start, intervals.get(0).end); List<Interval> result = new ArrayList<Interval>(); for (int i = 1; i < intervals.size(); i++) { Interval next = intervals.get(i); if (curr.end >= next.end) { // no need to do anything. } else if (curr.end >= next.start && curr.end < next.end) { curr.end = next.end; } else if (curr.end < next.start) { result.add(curr); curr = new Interval(next.start, next.end); } } result.add(curr); return result; }
9
public int maxProfit(int[] prices) { int length = prices.length; if(length == 0) return 0; int[] history = new int[length]; int[] furture = new int[length]; int maxProfit=0; int valley = prices[0]; int peak = prices[length-1]; for(int i =0 ; i< length;i++){ valley = Math.min(valley,prices[i]); if(i>0) history[i] = Math.max(history[i-1],prices[i]-valley); } for (int i =length-1;i > 0 ; i--) { peak = Math.max(peak,prices[i]); if(i<length-1) furture[i] = Math.max(furture[i+1],peak- prices[i]); maxProfit = Math.max(maxProfit,furture[i] + history[i]); } return maxProfit; }
5
public LockEventListener(LockManager manager){ this.manager = manager; }
0
private java.util.ArrayList<Binding> getBindings(String PortBinding){ NodeList Definitions, ChildNodes; NamedNodeMap attr; String BindingName, BindingType, BindingStyle, BindingTransport; Binding Binding = null; java.util.ArrayList<Binding> arrBindings = null; int BindingCount = -1; //Loop through definitions Definitions = getDefinitions(); //Definitions = Definitions.item(0).getChildNodes(); for (int i=0; i<Definitions.getLength(); i++ ) { if (contains(Definitions.item(i).getNodeName(), "binding")) { //Get Binding Name attr = Definitions.item(i).getAttributes(); BindingName = DOM.getAttributeValue(attr, "name"); BindingType = DOM.getAttributeValue(attr, "type"); if (BindingName.equals(PortBinding)){ arrBindings = new java.util.ArrayList<Binding>(); //Get Binding Transport/Style BindingStyle = BindingTransport = ""; ChildNodes = Definitions.item(i).getChildNodes(); for (int j=0; j<ChildNodes.getLength(); j++ ) { if (contains(ChildNodes.item(j).getNodeName(), "binding")) { attr = ChildNodes.item(j).getAttributes(); BindingStyle = DOM.getAttributeValue(attr, "style"); BindingTransport = DOM.getAttributeValue(attr, "transport"); } } //Get Operation Names/Soap Action for (int j=0; j<ChildNodes.getLength(); j++ ) { if (contains(ChildNodes.item(j).getNodeName(), "operation")) { Binding = new Binding(); BindingCount +=1; attr = ChildNodes.item(j).getAttributes(); Binding.Operation = DOM.getAttributeValue(attr, "name"); NodeList Operations = ChildNodes.item(j).getChildNodes(); for (int k=0; k<Operations.getLength(); k++ ) { if (contains(Operations.item(k).getNodeName(), "operation")) { attr = Operations.item(k).getAttributes(); Binding.SoapAction = DOM.getAttributeValue(attr, "soapaction"); Binding.Style = BindingStyle; //DOM.getAttributeValue(attr, "style"); Binding.Name = BindingName; Binding.Type = stripNameSpace(BindingType); } } arrBindings.add(Binding); } } return arrBindings; } } } return null; }
9
public static boolean Refill(PatientProfilePage pProfileP) { prescIDL=new JLabel("Prescription ID"); prescID = new JTextField(10); MyPanel = new JPanel(); MyPanel.add(prescIDL); MyPanel.add(prescID); int n = JOptionPane.showConfirmDialog( null,MyPanel, "Refill Prescription", JOptionPane.YES_NO_OPTION); if (n == JOptionPane.YES_OPTION) { return true; } else { return false; } }
1
@Override public JTable search(String searchTerm) { displaysearch = new String[result.length][result.length]; int n = 0; for(int i = 0; i < result.length; i++){ for(int j = 0; j < result[i].length; j++){ if((result[i][j].toLowerCase()).contains(searchTerm)){ displaysearch[n]= result[i]; n++; } } } String[][] small_displaysearch = new String[n][8]; for(int i = 0; i < small_displaysearch.length; i++){ for(int k = 0; k< small_displaysearch[i].length; k++){ small_displaysearch[i][k] = displaysearch[i][k]; } } System.out.println(small_displaysearch.length); Object rowSchedule[][] = small_displaysearch; Object columnTitle[] = result[0]; JTable table = new JTable(rowSchedule, columnTitle); return table; }
5
protected static boolean buscarPalabraDescripcion(String buscar){ boolean aux=false; //buca en cada linea del fichero si en la "casilla " descripcion hay la cadena que se esta buscando //si encuentra alguna coincidencia imprimira toda la linea try{ BufferedReader stdin=Files.newBufferedReader(path,java.nio.charset.StandardCharsets.UTF_8); String linea=""; while((linea=stdin.readLine())!=null){ String [] part=linea.split(";"); if(part[1].contains(buscar)){//encontar si hay coincidencia en el campo desc System.out.println(part[0]+" "+part[1]+" "+part[2]+" "+part[3]); aux=true; }else{ //no fa res } } }catch(IOException e){ System.out.println("Error en leer el fichero "+e); } return aux; }
3
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = "", data[]; StringBuilder out = new StringBuilder(); while ((line = in.readLine()) != null && line.length() != 0) { int test = Integer.parseInt(line.trim()); String name; for (int i = 0; i < test; i++) { data = in.readLine().trim().split(" "); name = data[0]; rows = Integer.parseInt(data[1].trim()); cols = Integer.parseInt(data[2].trim()); m = new int[rows][cols]; min = new int[rows][cols]; for (int j = 0; j < m.length; j++) m[j] = retInts(in.readLine()); int max = 0; for (int r = 0; r < m.length; r++) for (int c = 0; c < cols; c++) { if(min[r][c]==0) cal(r, c, 0); max = Math.max(max, min[r][c]); } out.append(name+": "+max+"\n"); } } System.out.print(out); }
7
private boolean checkColumns(Player player) { boolean isWinner = false; if ((board[0][0].equals(player.getMark()) && board[0][1].equals(player.getMark()) && board[0][2].equals(player.getMark()))) { winnerCombination[0] = "0 0"; winnerCombination[1] = "0 1"; winnerCombination[2] = "0 2"; isWinner = true; } else if ((board[1][0].equals(player.getMark()) && board[1][1].equals(player.getMark()) && board[1][2].equals(player.getMark()))) { winnerCombination[0] = "1 0"; winnerCombination[1] = "1 1"; winnerCombination[2] = "1 2"; isWinner = true; } else if ((board[2][0].equals(player.getMark()) && board[2][1].equals(player.getMark()) && board[2][2].equals(player.getMark()))) { winnerCombination[0] = "2 0"; winnerCombination[1] = "2 1"; winnerCombination[2] = "2 2"; isWinner = true; } return isWinner; }
9
public int candy(int[] ratings) { assert (ratings != null) : "Please input ratings!"; int len = ratings.length; if (len == 0 || len == 1) return len; int[] dp = new int[len]; // left -> right for (int i = 1; i < len; i++) { if (ratings[i] > ratings[i - 1]) { dp[i] = dp[i - 1] + 1; } } // right -> left for (int i = len - 2; i >= 0; i--) { if (ratings[i] > ratings[i + 1] && dp[i] < dp[i + 1] + 1) { dp[i] = dp[i + 1] + 1; } } int result = len; for (int i = 0; i < dp.length; i++) { result += dp[i]; } return result; }
8
public int numDecodings(String s) { if (s == null || s.length() == 0) { return 0; } int[] nums = new int[s.length() + 1]; nums[0] = 1; nums[1] = s.charAt(0) != '0' ? 1 : 0; for (int i = 2; i <= s.length(); i++) { if (s.charAt(i - 1) != '0') { nums[i] = nums[i - 1]; } int twoDigits = (s.charAt(i - 2) - '0') * 10 + s.charAt(i - 1) - '0'; if (twoDigits >= 10 && twoDigits <= 26) { nums[i] += nums[i - 2]; } } return nums[s.length()]; }
7
@SuppressWarnings("unchecked") private void parseQuery(String query, Map<String, Object> parameters) throws UnsupportedEncodingException { if (query != null) { String pairs[] = query.split("[&]"); for (String pair : pairs) { String param[] = pair.split("[=]"); String key = null; String value = null; if (param.length > 0) { key = URLDecoder.decode(param[0], System.getProperty("file.encoding")); } if (param.length > 1) { value = URLDecoder.decode(param[1], System.getProperty("file.encoding")); } if (parameters.containsKey(key)) { Object obj = parameters.get(key); if (obj instanceof List<?>) { List<String> values = (List<String>) obj; values.add(value); } else if (obj instanceof String) { List<String> values = new ArrayList<String>(); values.add((String) obj); values.add(value); parameters.put(key, values); } } else { parameters.put(key, value); } } } }
8
public int largestRectangleArea(int[] height) { if (height.length == 0) return 0; int max = 0; int[] f,g; f= new int[height.length]; g= new int[height.length]; f[0] = -1; g[height.length-1] = height.length; for (int i = 1;i< height.length;i++) { int j = i-1; while ( j >= 0 && height[j] >= height[i]) j = f[j]; f[i] = j; } for (int i = height.length -2; i >= 0; i--) { int k = i+1; while ( k < height.length && height[k] >= height[i]) k =g[k]; g[i] = k; } for (int i =0 ; i< height.length;i++) { if ((g[i] - f[i] -1) * height[i] > max) max =(g[i] - f[i] -1) * height[i]; } return max; }
9
public void updatePosition() { if (xPos < xDestination) xPos++; else if (xPos > xDestination) xPos--; if (yPos < yDestination) yPos++; else if (yPos > yDestination) yPos--; if (xPos == xDestination && yPos == yDestination && isMoving==true) { if (stayAtBreak) { DoMoveToPosition(breakLocation); } else { DoMoveToPosition(homeBase); } waiter.msgAtTable(); isMoving=false; } }
8
public static void main(String[] args) { Display display = Display.getDefault(); Shell shlCmss = new Shell(); shlCmss.setSize(562, 236); shlCmss.setText("CMSS"); Group group = new Group(shlCmss, SWT.NONE); group.setText("Current crisis"); group.setBounds(10, 10, 544, 194); Button button = new Button(group, SWT.NONE); button.addMouseListener(new MouseAdapter() { @Override public void mouseDown(MouseEvent e) { NewCrisis.main(null); } }); button.setText("New crisis"); button.setBounds(199, 134, 93, 33); table = new Table(group, SWT.BORDER | SWT.FULL_SELECTION); table.setLinesVisible(true); table.setHeaderVisible(true); table.setBounds(10, 10, 520, 107); TableColumn tableColumn = new TableColumn(table, SWT.NONE); tableColumn.setWidth(84); tableColumn.setText("Crisis number"); TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE); tableColumn_1.setWidth(71); tableColumn_1.setText("Type"); TableColumn tableColumn_2 = new TableColumn(table, SWT.NONE); tableColumn_2.setWidth(100); tableColumn_2.setText("Label"); TableColumn tableColumn_3 = new TableColumn(table, SWT.NONE); tableColumn_3.setWidth(100); tableColumn_3.setText("Place"); TableColumn tableColumn_4 = new TableColumn(table, SWT.NONE); tableColumn_4.setWidth(100); tableColumn_4.setText("State"); TableColumn tableColumn_5 = new TableColumn(table, SWT.NONE); tableColumn_5.setWidth(100); tableColumn_5.setText("Details"); Menu menu = new Menu(shlCmss, SWT.BAR); shlCmss.setMenuBar(menu); MenuItem mntmFile = new MenuItem(menu, SWT.CASCADE); mntmFile.setText("File"); Menu menu_1 = new Menu(mntmFile); mntmFile.setMenu(menu_1); MenuItem mntmInformations = new MenuItem(menu_1, SWT.NONE); mntmInformations.setText("Informations"); MenuItem mntmQuit = new MenuItem(menu_1, SWT.NONE); mntmQuit.setText("Quit"); MenuItem menuItem = new MenuItem(menu, SWT.NONE); MenuItem mntmDatabases = new MenuItem(menu, SWT.CASCADE); mntmDatabases.setText("Databases"); Menu menu_2 = new Menu(mntmDatabases); mntmDatabases.setMenu(menu_2); MenuItem mntmPsc = new MenuItem(menu_2, SWT.NONE); mntmPsc.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { PSCDB.main(null); } }); mntmPsc.setText("PSC"); MenuItem mntmFsc = new MenuItem(menu_2, SWT.NONE); mntmFsc.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { FSCDB.main(null); } }); mntmFsc.setText("FSC"); MenuItem mntmCrisis = new MenuItem(menu, SWT.CASCADE); mntmCrisis.setText("Crisis"); Menu menu_3 = new Menu(mntmCrisis); mntmCrisis.setMenu(menu_3); MenuItem mntmNew = new MenuItem(menu_3, SWT.NONE); mntmNew.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { NewCrisis.main(null); } }); mntmNew.setText("New"); MenuItem mntmList = new MenuItem(menu_3, SWT.NONE); mntmList.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { CrisisList.main(null); } }); mntmList.setText("List"); MenuItem mntmPolicies = new MenuItem(menu_3, SWT.NONE); mntmPolicies.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { PoliciesList.main(null); } }); mntmPolicies.setText("Policies"); shlCmss.open(); shlCmss.layout(); while (!shlCmss.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } }
2
@Override public double getHig() { return hight; }
0
Xpp3Dom createResult(final TestState testState) { return createElementWithText("result", testState.getState()); }
0
public static String writeObj(final Object object) { String result = null; if (object instanceof Long) { Long longObj = (Long) object; result = writeInt(longObj); } else if (object instanceof Integer) { Integer intObj = (Integer) object; result = writeInt(intObj.longValue()); } else if (object instanceof Short) { Short shObj = (Short) object; result = writeInt(shObj.longValue()); } else if (object instanceof Byte) { Byte bObj = (Byte) object; result = writeInt(bObj.longValue()); } else if (object instanceof String) { String strObj = (String) object; result = writeByteArray(strObj.getBytes(BConst.ASCII)); } else if (object instanceof byte[]) { byte[] bytes = (byte[]) object; result = writeByteArray(bytes); } else if (object instanceof Iterable) { Iterable itObj = (Iterable) object; result = writeList(itObj); } else if (object instanceof Map) { Map mObj = (Map) object; result = writeDict(mObj); } else { throw new IllegalArgumentException(String .format("Unsupport class for serialization: %s.", object.getClass().getName())); } return result; }
8
private OutputStream getOutputStream(final String s) { return new OutputStream() { StringBuffer o = new StringBuffer(); boolean done = false; @Override public void write(int b) throws IOException { if (b == '\n' && !sync) { synchronized (conf) { System.out.printf("[%s] %s \n", s, o.toString()); } o = new StringBuffer(); } o.append((char) b); } @Override public void flush() throws IOException { if (!done) { if (sync) { System.out.printf("************* %s **************\n", s); } System.out.printf(o.toString()); done = true; } } }; }
4
public void testConstructorEx9_TypeArray_intArray() throws Throwable { int[] values = new int[] {3, 0}; DateTimeFieldType[] types = new DateTimeFieldType[] { DateTimeFieldType.dayOfMonth(), DateTimeFieldType.dayOfWeek()}; try { new Partial(types, values); fail(); } catch (IllegalArgumentException ex) { // expected } }
1
@Override public void visitTypeInsn(final int opcode, final String type) { Item i = cw.newClassItem(type); // Label currentBlock = this.currentBlock; if (currentBlock != null) { if (compute == FRAMES) { currentBlock.frame.execute(opcode, code.length, cw, i); } else if (opcode == Opcodes.NEW) { // updates current and max stack sizes only if opcode == NEW // (no stack change for ANEWARRAY, CHECKCAST, INSTANCEOF) int size = stackSize + 1; if (size > maxStackSize) { maxStackSize = size; } stackSize = size; } } // adds the instruction to the bytecode of the method code.put12(opcode, i.index); }
4
public void addContestant(Contestant c) throws InvalidFieldException { if (allContestants.size() == numInitialContestants) { System.out.println("Too many contestants."); return; } if (isContestantIDInUse(c.getID())) { throw new InvalidFieldException( InvalidFieldException.Field.CONT_ID_DUP, "Contestant ID invald (in use)"); } allContestants.add(c); Collections.sort(allContestants, Utils.getComparator(CompType.ID, Contestant.class)); notifyAdd(UpdateTag.ADD_CONTESTANT); }
2
public void addToggleButtonListener(ActionListener listener){ toggleBtn.addActionListener(listener); if(disableAction != null) disableAction.addActionListener(listener); }
1
@Test public void runTestActivityCommunication1() throws IOException { InfoflowResults res = analyzeAPKFile("InterAppCommunication_ActivityCommunication1.apk"); Assert.assertEquals(1, res.size()); }
0
public void setState(String state) { this.state = state; }
0
public void setStoredValueAsString(String storedValueAsString) { this.storedValueAsString = storedValueAsString == null ? "" : storedValueAsString; }
1
public Type getCanonic() { int types = possTypes; int i = 0; while ((types >>= 1) != 0) { i++; } return simpleTypes[i]; }
1
public Term getTerm() { return term; }
0
public Point getSideLocation(TileColor face) { Point offset = new Point(150, -25); if (face.equals(TileColor.orange)) return new Point(offset.x, frameSize.height / 2 - squareSize / 2 + offset.y); else if (face.equals(TileColor.white)) return new Point(offset.x + squareSize, frameSize.height / 2 - squareSize / 2 + offset.y); else if (face.equals(TileColor.red)) return new Point(offset.x + squareSize * 2, frameSize.height / 2 - squareSize / 2 + offset.y); else if (face.equals(TileColor.yellow)) return new Point(offset.x + squareSize * 3, frameSize.height / 2 - squareSize / 2 + offset.y); else if (face.equals(TileColor.blue)) return new Point(offset.x + squareSize, frameSize.height / 2 - squareSize / 2 - squareSize + offset.y); else if (face.equals(TileColor.green)) return new Point(offset.x + squareSize, frameSize.height / 2 - squareSize / 2 + squareSize + offset.y); return null; }
6
public String getIpaddress() { return ipaddress; }
0
public void addAll(Profile[] p, byte gameID){ Game g = GameFactory.getGameFromID(gameID); for(int i=0; i<p.length; i++){ if(profiles.length == size) profiles = Arrays.copyOf(profiles, size+3); // Check if the profile is already in use int updateIndex = -1; for(int x=0; x<size; x++){ if( profiles[x].getGameID() == gameID && profiles[x].getSaveDir().equalsIgnoreCase(p[i].getSaveDir()) && profiles[x].getID() == p[i].getID()){ updateIndex = x; break; } } if( updateIndex == -1 ){ // Add the profile profiles[size] = p[i].clone(gameID, ++profileIdCounter); g.setupProfile(profiles[size]); size++; } else { // Update the profile profiles[updateIndex].setImage(p[i].getImage()); profiles[updateIndex].setName(p[i].getName()); } } }
7
public void refineTree() throws Exception { int nniCount = 0; switch( ntype ) { case OLS: if ( btype != balance.OLS ) T.assignAllSizeFields(); T.makeOLSAveragesTable(D,A); nniCount = T.NNI(A,nniCount); T.assignOLSWeights(A); break; case BAL: if ( btype != balance.BAL ) T.makeBMEAveragesTable(D,A); nniCount = T.bNNI( A, nniCount ); T.assignBMEWeights(A); break; case NONE: switch( wtype ) { case OLS: // default if ( balance.OLS != btype) T.assignAllSizeFields(); T.makeOLSAveragesTable(D,A); T.assignOLSWeights(A); break; case BAL: if ( balance.BAL != btype ) T.makeBMEAveragesTable(D,A); T.assignBMEWeights(A); break; default: throw new Exception( "Error in program: variable 'btype' has illegal value " +btype); } break; default: throw new Exception( "Error in program: variable 'ntype' has illegal value " +ntype); } }
9
public static <T> boolean binarySearch(ArrayList<T> list, T item, Comparator<? super T> cmp) { int comparison= cmp.compare(list.get(list.size()/2), item); if(comparison != 0) { //If we go to the bottom of the tree and there is like roots that are unequal then its not in the list. if(list.size() <= 1) return false; if(comparison > 0){ //take the left hand half of the list. ArrayList<T> left = new ArrayList<T>( list.subList(0, list.size()/2)); return binarySearch(left, item, cmp); } else { //take the right hand half of the list. ArrayList<T> right = new ArrayList<T>(list.subList( list.size()/2, list.size())); return binarySearch(right, item, cmp); } } else //The item is contained in the list return true; }
4
@Override public boolean nextKeyValue() throws IOException, InterruptedException { if (fsin.getPos() < end) { if (readUntilMatch(startTag, false)) { try { buffer.write(startTag); if (readUntilMatch(endTag, true)) { value.set(buffer.getData(), 0, buffer.getLength()); key.set(fsin.getPos()); return true; } } finally { buffer.reset(); } } } return false; }
3
public void setRight(PExp node) { if(this._right_ != null) { this._right_.parent(null); } if(node != null) { if(node.parent() != null) { node.parent().removeChild(node); } node.parent(this); } this._right_ = node; }
3
public T getSecond() { return second; }
0
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: List<String> pelaajat = new ArrayList<String>(); if(!jTextField2.getText().isEmpty()) { pelaajat.add(jTextField2.getText()); } if(!jTextField3.getText().isEmpty()) { pelaajat.add(jTextField3.getText()); } if(!jTextField4.getText().isEmpty()) { pelaajat.add(jTextField4.getText()); } if(!jTextField5.getText().isEmpty()) { pelaajat.add(jTextField5.getText()); } Peli p = new Peli(pelaajat); System.out.println(p.annaNoppa(1).annaSilmaluku()); liittyma.asetaPeli(p); PeliNaytto pelinaytto = new PeliNaytto(this.liittyma, p); JPanel pnaytto = pelinaytto.annaPaneeli(); this.liittyma.getFrame().getContentPane().add(pnaytto); liittyma.korttileiska().next(liittyma.getFrame().getContentPane()); }//GEN-LAST:event_jButton1ActionPerformed
4
@Override public boolean setFromString(String value) { this.strings=value.split("\\x00"); if(strings.length==0) { this.strings=null; } return true; }
1
public void testInvariants() { assertTrue(!(moteur.estFini() && !((moteur.combat().alex().estVaincu() && moteur .combat().ryan().estVaincu()) || moteur.combat().slick() .estVaincu()))); assertTrue(!(moteur.resulatFinal() == Resultat.GAGNEE && !(moteur .combat().slick().estVaincu() && (!moteur.combat().alex() .estVaincu() || !moteur.combat().ryan().estVaincu())))); assertTrue(!(moteur.resulatFinal() == Resultat.PERDUE && !(moteur .combat().alex().estVaincu() || moteur.combat().ryan() .estVaincu()))); }
8
public boolean fill() { Random rand = new Random(); boolean modified = false; for (int i = 0; i < height; i++) { for (int j = width - 1; j >= 0; j--) { if (contentGrid[i][j] instanceof EmptyCase) { if (j == 0) { contentGrid[i][j] = listOfContents.get(rand .nextInt(listOfContents.size())).clone(); } else { contentGrid[i][j] = contentGrid[i][j - 1]; contentGrid[i][j - 1] = emptyCase.clone(); } modified = true; } } } return modified; }
4
public int getResponseCode() throws IOException { int code = 0; try { code = con.getResponseCode(); } catch (FileNotFoundException fnfex) { code = HttpConnection.HTTP_NOT_FOUND; } catch (IOException ioex) { if (ioex.getMessage().startsWith("file not found")) { code = HttpConnection.HTTP_NOT_FOUND; } else { throw ioex; } } return code; }
3
public boolean birthChecker() { switch (state) { case NONE: // If leftHand is below leftElbow which is below leftShoulder (or right) if (GestureInfo.gesturePieces[GestureInfo.LEFT_HAND_DOWN] && GestureInfo.gesturePieces[GestureInfo.RIGHT_HAND_DOWN] && GestureInfo.gesturePieces[GestureInfo.LEFT_ARM_VERTICAL] && GestureInfo.gesturePieces[GestureInfo.RIGHT_ARM_VERTICAL]) { state = GestureState.BIRTH; confidence = 0.0f; return true; } break; case BIRTH: if ((GestureInfo.gesturePieces[GestureInfo.LEFT_HAND_RISING]) && (GestureInfo.gesturePieces[GestureInfo.RIGHT_HAND_RISING]) && !GestureInfo.gesturePieces[GestureInfo.HANDS_ABOVE_HEAD]) { duration++; final PVector diffHand = PVector.sub(joints[GestureInfo.LEFT_HAND], prevJoints[GestureInfo.LEFT_HAND]); tempo += diffHand.mag(); final PVector diffHandR = PVector.sub(joints[GestureInfo.RIGHT_HAND], prevJoints[GestureInfo.RIGHT_HAND]); tempo += (diffHand.mag() + diffHandR.mag()) / 2; return true; } break; } return false; }
9
@Override public void mouseClicked(MouseEvent arg0) { PictureLabel label = (PictureLabel) arg0.getSource(); if (SwingUtilities.isLeftMouseButton(arg0)) { switch (label.getText()) { case "Quest": for(int i = 0; i < Main.begin.getSize(); i++){ Main.begin.getCards()[i].getName(); Main.begin.getCards()[i].setLocation(150 * i, 0); Main.panel.add(Main.begin.getCards()[i]); Main.panel.repaint(); } System.out.println("Starting quest"); break; case "MP [WIP]": System.out.println("Starting multiplayer"); break; case "Edit Deck": System.out.println("Starting deck editing"); break; case "Options": System.out.println("Starting options"); break; case "Switch User": JFrame frame = (JFrame)label.getParent().getParent() .getParent().getParent().getParent(); frame.dispose(); System.out.println("Starting switch user"); break; case "Quit": System.out.println("Quitting"); System.exit(0); break; default: System.out.println(label.getText() + " not registered"); break; } } }
8
public void setSocketListen(ServerSocket socketListen) { this.socketListen = socketListen; }
0
public static void asm_rlf(Integer befehl, Prozessor cpu) { // TODO Integer f = getOpcodeFromToBit(befehl, 0, 6); Integer d = getOpcodeFromToBit(befehl, 7, 7); Integer result = cpu.getSpeicherzellenWert(f); result = result << 1; if(result > 255) { result -= 256; if(cpu.getStatus().getBit(bits.C)) { result++; ///Set Carrybit } cpu.getStatus().setBit(bits.C); } if(d == 1) { cpu.setSpeicherzellenWert(f, result, true); } else { cpu.setW(result, true); } cpu.incPC(); }
3
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) { Type type = typeToken.getType(); Class<? super T> rawType = typeToken.getRawType(); if (!Map.class.isAssignableFrom(rawType)) { return null; } Class<?> rawTypeOfSrc = $Gson$Types.getRawType(type); Type[] keyAndValueTypes = $Gson$Types.getMapKeyAndValueTypes(type, rawTypeOfSrc); TypeAdapter<?> keyAdapter = getKeyAdapter(gson, keyAndValueTypes[0]); TypeAdapter<?> valueAdapter = gson.getAdapter(TypeToken.get(keyAndValueTypes[1])); ObjectConstructor<T> constructor = constructorConstructor.get(typeToken); @SuppressWarnings({"unchecked", "rawtypes"}) // we don't define a type parameter for the key or value types TypeAdapter<T> result = new Adapter(gson, keyAndValueTypes[0], keyAdapter, keyAndValueTypes[1], valueAdapter, constructor); return result; }
5
public Object clone()throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
0
private void closeOpenReport() throws Exception { LedgerOverview ledgerOverview = getLedgerOverview(); if (ledgerOverview == null) { throw new Exception("Could not find ledger overview."); } String ledgerUri = null; for (String uri : ledgerOverview.uris) { if (uri.contains(this.ledger)) { ledgerUri = uri; break; } } if (ledgerUri == null) { throw new Exception("Could not find selected ledger."); } LedgerDetail ledgerDetail = getLedgerDetail(); ReportInfo reportInfo = getReportInfoFromOpenUri(ledgerDetail.open_report_uri); if (reportInfo == null || !reportInfo.status.equals("open")) { throw new Exception("Already closed or closing report."); } closeReportFromOpenUri(ledgerDetail.open_report_uri); this.openReportUri = ledgerDetail.open_report_uri; reportInfo = getReportInfoFromOpenUri(this.openReportUri); if (reportInfo == null || (!reportInfo.status.equals("closing") && !reportInfo.status.equals("closed"))) { throw new Exception("Close report failed."); } checkReportClosedWithTimer(); }
9
public void mouseMoved(MouseEvent e) { MouseCoords = Board.fromScreenSpace(e.getPoint()); if (engine != null) engine.mouseChanged(); if (!editable) return; if (!boardBox.contains(e.getPoint())) return; Rectangle2D testPt = new Rectangle2D.Double(e.getX() - 5, e.getY() - 5, 8, 8); boolean hit = false; for (Line2D line : board.walls) { if (line.intersects(testPt)) { hit = true; curCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR); } } if (!hit) { curCursor = Cursor.getDefaultCursor(); } repaint(); }
6
public static String remove(String s, char c) { //Quick corner case maybe not needed if(s.length() == 0) { return s; } StringBuilder sb = new StringBuilder(); for(int i=0; i< s.length(); i++) { if (s.charAt(i)!= c) { sb.append(s.charAt(i)); } } return sb.toString(); }
3
public void buyPickaxe() { if (this.game.chestOpen && this.chestWood >= 10) { // unlock stone this.pickaxe = true; this.chestWood -= 10; } }
2
public Class<?> getReturnType() { return this.returnParam; }
1
public static String fastaSimpleRead(String fastaFile) { StringBuilder sb = new StringBuilder(); BufferedReader inFile; try { // Open file (either 'regular' or gzipped) inFile = Gpr.reader(fastaFile); if (inFile == null) return ""; // Error opening file String line = inFile.readLine(); // Discard first line while (inFile.ready()) { line = inFile.readLine().trim(); // Read a line sb.append(line); } inFile.close(); } catch (IOException e) { throw new RuntimeException(e); } return sb.toString(); }
3
public void testConstructor_8int__PeriodType3() throws Throwable { try { new Period(1, 2, 3, 4, 5, 6, 7, 8, PeriodType.dayTime()); fail(); } catch (IllegalArgumentException ex) {} }
1
public boolean removeGeneric(String generic_name){ Generic sgl; boolean item_found = false; for(int i=0;i<generics.size();i++){ sgl = (Generic) generics.get(i); if (sgl.name.equals(generic_name)){ item_found = generics.remove(i) != null; break; } } return item_found; }
2
public static NotificationType get(int typeID) { for (NotificationType notificationType : values()) { if (notificationType.getId() == typeID) return notificationType; } return UNKNOWN; }
2
public void genera() { iDir = ((int) (Math.random() * 5 + 1)); Objeto objFire = new Objeto(0,0,imaFire11); switch (iDir) { case 1: //Fire1 objFire.setX(400); objFire.setY(550); objFire.setImagen(imaFire11); break; case 2: //Fire2 objFire.setX(480); objFire.setY(550); objFire.setImagen(imaFire21); break; case 3: //Fire3 objFire.setX(600); objFire.setY(550); objFire.setImagen(imaFire31); break; case 4: //Fire4 objFire.setX(700); objFire.setY(550); objFire.setImagen(imaFire41); break; case 5: //Fire5 objFire.setX(820); objFire.setY(550); objFire.setImagen(imaFire51); break; } objFire.setDireccion(iDir); lnkFire.add(objFire); }
5
public void run() { try { while (true) { monitorThreadPool(); Thread.sleep(monitoringPeriod * 1000); } } catch (Exception e) { log.error(e.getMessage()); } }
2
public void reinforce() { }
0
public void readPic(int width, int height, int startFrame, int framesToBeCoded, ArrayList<Picture> picList) { int widthC = width >> 1; int heightC = height >> 1; for (int framesNo = startFrame; framesNo < startFrame + framesToBeCoded; framesNo++) { Picture picTemp; if (startFrame == 0) { picTemp = new Picture(width, height); //System.out.println(framesNo+"size:"+picList.size()); picList.add(picTemp); } else { picTemp = picList.get(framesNo % picList.size()); //System.out.println(framesNo+"nosizeup,size:"+picList.size()); } readPlane(picTemp.getY(), oneLineY, width, height); readPlane(picTemp.getCb(), oneLineCbCr, widthC, heightC); readPlane(picTemp.getCr(), oneLineCbCr, widthC, heightC); } }
2
public static void setMaxAge(int max_age) { if (max_age >= 1) Grass.max_age = max_age; }
1
public static void main(String[] args) { LOG.log(Level.FINE, "start aplikacji"); List<Klient> klienci = load(); Scanner sc = new Scanner(System.in); while(true) { pokazMenu(); int i = czytajLiczbeZKlawiatury(sc); System.out.println("wybrałeś: " + i); switch (i) { case 1: for(Klient klient : klienci) { System.out.println(klient); } break; case 2: Klient klient = wczytajDaneKlientaZKlawiatury(sc); System.out.println(klient); klienci.add(klient); try { save(klienci); } catch (IOException ex) { LOG.log(Level.WARNING, "błąd zapisu pliku " + ex.getMessage()); ex.printStackTrace(); } break; case 0: LOG.log(Level.INFO, "stop aplikacji"); return; } } }
6
private HashSet<Integer> calcTargets(int start, int steps, HashSet<Integer> targets, HashSet<Integer> visited) { // This is our recursive function that creates the targets list. steps = steps - 1; visited.add(start); if(getCellAt(start).isDoorway()) { targets.add(start); } else if(steps == 0) { targets.add(start); } else { for(Integer adjCell : getAdjList(start)) { HashSet<Integer> visitedTemp = new HashSet<Integer>(visited); if(!visited.contains(adjCell)) { targets = calcTargets(adjCell, steps, targets, visitedTemp); } } } return targets; }
4
@Override public void paint(Graphics g) { super.paint(g); for (Entry<State, Point> node : statePositionList.entrySet()) { for (State followingState : node.getKey().getFollowingStates()) { Point followingPosition = statePositionList.get(followingState); g.setColor(Color.BLACK); drawArrow(g, calculateNodeCenter(node.getValue().x), calculateNodeCenter(node.getValue().y), calculateNodeCenter(followingPosition.x), calculateNodeCenter(followingPosition.y), node.getKey() .getComputation(followingState) .toTranslationCode()); } } for (Entry<State, Point> node : statePositionList.entrySet()) { if (node.getKey().equals(startState)) { drawArrow(g, 0, getHeight() / 2, calculateNodeCenter(node.getValue().x), calculateNodeCenter(node.getValue().y), ""); } if (tape!=null&&node.getKey().equals(tape.getCurrentState())) { g.setColor(progression.getColor()); } else { g.setColor(DEFAULT_COLOR); } drawNode(g, node.getValue().x, node.getValue().y, node.getKey() .getIdentifier(),node.getKey().isEnd()); } }
6
@Override public void OnTimerTick(Room Room, RoomUser PetUser) { int timenow = Room.Environment.GetTimestamp(); if(timenow < NextThink) return; int r = Room.Environment.GetRandomNumber(1, 35); if(r == 1) { PetUser.MoveTo(Room.Environment.GetRandomNumber(1, Room.Model.MapSizeX), Room.Environment.GetRandomNumber(1, Room.Model.MapSizeY),true); NextThink = timenow + 4; } else if(r == 2) { String rSpeech = Speech[Room.Environment.GetRandomNumber(0, Speech.length - 1)]; if (rSpeech.length() != 3) { PetUser.Chat(null, Room, rSpeech, false); } else { PetUser.SetStatus(rSpeech, Double.toString(PetUser.Z)); } NextThink = timenow + 3; } else if(r == 35) { PetUser.PetData.GiveEnergy(+10); } }
5
public SimpleStringProperty addressTypeProperty() { return addressType; }
0
public String _toString () { org.omg.CORBA.portable.InputStream $in = null; try { org.omg.CORBA.portable.OutputStream $out = _request ("toString", true); $in = _invoke ($out); String $result = $in.read_string (); return $result; } catch (org.omg.CORBA.portable.ApplicationException $ex) { $in = $ex.getInputStream (); String _id = $ex.getId (); throw new org.omg.CORBA.MARSHAL (_id); } catch (org.omg.CORBA.portable.RemarshalException $rm) { return _toString ( ); } finally { _releaseReply ($in); } } // _toString
2
public String getTypeString(Type type) { if (type instanceof ArrayType) return getTypeString(((ArrayType) type).getElementType()) + "[]"; else if (type instanceof ClassInterfacesType) return getClassString(((ClassInterfacesType) type).getClassInfo()); else if (type instanceof NullType) return "Object"; else return type.toString(); }
3
@Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(affected instanceof MOB)) return super.okMessage(myHost,msg); final MOB mob=(MOB)affected; if((msg.amITarget(mob)) &&(CMath.bset(msg.targetMajor(),CMMsg.MASK_MALICIOUS)) &&(msg.targetMinor()==CMMsg.TYP_CAST_SPELL) &&(msg.tool() instanceof Ability) &&((((Ability)msg.tool()).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_SONG) &&(invoker!=null) &&(!mob.amDead()) &&(CMLib.dice().rollPercentage()<35)) { mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,L("The ward around <S-NAME> inhibits @x1!",msg.tool().name())); return false; } return super.okMessage(myHost,msg); }
9
private int[] generateRow(int[] input) { LinkedList<Integer> checkList = new LinkedList<Integer>(); Random r = new Random(); int row[] = new int[9]; for(int i=1; i<10; i++) checkList.add(i); for(int i=0; i<9; i++){ int num = Math.abs(input[i]); if(num>9||num==0) row[i]=0; else{ row[i]= -num; checkList.removeFirstOccurrence(num); } } for(int i=0; i<9; i++){ if(row[i]!=0)continue; if(checkList.isEmpty()) break; row[i]= checkList.remove(r.nextInt(checkList.size())); } return row; }
7
public static void main(String[] args) { Scanner in = new Scanner(System.in); char grade = in.next().charAt(0); switch (grade) { case 'A': System.out.println("Excellent"); break; case 'B': System.out.println("Good"); break; case 'C': System.out.println("So so"); break; case 'D': System.out.println("Fails"); break; case 'F': System.out.println("Get lost"); break; default: System.out.println("Invalid"); break; } }
5
public void renderLights(){ for(LightSource source : lightSources){ calculateShadows(source); } for(Player e : players){ if(e.light != null) calculateShadows(e.light); } for(Mob e : mobs){ if(e.light != null) calculateShadows(e.light); } }
5
@Override public String toString() { return this.file + "" + this.rank; }
0
private static GridResourceWithFailure createGridResource(String name, double baud_rate, double delay, int MTU, int totalPE, int totalMachine, int rating, String sched_alg) { // Here are the steps needed to create a Grid resource: // 1. We need to create an object of MachineList to store one or more // Machines MachineList mList = new MachineList(); for (int i = 0; i < totalMachine; i++) { // 2. Create one Machine with its id, number of PEs and rating mList.add( new Machine(i, totalPE, rating)); } // 3. Create a ResourceCharacteristics object that stores the // properties of a Grid resource: architecture, OS, list of // Machines, allocation policy: time- or space-shared, time zone // and its price (G$/PE time unit). String arch = "Sun Ultra"; // system architecture String os = "Solaris"; // operating system double time_zone = 9.0; // time zone this resource located double cost = 3.0; // the cost of using this resource // we create Space_Shared_failure or Time_Shared_failure schedulers int scheduling_alg = 0; // space_shared or time_shared if (sched_alg.equals("SPACE") == true) { scheduling_alg = ResourceCharacteristics.SPACE_SHARED; } else if (sched_alg.equals("TIME") == true) { scheduling_alg = ResourceCharacteristics.TIME_SHARED; } ResourceCharacteristics resConfig = new ResourceCharacteristics( arch, os, mList, scheduling_alg, time_zone, cost); // 4. Finally, we need to create a GridResource object. long seed = 11L*13*17*19*23+1; double peakLoad = 0.0; // the resource load during peak hour double offPeakLoad = 0.0; // the resource load during off-peak hr double holidayLoad = 0.0; // the resource load during holiday // incorporates weekends so the grid resource is on 7 days a week LinkedList Weekends = new LinkedList(); Weekends.add(new Integer(Calendar.SATURDAY)); Weekends.add(new Integer(Calendar.SUNDAY)); // incorporates holidays. However, no holidays are set in this example LinkedList Holidays = new LinkedList(); GridResourceWithFailure gridRes = null; try { // creates a GridResource with a link gridRes = new GridResourceWithFailure(name, new SimpleLink(name + "_link", baud_rate, delay, MTU), seed, resConfig, peakLoad, offPeakLoad, holidayLoad, Weekends, Holidays); } catch (Exception e) { e.printStackTrace(); } return gridRes; }
4
public boolean hasNext() throws Exception { if (!tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine().trim()); return hasNext(); } return true; }
1
@Override protected boolean execute(Widget widget, MouseEvent event) { final Widget c = parent != null ? parent : widget; switch (event.getID()) { case MouseEvent.MOUSE_EXITED: case MouseEvent.MOUSE_RELEASED: pressedPoint = null; initialXOffset = 0; initialYOffset = 0; break; case MouseEvent.MOUSE_PRESSED: if (event.getButton() == MouseEvent.BUTTON3) { pressedPoint = widget.isPressed() ? event.getPoint() : null; initialXOffset = c.getXOffset(); initialYOffset = c.getYOffset(); event.consume(); return true; } return false; case MouseEvent.MOUSE_DRAGGED: if (pressedPoint == null) { break; } c.setXOffset(initialXOffset + (event.getX() - pressedPoint.x)); c.setYOffset(initialYOffset + (event.getY() - pressedPoint.y)); event.consume(); c.invalidate(); return true; } return false; }
8
public Tablero(){ super(); setBackground(new Color(0,0,0)); tortuga =new Tortuga(); liebre = new Liebre(); pista = new Pista(); setLayout(null); ltortuga=new JLabel(""); ltortuga.setForeground(new Color(126,176,175)); ltortuga.setLocation(30,100); ltortuga.setSize(400, 25); lliebre=new JLabel(""); lliebre.setForeground(new Color(240,106,53)); lliebre.setSize(400, 25); lliebre.setLocation(30,120); lpausa=new JLabel(""); lpausa.setForeground(new Color(255,255,255)); lpausa.setSize(400, 25); lpausa.setLocation(30,140); try{ imageTortuga = ImageIO.read(new File("imagenes/turtle.png")); }catch (IOException e){System.out.println("ERROR: No se pudo abrir tortuga\n");} try{ imageLiebre = ImageIO.read(new File("imagenes/rabbit.png")); }catch (IOException e){System.out.println("ERROR: No se pudo abrir liebre\n");} try{ imageFondo = ImageIO.read(new File("imagenes/fondo.png")); }catch (IOException e){System.out.println("ERROR: No se pudo abrir el fondo\n");} add(ltortuga); add(lliebre); add(lpausa); tortuga.start(); liebre.start(); }
3
public void reset(){ Object[] data; try { data = Parser.parse(Constants.LEVEL_FILENAME); world = new World((List<Entity>)data[0], (List<Tile>)data[1], (List<PickUpObject>)data[2], (Player)data[3]); player = (Player)data[3]; lastJump = 0; lastRedraw = 0; cam = new Camera(); hud = new HUD(); world.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
1
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); double totaal = 0; if (session != null) { @SuppressWarnings("unchecked") Map<Integer, Integer> mandje = (HashMap<Integer, Integer>) session.getAttribute("mandje"); if (mandje != null) { List<ReservatieMandjeItem> reservaties = new ArrayList<>(); for (Map.Entry<Integer, Integer> entry : mandje.entrySet()) { int nummer = entry.getKey(); int plaatsen = entry.getValue(); ReservatieMandjeItem reservatie = new ReservatieMandjeItem(plaatsen, voorstellingDAO.findByNumber(nummer)); reservaties.add(reservatie); double tussenResultaat = plaatsen * voorstellingDAO.findByNumber(nummer).getPrijs().doubleValue(); totaal = totaal + tussenResultaat; } request.setAttribute("reservaties", reservaties); request.setAttribute("totaalTeBetalen", totaal); } } RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW); dispatcher.forward(request, response); }
3
private void resetTargetsIfNeeded() { if(runawayTarget[0] == x && runawayTarget[1] ==y){ runawayTarget[0] = -1; runawayTarget[1] = -1; } if(foodTarget[0] == x && foodTarget[1] == y){ foodTarget[0] = -1; foodTarget[1] = -1; randomTarget[0] = -1; randomTarget[1] = -1; } if(foodTarget[0]>0 && foodTarget[1]>0 && !env.tiles[foodTarget[0]][foodTarget[1]].hasFood) { foodTarget[0] = -1; foodTarget[1] = -1; randomTarget[0] = -1; randomTarget[1] = -1; } if((randomTarget[0] == x && randomTarget[1] == y)){ randomTarget[0] = -1; randomTarget[1] = -1; } }
9