text
stringlengths
14
410k
label
int32
0
9
private void init() { world1 = WorldGenerator.createWorld(GraphicsMain.WIDTH*GraphicsMain.SCALE, GraphicsMain.HEIGHT*GraphicsMain.SCALE); player = new Player(5, WorldGenerator.dirtBoundary*8 - Player.height - 1); graphicsMain = new GraphicsMain(); }
0
@Override public void enablePlugin(Plugin plugin) { Validate.isTrue(plugin instanceof InjectablePlugin, "Plugin is not associated with this PluginLoader"); if (!plugin.isEnabled()) { Injector.getLogger().info("Injecting plugin " + plugin.getName()); Inje...
3
private static int doTimedEvents( int firedEvents, long startTime ) { Iterator< Event > it = timedEvents.iterator(); // get the iterator for the timed events while ( it.hasNext() ) { if ( TimeHelper.isOver( startTime, MaxTickTime ) ) { return firedEve...
8
public List<ExameDAO> getExames() { try { EntityManager em = conecta(); if (em != null) { Query q = em.createQuery("SELECT p FROM Exame p"); List<Exame> resultado = q.getResultList(); List<ExameDAO> exames = new ArrayList<ExameDAO>(); ...
3
public BasicCoordinateTransform(CoordinateReferenceSystem srcCRS, CoordinateReferenceSystem tgtCRS) { this.srcCRS = srcCRS; this.tgtCRS = tgtCRS; // compute strategy for transformation at initialization time, to make transformation more efficient ...
9
public void imageRect(int x, int y, int w, int h, Object pix) { if (pix instanceof Image) { Image img = (Image)pix; clip = new Rectangle(x, y, w, h); synchronized(clip) { tk.prepareImage(img, -1, -1, this); try { clip.wait(1000); } catch(InterruptedException e) { ...
6
public void addTagsToOriginalStream(List<LabeledToken> parsedContents,int startIndex) { List<String> myPath=getBestViterbiPath(); int i=0,j=0; String fullEnamex; String leader; StringBuffer outBuffer=new StringBuffer(); LabeledToken myToken; while (i<myPath.size() && (startIndex+i+j<parsedContents....
4
private double coFactor(int c, int r) { Matrix3d minor = new Matrix3d(); int i = 0; for(int ri = 0;ri < SIZE;ri++) { if(ri == c) continue; for(int ci = 0;ci < SIZE;ci++) { if(ci == r) continue; minor.m[i++] = m[ri * 4 + ci]; } } if((r + c) % 2 == 0) return minor.determinant(); else return -...
5
private void setupColorMap() { if (wb instanceof HSSFWorkbook) { helper = new HSSFHtmlHelper((HSSFWorkbook) wb); } else if (wb instanceof XSSFWorkbook) { helper = new XSSFHtmlHelper((XSSFWorkbook) wb); } else { throw new IllegalArgumentException( ...
2
public List<String> getOptionArguments(CmdLineOption option) { List<String> list = new ArrayList<>(); if (isOptionUsed(option)) { for (CmdLineData one : mData) { if (one.isOption() && one.getOption() == option) { list.add(one.getArgument()); } } } return list; }
4
public void addPlayer(String playerName) { try { if (exists(playerName)) { return; } } catch (SQLException e) { e.printStackTrace(); return; } String query = "INSERT INTO `Player`(`Name`, `ReadRules`, `Agreed`, `Ignoring`) VALUES (\'" + playerName + "\', 0, 0, 0);"; plugin.getSQL().execut...
2
public static List<Double> closestPoint(Matrix points, List<Double> point) { double closestDistance = Double.POSITIVE_INFINITY; int closestIndex = -1; int size = points.getNumRows(); for (int i = 0; i < size; i++) { List<Double> row = points.getRow(i); // Ignore ...
3
@Override public void run() { File inputFile = new File(inputPath); File outputFile = new File(outputPath); try { MP4Demuxer demuxer = new MP4Demuxer(new AutoFileChannelWrapper(inputFile)); MP4Muxer muxer = new MP4Muxer(NIOUtils.rwFileChannel(outputFile)); ...
7
private boolean Formula() { begin("Formula"); if (Predicate()) { sem.moveUpPred(); return accept(); } if (False()) { sem.fls(); return accept(); } if (Formula_0()) { sem.binaryFormula(); return accept(); } if (Formula_1()) { sem.notFormula(); return accept(); } ...
4
private boolean listaParametros() { /*<lista_parametros> ::= <parametro> <prox_parametro> | “vazio” “)” <prox_parametro> ::= “,” <parametro> <prox_parametro> | “)” <parametro> ::= <tipo_parametro> <id> <colchete> <tipo_parametro> ::= <tipo_primitivo> | <id> <colchete> ::= “...
9
@Override public void run() { if(minecraft.session != null) { HttpURLConnection connection = null; try { connection = (HttpURLConnection)new URL("http://www.minecraft.net/skin/" + minecraft.session.username + ".png").openConnection(); connection.setDoInput(true); connection.setDoOutput(false);...
4
@Override public void mouseClicked(MouseEvent arg0) { if(arg0.getSource() == view.dishIcon[0]){ //Opens DishView setUpView(new DishView(model, model.getDishByName(view.dishIcon[0].getName(),model))); } if(arg0.getSource() == view.dishIcon[1]){ setUpView(new DishView(model, model.getDishByName(view.dishIcon...
9
public static double[] createRandomDistributionProbabilistWithNoZero(int size, int precision) { double[] distribution = new double[size]; int minimum = (int)Math.pow(precision, 0.2); for (int i = 0; i < distribution.length; i++) { distribution[i] += minimum; } ...
3
private int closestMultiColor(MultiColor mc) { if (mc.allTransparent()) return 0; else { int best = -1; float bestd = Float.POSITIVE_INFINITY; for (int i = 0; i < multiPalette.length; i++) { if (multiPalette[i] == nu...
5
public void unregisterListener( EventListener listener, Plugin plugin ) { for( Class< ? extends Event > eventClass : executors.keySet()) { List< EventExecutor > keep = new ArrayList< EventExecutor >(); for( EventExecutor e : executors.get( eventClass ) ) { if( e.getListener().getClass() == listene...
6
@EventHandler(priority = EventPriority.NORMAL) public void onPlayerJoin(PlayerJoinEvent event) { Player player = event.getPlayer(); if (player.isOp() && plugin.getConfig().getBoolean("enable-version-notifier")) { try { URL version = new URL(ColorKeys.versionURL); URLConnection dc = version.openConnecti...
6
public static String getDefaultValue(String currentField, Map<String, String> defaultValueMap, Map<String, String> globalDefaultValueMap, Boolean isSinlgeFile) { String defalutValue = "''"; String currentFieldDefaultKey; String currentFieldTypeKey; String commonDefaultKey; String...
9
public List<String> parseGamesData(String gamesString, String parameter) { List<String> games = new ArrayList<>(); String[] data = getGamesData(gamesString); for (String str : data) games.add(extractParameterValue(str, parameter)); return games; }
1
public boolean checkSunkFor(Player p, int hitSize) { // System.out.println("hitSize: " + hitSize); generalPlayer = p; sunk = false; if (generalPlayer == p1) { board = p2Board; // System.out.println("Initial hits p1: " + hits); } if (generalPlayer == p2) { board = p1Board; // System.out.println...
9
private void draw(Graphics2D g) { g.setFont(font); Dimension dim = getSize(); if (knob == null) knob = new Rectangle(0, 0, dim.width / 5, dim.height); g.setColor(getBackground()); g.fillRect(0, 0, dim.width, dim.height); g.setColor(Color.white); g.fillRect(5, 5, dim.width - knob.width, dim.height -...
8
public String post(String url, Map<String, Serializable> data) { try { URL u = new URL(url); HttpURLConnection conn = (HttpURLConnection) u.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Ty...
6
public void testMinusFields() { Period test; test = Period.years(3).minusYears(1); assertEquals(new Period(2, 0, 0, 0, 0, 0, 0, 0, PeriodType.standard()), test); test = Period.months(3).minusMonths(1); assertEquals(new Period(0, 2, 0, 0, 0, 0, 0, 0, PeriodType.standard()), test);...
1
@After("execution(* crossPoint(..)) && args (splashWindow,..)") public void killSplash(SplashWindow splashWindow) { splashWindow.dispose(); splashWindow = null; }
0
private static double DaylightSavingTA(double t) { // Another workaround! The JRE doesn't seem to know about DST // before year 1 AD, so we map to equivalent dates for the // purposes of finding dst. To be safe, we do this for years // outside 1970-2038. if (t < 0.0 || t > ...
7
public static void main(String... args) throws Throwable { final List<String> catalog = Collections.synchronizedList(new ArrayList<String>()); MqttClientListener listener = new MqttClientListener() { @Override public void publishReceived(MqttClient client, PublishMessage message) { catalog.add(message.get...
8
@Override public Vector slice(int from, int to) { SparseVector res = new SparseVector(); int fi = find(from); if (fi < 0 ) { fi = - fi - 1; } int ti = find(to); if (ti < 0) { ti = - ti - 1; } for(int idx = fi; idx<ti; idx++) { ...
3
public static void search(String command) { String[] lookIn = command.split(" ", 2); boolean adjacent = false; for(int i = 0; i < Parasite.thePlayer.currentLocation.adjacentRooms.length;i++) { if(LocationHelper.getLocationFromName(lookIn[1]).e...
3
@SuppressWarnings( {"unchecked", "rawtypes"}) private void validateMethod(final Object instance, final Method method, final boolean useStrictMode, final ValidationResults results) { /* * Validate all method annotations. */ final Annotation[] ...
9
public List<String> letterCombinations(String digits) { List<String> results = new ArrayList<String>(); StringBuffer letter = new StringBuffer(); appendDigits(digits,0,results,letter); return results; }
0
private void parseUnMod(){ //Only read in lines up to the breakAt point. This is useful for debugging. int breakAt = -1; int count = 0; try { Scanner s = new Scanner(new File(inputFile)); String token = ""; //Skip the header for(int i = 0; i < 4; i++){ token = s.nextLine(); } /...
8
public static void moveDownText(OutlinerCellRendererImpl textArea, JoeTree tree, OutlineLayoutManager layout) { Node currentNode = textArea.node; // Get Prev Node Node nextNode = tree.getNextNode(currentNode); if (nextNode == null) { return; } // Record the EditingNode and CursorPosition tree.setEdit...
2
private void resolveConflicts() { ArrayList<HumanAgent> humans; ArrayList<ZombieAgent> zombies; ArrayList<AgentsGroup> cellGroups; EnvironmentCell cell; final int rows, columns; cellGroups = new ArrayList<>(); rows = this.configuration.getEnvironmen...
6
@Override public void move(Set<Direction> directions) { //for each direction the player wants to move in for(Direction direction : directions) { //if that direction is not one that is in the direction of a collision if(!collisions.contains(direction)) { //move switch(direction) { case B...
7
@Override public String toString() { String temp = Long.toString(result[0]); for (int i = 1; i < result.length; i++) { temp += Const.splitOutValStats + Long.toString(result[i]); } for (int i = 0; i < statistic.length; i++) { temp += Const.splitOutValStats + statistic[i]; } return temp; }
2
public static Sexp[] parses(String sExps) throws ParseException { //改行とコメント行の削除 StringBuilder sb = new StringBuilder(); for (String line : sExps.split("\n")) { if (line.indexOf(";") == -1) { sb.append(line); } else { sb.append(line.substrin...
9
public void testSetDate_int_int_int2() { MutableDateTime test = new MutableDateTime(TEST_TIME1); try { test.setDate(2010, 13, 3); fail(); } catch (IllegalArgumentException ex) {} assertEquals(TEST_TIME1, test.getMillis()); }
1
private float getWorldMap(int x, int z) { int x1 = (int)Math.floor(x/Chunk.size) * Chunk.size; int z1 = (int)Math.floor(z/Chunk.size) * Chunk.size; if(x < 0) x1-=Chunk.size; if(z < 0) z1-=Chunk.size; Chunk chunk = getChunk(x1, z1); if(chunk != null) { // System.out.println("C(" + chun...
8
private void split(Node<T> node) { int size = node.numberOfKeys(); int medianIndex = size / 2; T medianValue = node.getKey(medianIndex); Node<T> left = new Node<T>(null, maxKeySize, maxChildrenSize); for (int i = 0; i < medianIndex; i++) { left.addKey(node.getKey(i))...
8
public EventsService(IClient client, JsonHandler dataHandler) { this.client = client; this.dataHandler = dataHandler; }
0
public int getNoOfStocksByUserAndTickerName(String username, String tickername) { tickername = tickername.toUpperCase(); for(UserStocks us:thisUserStock) { if(us.getTickername().equals(tickername) && us.getUsername().equals(username)) { return us.getNo(); } } return 0; }
3
public void fillBackgroundLayer(TileSprite bgTile, int width, int height){ // Instantiate that new layer TileMapLayer tLayer = new TileMapLayer(-1, "Background"); // Tile to use for filling Tile tile = new BasicTile(0, bgTile, false); Tile[][] tiles = new Tile[width][height]; // Loop and fill the layer with...
1
public static void saveDataFirst(String name) { path = name; File f = new File(plugin.getDataFolder() + File.separator + "Players" + File.separator + name + ".data"); if (new File(plugin.getDataFolder() + File.separator + "Players").exists()) { if (!f.exists()) { try { // Bukkit.broadcastMessage(...
5
private static void checkRange(int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex < 0: " + fromIndex); if (toIndex < 0) throw new IndexOutOfBoundsException("toIndex < 0: " + toIndex); if (fromIndex > toIndex) th...
3
private void fillList() { Statement stmt = null; ResultSet rs = null; Connection conn = null; conn = Database.getConnection(); try { stmt = conn.createStatement(); String q = "select * from book"; switch (select) { case "genre":...
8
public ArrayList<ArrayList<Integer>> threeSum(int[] num) { Arrays.sort(num); Set set = new HashSet(); HashMap<Integer, Integer> mapper = new HashMap<Integer, Integer>(); for (int i = 0; i < num.length; i++) { mapper.put(num[i], i); } ArrayList<ArrayList<Int...
7
public void setLineNumbers(Program program) { for(int line = 0, ctr = 0; line < program.getProgramStatements().size(); line++) { for(int j = 1; j <= 2; j++) { if(program.getProgramStatements().get(line).get(j) != null && !program.getProgramStatements().get(line).get(j).equals(" ") && InstructionLi...
5
public static LinkedList<String> getAlgorithmList() { LinkedList<String> l = new LinkedList<String>(); try { BufferedReader in = new BufferedReader(new FileReader( "sortAlgorithms.lst")); String algo; while ((algo = in.readLine()) != null) l.add(algo); in.close(); } catch (IOException x...
2
@Override protected boolean isSubTypeOf(final BasicValue value, final BasicValue expected) { Type expectedType = expected.getType(); Type type = value.getType(); switch (expectedType.getSort()) { case Type.INT: case Type.FLOAT: case Type.LONG: case...
9
private static void insertRecordIntoDbUserTable(ArrayList<String> xmlList) throws SQLException { // generates rows in table, each with file name and one keyword/ontology Connection dbConnection = null; PreparedStatement statement = null; try { dbConnection = getDBConnection(); int batchSize = 0...
9
private void controlDisplay(KeyEvent e) { if (e.getKeyChar() == 'w') { moveRichtungY = -5; } if (e.getKeyChar() == 'a') { moveRichtungX = -5; } if (e.getKeyChar() == 's') { moveRichtungY = 5; } if (e.getKeyChar() == 'd') { moveRichtungX = 5; } }
4
public static boolean isEmpty(Object o) { if (o != null) { if (o instanceof Object[]) { return ((Object[]) o).length == 0 || (((Object[]) o).length == 1 && isEmpty(((Object[]) o)[0])); } else { return ("".equals(valueOf(o))) || "null".equals(valueOf(o)) ...
9
private void doAddAppender(LoggerAppender appender) throws Exception { if ((appender.getAppenderName() == null) || (appender.getAppenderName().isEmpty())) throw new IllegalArgumentException("Appender is null"); if (appender.getAppenderName().equalsIgnoreCase("STDOUT")) { addConsoleAppender(appender.getApp...
4
private void findFrom() { possibleFromEdges = guiM.findPossibleEdges(cgInstance.getTextFromFromTextField()); if(possibleFromEdges.size() > 1){ new ChooseFrame(this, true); } else if(possibleFromEdges.size() == 1){ for(Entry<String, MyEdge> entry : possibleFromEdges.entrySet()) { guiM.nodeFromKDV = entry...
5
private void paintPiecesInHand(Graphics g, Player player) { int player_type = player instanceof AheadPlayer ? Player.AHEAD : Player.BEHIND; Point offset = player_type == Player.AHEAD ? AHEAD_OFFSET : BEHIND_OFFSET; int count_of[] = new int[7]; for(Piece p : player.getPiecesInHand()) { ...
9
public void add(Matrix that, int rowStart, int colStart, int rowCount) throws Exception { if(colStart + cols() > that.cols()) throw new Exception("out of range"); for(int i = 0; i < cols(); i++) { if(that.valueCount(colStart + i) != valueCount(i)) throw new Exception("incompatible relations"); } for(i...
5
protected void useAlgorithm(String algorithm) throws NoSuchAlgorithmException { if (messageDigest == null || messageDigest.getAlgorithm() != algorithm) { messageDigest = MessageDigest.getInstance(algorithm); } if (encoder == null) { encoder = new BASE64Encoder(); } }
3
private void makeConnection(){ String serverIP = this.view.getServerField().getText(); String portText = this.view.getPortField().getText(); String nickname = this.view.getUsernameField().getText(); String password = this.view.getPasswordField().getText(); if (!serverIP.equals("") && !portText.equals(""...
6
public Map<String, UUID> call() throws Exception { Map<String, UUID> uuidMap = new HashMap<String, UUID>(); int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST); for (int i = 0; i < requests; i++) { HttpURLConnection connection = createConnection(); String ...
4
public Block getBlock(int x, int y) { if (x >= 0 && x < LINE_WIDTH && y >= 0 && y < LINE_AMOUNT) return rows[y][x]; return null; }
4
public SHORT_FORM getShortText(String dayz) { Collection<String> listOfShiftDay = new ArrayList<String>(); listOfShiftDay.addAll(Arrays.asList(dayz.replace(" ", "").split(","))); if (listOfShiftDay == null || listOfShiftDay.size() <= 0) return SHORT_FORM.OTHER; if (listOfS...
8
public Region(long initialTemp, double[] tc, int i, int j, Alloy sa) { this.sa = sa; sa.temps[0][i][j] = initialTemp; sa.temps[1][i][j] = initialTemp; thermalConstants = tc; calculatePercentages(); constantTemp = false; this.indexI = i; this.in...
0
public void parseDataList() { ArrayList<HashMap<String, String>> acc = new ArrayList(); HashMap<String, String> stickyMap = new HashMap(); for(Map<String, String> sourceMap : dataList) { if( acc.size() == 0 ) { for(Map.Entry<String, String> e : sou...
6
public void setFullScreen(DisplayMode dm, JFrame window){ window.setUndecorated(true); window.setResizable(false); vc.setFullScreenWindow(window); if (dm != null && vc.isDisplayChangeSupported()){ try{ vc.setDisplayMode(dm); }catch(Exception ex){} } }
3
private void jMenuItem1MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenuItem1MousePressed try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); JFrame mainFra...
5
public static CountryEnum fromValue(String v) { for (CountryEnum c: CountryEnum.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); }
2
public void add(String key) { assert key != null; for (int bucketIndex : getHashBuckets(key)) { Bucket bucket = new Bucket(bucketIndex); if(bucket.value < MAX_COUNT) { bucket.set(bucket.value + 1); } } }
2
private void prepareNewSaveFile() throws IOException{ //Carregando o Score Table do arquivo: File temp = null; try{ temp = new File("ScoreBoard.txt"); //Se o arquivo não existe, criando o mesmo: if(!temp.exists()){ temp.create...
2
@Override public void keyPressed(KeyEvent e) { AppliWindow window = AppliWindow.getInstance(); switch (e.getKeyChar()) { case 'p': // Retour au jeu if(window.isPauseStatus()) { window.hidePause(); window.showGame(); Game.getInstance().setRunning(true); Game.getInstance().start(); ...
4
@Override public String toString() { return "fleming.entity.Diagnostico[ idDiagnostico=" + idDiagnostico + " ]"; }
0
public static float pedir_cantidad_ingreso(){ float cantidad=0; do{ try{ BufferedReader stdin=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Importe Ingreso => "); cantidad=Float.parseFloat(stdin.readLine()); }catch(NumberFormatException e){ System.out.println(e+"Valores numeri...
3
private void listen(int port, int wss_port) { try { ServerSocket listener = new ServerSocket(port); try { new FlashPolicyServer().run(); } catch (Exception e) { e.printStackTrace(); } try { new Websocket(wss_port).start(); } catch (Exception e) { e.printStackTrace(); } ...
4
public static void main(String[] args) { System.out.println("Frage: Ist dieses Zeichen eine HEX-Zahl?"); System.out.print("Bitte Zeichen eingeben: "); char eingabe = Console.readChar(); if(( '0' <= eingabe && eingabe <= '9' ) || ( 'a' <= eingabe && eingabe <= 'f' ) || ( 'A' <= eingabe && eingabe <= 'F' )) {...
6
private JPanel createServerStatusPanel(ArrayList<ServerStatus> serverList){ JPanel mainPanel = new JPanel(); String realm = ""; JPanel panel = null; for (ServerStatus server: serverList){ if(!realm.equals(server.realm)){ if(panel != null) mainPanel.add(panel); realm = server.realm; panel = new JP...
8
private State planIngredient(Domain domain, State startingState, IngredientRecipe ingredient, State currentState, List<RewardFunction> rewardFunctions, TerminalFunction recipeTerminalFunction, StateHashFactory hashFactory, StateConditionTest goalCondition, Heuristic heuristic, List<EpisodeAnalysis> episo...
8
public static SyncPDU fromBuffer(ByteBuffer buf) throws Exception { SyncPeer from; SyncPeer to; byte[] setID; byte type; int setsize; long begin; long end; long[] recVector; int i = buf.getInt(); ...
2
public ArrayList<Organism> getOthersWorldMonster(int x,int y,String wor) { ArrayList<Organism> end=new ArrayList<>(); for(int i=0;i<organisms.size();i++) { if((organisms.get(i).getX()<=x+8)&&(organisms.get(i).getX()>=x-8)) { if((organisms.get(i).getY()<=y+8)&&(organisms.get(i).getY...
8
private static Subtask[] append(Subtask[] array, Subtask subtask){ Subtask[] newArray = new Subtask[array.length+1]; for(int i=0; i<array.length; i++){ newArray[i] = array[i]; } newArray[array.length] = subtask; return newArray; }
1
@Test public void testRemovePromotion() { BlockingQueue<Promotion> promotionAux = null; Product book = new Product("Book", 1234, 2.30, 100); Product table = new Product("Table", 4321, 3.00, 100); Product printer = new Product("Printer", 1334, 1.20, 100); facade.addProduct(book); facade.addProduct(table)...
3
@GET @Path("all") @Produces({MediaType.APPLICATION_XML}) public String findTournaments() { Set<Tournament> tournamentSet = tournamentBO.findAll(); for (Tournament tournament : tournamentSet) { Set<Team> teamSet = teamBO.findByTournament(tournament.getIdTournament()); tournamentSet.re...
2
@Override public void mouseClicked(MouseEvent arg0) { if (orderComboBox.isEnabled()) { String[] values = ((String) orderComboBox.getSelectedItem()).split("\\t"); if (values != null) { showOrderDetails(driver.getOrderDB().getOrderById( Integer.parseInt(values[1].trim()), driver.getOrderDB().getC...
2
Line execute(Interpreter machine) throws MyException { if (_operands != null && _operands.size() == 4 && _operands.get(0).execute(machine).isNumber() && _operands.get(1).execute(machine).isNumber() && _operands.get(2).execute(machine).isNumber() &&...
6
public static boolean open(Line line) { if (line.isOpen()) return false; try { line.open(); } catch (LineUnavailableException ex) { return false; } return true; }
2
public Grass(boolean flowers) { Random random = new Random(43287234); int w = 6; int h = 8; double ws = 1.0 / (w); double hs = 1.0 / (h); for (int x = 0; x < w; x++) { for (int z = 0; z < w; z++) { int y = h - 1; double xx = x *...
4
public Point getPoint(int index) { try { return Geometry.toPoint(getString(index)); } catch (Exception exception) { return new Point(); } }
1
public boolean equals(AState state) { if(this.getX() == state.getX() && this.getY() == state.getY()) return true; return false; }
2
public static int findCeeling(int[] input, int start, int end, int k) { if(k <= input[start]){ return input[start]; } if(k >= input[end]){ return -1; } int mid = (start +end)/2; if(input[mid]>=k && input[mid-1]< k){ return input[mid]; }...
7
public boolean move(Map map, Dot o) { if(o.curNode<o.node.size()) { if(!about(o.x,o.tx,o.speed) || !about(o.y,o.ty,o.speed)) { xcounter++; if(o.x!=0 && o.tx!=0) { if(!see(new Point((int)o.tx,(int)o.ty), new Point((int)o.x,(int)o.y),map)) { o.curNode=10000; System.out.println("i...
7
public void testGeoNamesK4() { // System.out.println("START"); int k = 4; File dataFile = new File(String.format("res/hamming/geonames_k%d_testdata.csv", k)); List<String> strings = DataReader.readDataAsStrings(dataFile); Trie t = new Trie(strings); t.buildMismatchesIndex(k); File queriesFile = new File...
7
public void rotateACW(Node root, int n) { if (root == null || n <= 0) { return; } int size = size(root); if (n == size) { // no need to rotate, as it will be the same System.out.println("List after rotating"); print(root); return; } if (n > size) { n = n % size; } System.out.printl...
6
public void paintDrawable(Drawable d,Graphics g){ if(d.getShapeType() == Drawable.LINE){ g.setColor(d.getBorderColor()); g.drawLine(d.getOriginX(), d.getOriginY(), d.getWidth() + d.getOriginX(), d.getOriginY()+d.getHeight()); }else if(d.getShapeType() == Drawable.RECTANGLE){ g.setColor(d.getFillingColor())...
6
@Test public void test_mult_matrix() { int a = 2; int b = 3; int c = 4; Matrix m1 = new MatrixArray(a,b); Matrix m2 = new MatrixArray(b,c); Matrix m3 = new MatrixArray(a,c); for(int i = 1; i <= a; i++){ for(int j = 1; j <= b; j++) m1.insert(i, j, (double)(2*i-j)); } for(int i = 1; i <= b...
4
public void removeFormVotingUser(int userId, int formId) throws InvalidVotingUserException { try { String q = "delete from ValidVoter where formId = ? and userId = ?;"; PreparedStatement st = conn.prepareStatement(q); st.setInt(1, formId); st.setInt(2, userId); ...
2
public void loadImage(final File fileToLoad) { controller.getImageBean().setStatus(ImageBean.LOADING); controller.setStatus("Loadin image..."); new SwingWorker<Boolean, Void>() { @Override protected Boolean doInBackground() throws Exception { try { loadedImage = ImageIO.read(fileToLoad); re...
3
@Override public void actionPerformed(ActionEvent ae) { switch (ae.getActionCommand()) { case "#language": languagePressed(); break; case "#controls": controlsPressed(); break; case "#aspectratio"...
4
public CmdDial() { setBounds(100, 100, 179, 171); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(new GridLayout(0, 2, 0, 0)); { JLabel lblUp = new JLabel("Up:"); conten...
6