text
stringlengths
14
410k
label
int32
0
9
public void testWithFieldAddWrapped5() { Partial test = createHourMinPartial(); try { test.withFieldAddWrapped(DurationFieldType.days(), 6); fail(); } catch (IllegalArgumentException ex) {} check(test, 10, 20); }
1
@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; } ...
8
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/da...
5
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
0
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.getOnderdele...
2
@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.ge...
6
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()); } }
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); } }
1
@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.nex...
4
@Test public void testCrossUncrossableEdgeInvalid(){ try { testEdgeUncrossable.cross(testTile1, null); fail("IllegalArgumentException Expected"); } catch (IllegalArgumentException e){ //exception expected } try { testEdgeUncrossable.cross(null, testCharacter); fail("IllegalArgumentException Ex...
3
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]); } ...
5
public Set<AndroidMethod> getSinks() { return sinks; }
0
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(); ...
9
private boolean alreadyListed (String[] list, String value) { for (String valueListed : list) { if (value.equals(valueListed)) { return true; } } return false; }
2
public void setG(byte[] value) { this.g = value; }
0
public static MainWindow getInstance() { if (instance == null) instance = new MainWindow(); return instance; }
1
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;...
2
@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; ...
9
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); ...
5
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++) { m...
7
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 e...
2
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(','); ...
7
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); } ...
3
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)); }
1
public static int sumWithCondition(List<Integer> numbers, Predicate<Integer> predicate) { return numbers.parallelStream() .filter(predicate) .mapToInt(i -> i) .sum(); }
0
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 Fix...
9
private static void addFontStyle(PacketBuilder buffer, char weight, int size) { if (weight != 'p') { buffer.writeByte(weight); } buffer.writeByte('g'); addSize(buffer, size); }
1
public void setRGB(int red, int green, int blue) { this.red = red; this.green = green; this.blue = blue; }
0
@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 &...
3
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) {...
9
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]++; cumulati...
3
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)) { ...
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(); } ...
6
@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 = fa...
7
@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...
5
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( leftP...
7
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; }
3
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()) {...
6
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); ...
4
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); ...
6
@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; }
5
public SHSMemberEntity getAccount() { return account; }
0
public void setStatus(Status status) { this.status = status; }
0
public LightingSword(){ this.name = Constants.LIGHTING_SWORD; this.attackScore = 50; this.attackSpeed = 20; // 20 % this.money = 4000; }
0
public void setName(String value) { this._name = value; }
0
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()); ...
2
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, ...
3
public String getLicenseDate() { return licenseDate; }
0
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(userP...
1
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 IllegalArgumentExce...
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); ...
3
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.STA...
9
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) ...
2
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; }
5
@Override public void windowIconified(WindowEvent e) { }
0
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)); ...
8
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.addClassIn...
1
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 Dis...
8
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...
6
@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...
9
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 { ...
8
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 (...
5
@RequestMapping(value = {"/EntidadBancaria/{idEntidadBancaria}"}, method = RequestMethod.PUT) public void update(HttpServletRequest httpRequest, HttpServletResponse httpServletResponse, @PathVariable("idEntidadBancaria") int idEntidadBancaria, @RequestBody String json) { try { ObjectMapper objec...
2
private void render() { switch(menu){ case main: break; case Game: RenderUtil.initGraphics(); RenderUtil.clearScreen(); game.render(); Window.render(); break; } }
2
@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_buildi...
9
public void setEncryptedValue(EncryptedDataType value) { this.encryptedValue = value; }
0
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 ...
9
@Override public void move() { if (alive) { if (stomache > 0) { addGlied(); stomache--; } super.move(); invertedBevoreMoves ++; } }
2
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); EventQueue.invokeLater(new Runnable() { public void run() { try { iXportSMS windo...
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)...
1
private String readInput() throws IOException { return this.keyboard.readLine(); }
0
@Override public void execute() { while (true) { showMessage(); showCurrencies(); try { moneyDialog.execute(); currencyDialog.execute("Introduzca la divisa a convertir: "); this.calculate.execute(); } catch (Exce...
3
protected void redo() throws CannotRedoException { if (insertionPoint >= maxInsertionPoint) { throw new CannotRedoException(); } if (insertionPoint < maxInsertionPoint) { AbstractEdit edit = edits.get(insertionPoint); edit.redo(); publishEdit(edit)...
4
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....
5
private BeverageFactory() { }
0
@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.ge...
7
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--; } }
1
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...
6
public User getUser(String username) { PreparedStatement statement = null; Connection connection = null; try { try { connection = data.getConnection(); statement = connection.prepareStatement("SELECT * FROM User WHERE username = ?"); statemen...
4
public static boolean isNumberType(Class<?> clazz) { return (clazz == Number.class || clazz.getSuperclass() == Number.class || isPrimitiveNumberType(clazz)); }
3
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 o...
9
* @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; ...
3
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...
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...
7
public void setValueMAC(byte[] value) { this.valueMAC = value; }
0
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 && nroCla...
9
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!"...
7
public static List<CommandeFournisseur> selectCommandeFournisseur() throws SQLException { String query = null; List<CommandeFournisseur> Commande = new ArrayList<CommandeFournisseur>(); ResultSet resultat; try { query = "SELECT * from COMMANDE_FOURNISSEUR "; Pre...
2
@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(...
8
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; cas...
9
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(pa...
6
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 = trans...
8
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 deseri...
5
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 =...
3
@Override public void add(Credit element) { //Добавляем запись в список getList().add(element); Statement statement = null; ResultSet result = null; try { //Создаем изменяемую выборку statement = getConnection().createStatement(ResultSet.TYPE_SCROLL_S...
2
public static boolean fullName(String name){ String[] temp = name.split(" "); if(name(temp[0])&&name(temp[1])) return true; return false; }
2
public static void choque() { if (terminochoque){ terminochoque = false; file = new File("."); ruta = file.getAbsolutePath(); Thread hilo = new Thread() { @Override public void run() { try { ...
3
public boolean retrack(Tracking tracking) throws AftershipAPIException,IOException,ParseException,JSONException{ String paramRequiredFields = tracking.getQueryRequiredFields().replaceFirst("&","?"); String url = "/trackings/"+tracking.getSlug()+ "/"+tracking.getTrackingNum...
2
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_com...
9
public synchronized static ConfigManager getInstance() { return m_instance; }
0