index
int64
1
4.83k
file_id
stringlengths
5
9
content
stringlengths
167
16.5k
repo
stringlengths
7
82
path
stringlengths
8
164
token_length
int64
72
4.23k
original_comment
stringlengths
11
2.7k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
142
16.5k
Inclusion
stringclasses
4 values
file-tokens-Qwen/Qwen2-7B
int64
64
3.93k
comment-tokens-Qwen/Qwen2-7B
int64
4
972
file-tokens-bigcode/starcoder2-7b
int64
74
3.98k
comment-tokens-bigcode/starcoder2-7b
int64
4
959
file-tokens-google/codegemma-7b
int64
56
3.99k
comment-tokens-google/codegemma-7b
int64
3
953
file-tokens-ibm-granite/granite-8b-code-base
int64
74
3.98k
comment-tokens-ibm-granite/granite-8b-code-base
int64
4
959
file-tokens-meta-llama/CodeLlama-7b-hf
int64
77
4.12k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
1.11k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
1,528
170472_3
/** * LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.synthesis.nl; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class DutchSynthesizerTest { @Test public final void testSynthesizeStringString() throws IOException { DutchSynthesizer synth = new DutchSynthesizer(); Assert.assertEquals(synth.synthesize(dummyToken("blablabla"), "blablabla").length, 0); Assert.assertEquals("[zwommen]", Arrays.toString(synth.synthesize(dummyToken("zwemmen"), "WKW:VLT:INF"))); // assertEquals("[Afro-Surinamers]", Arrays.toString(synth.synthesize(dummyToken("Afro-Surinamer"), "ZNW:MRV:DE_"))); Assert.assertEquals("[hebt, heeft]", Arrays.toString(synth.synthesize(dummyToken("hebben"), "WKW:TGW:3EP", true))); // with regular expressions Assert.assertEquals("[doorgeseind]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW:VTD:ONV", true))); // assertEquals("[doorseine, doorseinenden, doorseinend, doorseinende, doorsein, doorseint, doorseinen, doorseinde, doorseinden, doorgeseind, doorgeseinde]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW.*", true))); } }
STAMP-project/dspot-experiments
benchmark/validation/org/languagetool/synthesis/nl/DutchSynthesizerTest.java
650
// assertEquals("[doorseine, doorseinenden, doorseinend, doorseinende, doorsein, doorseint, doorseinen, doorseinde, doorseinden, doorgeseind, doorgeseinde]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW.*", true)));
line_comment
nl
/** * LanguageTool, a natural language style checker * Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.synthesis.nl; import java.io.IOException; import java.util.Arrays; import org.junit.Assert; import org.junit.Test; public class DutchSynthesizerTest { @Test public final void testSynthesizeStringString() throws IOException { DutchSynthesizer synth = new DutchSynthesizer(); Assert.assertEquals(synth.synthesize(dummyToken("blablabla"), "blablabla").length, 0); Assert.assertEquals("[zwommen]", Arrays.toString(synth.synthesize(dummyToken("zwemmen"), "WKW:VLT:INF"))); // assertEquals("[Afro-Surinamers]", Arrays.toString(synth.synthesize(dummyToken("Afro-Surinamer"), "ZNW:MRV:DE_"))); Assert.assertEquals("[hebt, heeft]", Arrays.toString(synth.synthesize(dummyToken("hebben"), "WKW:TGW:3EP", true))); // with regular expressions Assert.assertEquals("[doorgeseind]", Arrays.toString(synth.synthesize(dummyToken("doorseinen"), "WKW:VTD:ONV", true))); // assertEquals("[doorseine, doorseinenden,<SUF> } }
False
515
68
576
75
555
69
576
75
668
79
false
false
false
false
false
true
3,544
202145_1
package com.auce.monitor.clock; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import javax.swing.JComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.auce.auction.entity.Lot; import com.auce.auction.entity.Product; import com.auce.auction.entity.Supplier; import com.auce.auction.entity.Trader; import com.auce.auction.event.Purchase; import com.auce.auction.event.Run; public class ClockFace extends JComponent implements ClockModelListener { private static final long serialVersionUID = -4656800951220278621L; private static final double TWO_PI = 2.0 * Math.PI; private static final int MAX_VALUE = 100; private int diameter; private int centerX; private int centerY; private BufferedImage image; protected int tickSize; protected ClockModel model; protected Logger logger; protected Font smallFont; protected Font largeFont; public ClockFace( ClockModel model ) { this.logger = LoggerFactory.getLogger( this.getClass().getSimpleName() + "[" + model.getClock().getId() + "]" ); this.model = model; this.model.addClockModelListener( this ); this.tickSize = 10; } public ClockModel getModel () { return this.model; } public void paintComponent ( Graphics graphics ) { Graphics2D g2 = (Graphics2D)graphics; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); int w = getWidth(); int h = getHeight(); diameter = ( ( w < h ) ? w : h ); this.tickSize = (int)( 0.02 * diameter ); centerX = diameter / 2; centerY = diameter / 2; if ( this.image == null || this.image.getWidth() != w || this.image.getHeight() != h ) { int fontSize = (int)( diameter / 20.0 ); this.smallFont = new Font( "SansSerif", Font.BOLD, fontSize ); fontSize = (int)( diameter / 7.0 ); this.largeFont = new Font( "SansSerif", Font.BOLD, fontSize ); GraphicsConfiguration gc = g2.getDeviceConfiguration(); this.image = gc.createCompatibleImage( w, h, Transparency.TRANSLUCENT ); Graphics2D g = this.image.createGraphics(); g.setComposite( AlphaComposite.Clear ); g.fillRect( 0, 0, w, h ); g.setComposite( AlphaComposite.Src ); g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); g.setColor( Color.WHITE ); g.fillOval( 0, 0, diameter, diameter ); g.setComposite( AlphaComposite.SrcAtop ); Color color = Color.LIGHT_GRAY; g.setPaint( new GradientPaint( 0, 0, color, 0, h, Color.WHITE ) ); g.fillOval( 0, 0, diameter, diameter ); int radius = diameter / 2; for ( int i = 0; i < MAX_VALUE; i++ ) { drawTick( g, i / (double)MAX_VALUE, radius - this.tickSize, null ); if ( i % 5 == 0 ) { drawTick( g, i / (double)MAX_VALUE, radius - (int)( this.tickSize * 2.5 ), Color.DARK_GRAY ); } } if ( this.model.getRun() != null ) { this.drawInfo( g ); } g.dispose(); g2.drawImage( this.image, 0, 0, null ); } else { g2.drawImage( this.image, null, 0, 0 ); } this.drawValue( g2 ); } private void drawText ( Graphics2D g2, String text, int position ) { Rectangle2D r = this.smallFont.getStringBounds( text, g2.getFontRenderContext() ); g2.drawString( text, centerX - (int)( (double)r.getWidth() / 2.0 ), centerY + (int)( (double)r.getHeight() / 2.0 ) + (int)( position * r.getHeight() ) ); } private void drawInfo ( Graphics2D g2 ) { g2.setColor( Color.DARK_GRAY ); g2.setFont( this.smallFont ); Run auction = this.model.getRun(); Lot lot = auction.getLot(); if ( lot != null ) { Supplier supplier = lot.getSupplier(); if ( supplier != null ) { this.drawText( g2, supplier.getName(), -3 ); } Product product = lot.getProduct(); if ( product != null ) { StringBuilder sb = new StringBuilder(); sb.append( Integer.toString( lot.getQuantity() ) ); sb.append( " units " ); sb.append( auction.getLot().getProduct().getName() ); this.drawText( g2, sb.toString(), -4 ); } StringBuilder sb = new StringBuilder(); sb = new StringBuilder(); sb.append( "Partij " ); sb.append( lot.getId() ); this.drawText( g2, sb.toString(), -5 ); } Purchase purchase = this.model.getPurchase(); if ( purchase != null ) { String traderId = "unknown"; Trader trader = purchase.getTrader(); if ( trader != null ) { traderId = purchase.getTrader().getId(); } this.drawText( g2, traderId, 3 ); this.drawText( g2, purchase.getQuantity() + " units", 4 ); } // else if ( this.model.getValue() == 0 ) // { // this.drawText( g2, "doorgedraaid", 3 ); // this.drawText( g2, auction.getUnits() + " units", 4 ); // } } private void drawValue ( Graphics2D g2 ) { int value = this.model.getValue(); String text = Integer.toString( value ); g2.setColor( this.model.getColor() ); g2.setFont( this.largeFont ); Rectangle2D r = this.largeFont.getStringBounds( text, g2.getFontRenderContext() ); g2.drawString( text, centerX - (int)( (double)r.getWidth() / 2.0 ), centerY + (int)( (double)r.getHeight() / 4.0 ) ); int handMax = this.diameter / 2; double percent = ( (double)value ) / (double)MAX_VALUE; drawTick( g2, percent, handMax - this.tickSize, Color.RED ); } private void drawTick ( Graphics2D g2, double percent, int minRadius, Color color ) { double radians = ( 0.5 - percent ) * TWO_PI; double sine = Math.sin( radians ); double cosine = Math.cos( radians ); int dxmin = centerX + (int)( minRadius * sine ); int dymin = centerY + (int)( minRadius * cosine ); if ( color != null ) { g2.setColor( color ); g2.fillOval( dxmin - 5, dymin - 5, tickSize + 1, tickSize + 1 ); } else { g2.setColor( Color.WHITE ); g2.fillOval( dxmin - 5, dymin - 5, tickSize + 1, tickSize + 1 ); g2.setColor( Color.BLACK ); g2.drawOval( dxmin - 5, dymin - 5, tickSize, tickSize ); } } public void clockValueChanged ( ClockModelEvent event ) { Run auction = this.model.getRun(); if ( auction != null ) { if ( this.model.getValue() == 0 ) { this.image = null; } } this.repaint(); } public void clockAuctionChanged ( ClockModelEvent event ) { if ( this.model.getRun() != null ) { this.image = null; this.repaint(); } } }
mamersfo/DutchAuction
monitor/src/main/java/com/auce/monitor/clock/ClockFace.java
2,523
// this.drawText( g2, "doorgedraaid", 3 );
line_comment
nl
package com.auce.monitor.clock; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.RenderingHints; import java.awt.Transparency; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import javax.swing.JComponent; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.auce.auction.entity.Lot; import com.auce.auction.entity.Product; import com.auce.auction.entity.Supplier; import com.auce.auction.entity.Trader; import com.auce.auction.event.Purchase; import com.auce.auction.event.Run; public class ClockFace extends JComponent implements ClockModelListener { private static final long serialVersionUID = -4656800951220278621L; private static final double TWO_PI = 2.0 * Math.PI; private static final int MAX_VALUE = 100; private int diameter; private int centerX; private int centerY; private BufferedImage image; protected int tickSize; protected ClockModel model; protected Logger logger; protected Font smallFont; protected Font largeFont; public ClockFace( ClockModel model ) { this.logger = LoggerFactory.getLogger( this.getClass().getSimpleName() + "[" + model.getClock().getId() + "]" ); this.model = model; this.model.addClockModelListener( this ); this.tickSize = 10; } public ClockModel getModel () { return this.model; } public void paintComponent ( Graphics graphics ) { Graphics2D g2 = (Graphics2D)graphics; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); int w = getWidth(); int h = getHeight(); diameter = ( ( w < h ) ? w : h ); this.tickSize = (int)( 0.02 * diameter ); centerX = diameter / 2; centerY = diameter / 2; if ( this.image == null || this.image.getWidth() != w || this.image.getHeight() != h ) { int fontSize = (int)( diameter / 20.0 ); this.smallFont = new Font( "SansSerif", Font.BOLD, fontSize ); fontSize = (int)( diameter / 7.0 ); this.largeFont = new Font( "SansSerif", Font.BOLD, fontSize ); GraphicsConfiguration gc = g2.getDeviceConfiguration(); this.image = gc.createCompatibleImage( w, h, Transparency.TRANSLUCENT ); Graphics2D g = this.image.createGraphics(); g.setComposite( AlphaComposite.Clear ); g.fillRect( 0, 0, w, h ); g.setComposite( AlphaComposite.Src ); g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); g.setColor( Color.WHITE ); g.fillOval( 0, 0, diameter, diameter ); g.setComposite( AlphaComposite.SrcAtop ); Color color = Color.LIGHT_GRAY; g.setPaint( new GradientPaint( 0, 0, color, 0, h, Color.WHITE ) ); g.fillOval( 0, 0, diameter, diameter ); int radius = diameter / 2; for ( int i = 0; i < MAX_VALUE; i++ ) { drawTick( g, i / (double)MAX_VALUE, radius - this.tickSize, null ); if ( i % 5 == 0 ) { drawTick( g, i / (double)MAX_VALUE, radius - (int)( this.tickSize * 2.5 ), Color.DARK_GRAY ); } } if ( this.model.getRun() != null ) { this.drawInfo( g ); } g.dispose(); g2.drawImage( this.image, 0, 0, null ); } else { g2.drawImage( this.image, null, 0, 0 ); } this.drawValue( g2 ); } private void drawText ( Graphics2D g2, String text, int position ) { Rectangle2D r = this.smallFont.getStringBounds( text, g2.getFontRenderContext() ); g2.drawString( text, centerX - (int)( (double)r.getWidth() / 2.0 ), centerY + (int)( (double)r.getHeight() / 2.0 ) + (int)( position * r.getHeight() ) ); } private void drawInfo ( Graphics2D g2 ) { g2.setColor( Color.DARK_GRAY ); g2.setFont( this.smallFont ); Run auction = this.model.getRun(); Lot lot = auction.getLot(); if ( lot != null ) { Supplier supplier = lot.getSupplier(); if ( supplier != null ) { this.drawText( g2, supplier.getName(), -3 ); } Product product = lot.getProduct(); if ( product != null ) { StringBuilder sb = new StringBuilder(); sb.append( Integer.toString( lot.getQuantity() ) ); sb.append( " units " ); sb.append( auction.getLot().getProduct().getName() ); this.drawText( g2, sb.toString(), -4 ); } StringBuilder sb = new StringBuilder(); sb = new StringBuilder(); sb.append( "Partij " ); sb.append( lot.getId() ); this.drawText( g2, sb.toString(), -5 ); } Purchase purchase = this.model.getPurchase(); if ( purchase != null ) { String traderId = "unknown"; Trader trader = purchase.getTrader(); if ( trader != null ) { traderId = purchase.getTrader().getId(); } this.drawText( g2, traderId, 3 ); this.drawText( g2, purchase.getQuantity() + " units", 4 ); } // else if ( this.model.getValue() == 0 ) // { // this.drawText( g2,<SUF> // this.drawText( g2, auction.getUnits() + " units", 4 ); // } } private void drawValue ( Graphics2D g2 ) { int value = this.model.getValue(); String text = Integer.toString( value ); g2.setColor( this.model.getColor() ); g2.setFont( this.largeFont ); Rectangle2D r = this.largeFont.getStringBounds( text, g2.getFontRenderContext() ); g2.drawString( text, centerX - (int)( (double)r.getWidth() / 2.0 ), centerY + (int)( (double)r.getHeight() / 4.0 ) ); int handMax = this.diameter / 2; double percent = ( (double)value ) / (double)MAX_VALUE; drawTick( g2, percent, handMax - this.tickSize, Color.RED ); } private void drawTick ( Graphics2D g2, double percent, int minRadius, Color color ) { double radians = ( 0.5 - percent ) * TWO_PI; double sine = Math.sin( radians ); double cosine = Math.cos( radians ); int dxmin = centerX + (int)( minRadius * sine ); int dymin = centerY + (int)( minRadius * cosine ); if ( color != null ) { g2.setColor( color ); g2.fillOval( dxmin - 5, dymin - 5, tickSize + 1, tickSize + 1 ); } else { g2.setColor( Color.WHITE ); g2.fillOval( dxmin - 5, dymin - 5, tickSize + 1, tickSize + 1 ); g2.setColor( Color.BLACK ); g2.drawOval( dxmin - 5, dymin - 5, tickSize, tickSize ); } } public void clockValueChanged ( ClockModelEvent event ) { Run auction = this.model.getRun(); if ( auction != null ) { if ( this.model.getValue() == 0 ) { this.image = null; } } this.repaint(); } public void clockAuctionChanged ( ClockModelEvent event ) { if ( this.model.getRun() != null ) { this.image = null; this.repaint(); } } }
False
1,910
17
2,299
18
2,274
17
2,299
18
2,842
20
false
false
false
false
false
true
3,416
159873_0
package be.kwakeroni.scratch.tv; /** * (C) 2016 Maarten Van Puymbroeck */ public enum Dag { MAANDAG, DINSDAG, WOENSDAG, DONDERDAG, VRIJDAG, ZATERDAG, ZONDAG; }
kwakeroni/BusinessParameters
scratch/src/main/java/be/kwakeroni/scratch/tv/Dag.java
78
/** * (C) 2016 Maarten Van Puymbroeck */
block_comment
nl
package be.kwakeroni.scratch.tv; /** * (C) 2016 Maarten<SUF>*/ public enum Dag { MAANDAG, DINSDAG, WOENSDAG, DONDERDAG, VRIJDAG, ZATERDAG, ZONDAG; }
False
68
19
78
22
70
18
78
22
85
21
false
false
false
false
false
true
107
169888_6
public class E_Combining_Bonus { public static void main(String[] args) { // Hieronder zie je een array. We gaan arrays later behandelen, voor nu hoef je maar 3 dingen te weten. // 1. De array is een lijstje van nummers // 2. Je kunt de lengte van een Array opvragen met de length property (numbers.length) // 3. Je kunt een individueel element ophalen met de index (numbers[0] == 4, numbers[1] == 3) int[] numbers = {7, 4, 1, 67, 2, 4, 6, 2, 345, 5, 52, 1, 2415, 7, 5, 178, 14, 4}; // // Combination 1 // // implementeer een forloop die alle even nummers print. Je gebruikt hiervoor ook een if statement for (int i = 0; i < numbers.length; i++) { if (numbers[i] % 2 == 0) { System.out.println(numbers[i]); } } // // Combination 2 // // Implementeer een whileloop de nummers in de lijst optelt tot het resultaat groter is dan 400. Bonus, zorg ook dat de index nooit groter kan worden dan de lengte van de array. // Je hebt ook een index nodig voor de array (int index = 0;) en een accumulator voor het resultaat (int result = 0;). Deze index en accumulator kun je in de while loop muteren. int index = 0; int accumulator = 0; //add while while (index < numbers.length && accumulator <= 400) { accumulator += numbers[index]; } System.out.println(accumulator); } }
Aphelion-im/EdHub-Programmeren-met-Java-opdrachten
H3.5 - Controlflow-constructies/backend-java-controlflow/src/main/java/E_Combining_Bonus.java
482
// Je hebt ook een index nodig voor de array (int index = 0;) en een accumulator voor het resultaat (int result = 0;). Deze index en accumulator kun je in de while loop muteren.
line_comment
nl
public class E_Combining_Bonus { public static void main(String[] args) { // Hieronder zie je een array. We gaan arrays later behandelen, voor nu hoef je maar 3 dingen te weten. // 1. De array is een lijstje van nummers // 2. Je kunt de lengte van een Array opvragen met de length property (numbers.length) // 3. Je kunt een individueel element ophalen met de index (numbers[0] == 4, numbers[1] == 3) int[] numbers = {7, 4, 1, 67, 2, 4, 6, 2, 345, 5, 52, 1, 2415, 7, 5, 178, 14, 4}; // // Combination 1 // // implementeer een forloop die alle even nummers print. Je gebruikt hiervoor ook een if statement for (int i = 0; i < numbers.length; i++) { if (numbers[i] % 2 == 0) { System.out.println(numbers[i]); } } // // Combination 2 // // Implementeer een whileloop de nummers in de lijst optelt tot het resultaat groter is dan 400. Bonus, zorg ook dat de index nooit groter kan worden dan de lengte van de array. // Je hebt<SUF> int index = 0; int accumulator = 0; //add while while (index < numbers.length && accumulator <= 400) { accumulator += numbers[index]; } System.out.println(accumulator); } }
True
431
46
458
50
454
45
458
50
501
51
false
false
false
false
false
true
1,230
138974_2
package be.odisee; /* Requirements * a) We simuleren een broodrooster welke gedurende 1 minuut roostert als we het roosteren starten * => klasse Broodrooster, methode Broodrooster.start() * b) De broodrooster kan 2 sneden tegelijk roosteren => Broodrooster.aantalSneden * c) Een temperatuurregelknop op het apparaat bepaalt hoeveel weerstand het apparaat levert => Broodrooster.weerstand */ /** * Deze klasse stelt een broodrooster voor met 1 knop: een temperatuurregelaar */ public class Broodrooster { /* variabele die het aantal sneden bijhoudt */ private final Integer aantalSneden=2; /** * Req b) Bepaalt hoeveel sneden tegelijk geroosterd worden */ public void getAantalSneden() {} /* variabele die de weerstand bijhoudt */ private Double weerstand; /** * Req c) De elektrische weerstand zoals bepaald door de temperatuurregelaar * */ public void setWeerstand(Double weerstand) {} /** * Req a) Start het roosteren gedurende 1 minuut */ public void start() { } }
OdiseeSEF2324/Leerstof-klas-1-2
Les 2/Demos/Broodrooster/src/main/java/be/odisee/Broodrooster.java
358
/* variabele die het aantal sneden bijhoudt */
block_comment
nl
package be.odisee; /* Requirements * a) We simuleren een broodrooster welke gedurende 1 minuut roostert als we het roosteren starten * => klasse Broodrooster, methode Broodrooster.start() * b) De broodrooster kan 2 sneden tegelijk roosteren => Broodrooster.aantalSneden * c) Een temperatuurregelknop op het apparaat bepaalt hoeveel weerstand het apparaat levert => Broodrooster.weerstand */ /** * Deze klasse stelt een broodrooster voor met 1 knop: een temperatuurregelaar */ public class Broodrooster { /* variabele die het<SUF>*/ private final Integer aantalSneden=2; /** * Req b) Bepaalt hoeveel sneden tegelijk geroosterd worden */ public void getAantalSneden() {} /* variabele die de weerstand bijhoudt */ private Double weerstand; /** * Req c) De elektrische weerstand zoals bepaald door de temperatuurregelaar * */ public void setWeerstand(Double weerstand) {} /** * Req a) Start het roosteren gedurende 1 minuut */ public void start() { } }
True
319
14
347
14
289
12
347
14
363
14
false
false
false
false
false
true
3,116
48249_1
import java.util.Arrays; /** * */ public class DemoOrdenación { /** * Constructor */ public DemoOrdenación() { } /** * Ordenar en orden ascendente */ public void ordenarSeleccionDirecta(int[] array) { for (int i = 0; i < array.length - 1; i++) { int posmin = i; for (int j = i + 1; j < array.length; j++) { if (array[j] < array[posmin]) { posmin = j; } } int aux = array[posmin]; array[posmin] = array[i]; array[i] = aux; } System.out.println(Arrays.toString(array)); } /** * Ordenar en orden ascendente */ public void ordenarInsercionDirecta(int[] array) { for (int i = 1; i < array.length; i++) { int aux = array[i]; int j = i - 1; while (j >= 0 && array[j] > aux) { array[j + 1] = array[j]; j--; } array[j + 1] = aux; } System.out.println(Arrays.toString(array)); } /** * Ordenar en orden ascendente */ public void ordenarBurbuja(int[] array) { for (int i = 1; i < array.length; i++) { for (int j = 0; j < array.length - i; j++) { if (array[j] > array[j + 1]) { int aux = array[j]; array[j] = array[j + 1]; array[j + 1] = aux; } } } System.out.println(Arrays.toString(array)); } }
iremoncdam1/Programacion-DAM1-2021-2022
UT5/Ejemplos UT5 Arrays/DemoOrdenación.java
546
/** * Ordenar en orden ascendente */
block_comment
nl
import java.util.Arrays; /** * */ public class DemoOrdenación { /** * Constructor */ public DemoOrdenación() { } /** * Ordenar en orden<SUF>*/ public void ordenarSeleccionDirecta(int[] array) { for (int i = 0; i < array.length - 1; i++) { int posmin = i; for (int j = i + 1; j < array.length; j++) { if (array[j] < array[posmin]) { posmin = j; } } int aux = array[posmin]; array[posmin] = array[i]; array[i] = aux; } System.out.println(Arrays.toString(array)); } /** * Ordenar en orden ascendente */ public void ordenarInsercionDirecta(int[] array) { for (int i = 1; i < array.length; i++) { int aux = array[i]; int j = i - 1; while (j >= 0 && array[j] > aux) { array[j + 1] = array[j]; j--; } array[j + 1] = aux; } System.out.println(Arrays.toString(array)); } /** * Ordenar en orden ascendente */ public void ordenarBurbuja(int[] array) { for (int i = 1; i < array.length; i++) { for (int j = 0; j < array.length - i; j++) { if (array[j] > array[j + 1]) { int aux = array[j]; array[j] = array[j + 1]; array[j + 1] = aux; } } } System.out.println(Arrays.toString(array)); } }
False
415
13
463
14
515
14
463
14
544
16
false
false
false
false
false
true
120
140838_0
package nl.novi.jp.methods.junior; /** * Uitdagende opdracht! * Een stuk van de code is uitgecommentarieerd, omdat deze pas gaat werken, wanneer de methode doTransaction afgemaakt * is. * <p> * Maak doTransaction af. Deze moet twee waardes accepteren (welk datatype?). Een waarde is het banksaldo voor de * transactie, de andere waarde is de waarde van de transactie. * <p> * Wanneer de waarde van de transactie negatief is, gaat het om het opnemen (withdraw) van geld. Deze methode dient dan * ook aangeroepen te worden. Wanneer deze positief is, gaat het om geld storten (deposit). Dan dient de deposit methode * aangeroepen te worden. */ public class JuniorFour { public static void main(String[] args) { doTransaction(1000, -200); doTransaction(123, 3445); } public static void doTransaction(int banksaldo, int waardeTransactie) { if (waardeTransactie > 0) { deposit(banksaldo, waardeTransactie); } else { withdraw(banksaldo, waardeTransactie); } } public static void deposit(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user deposits: " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } public static void withdraw(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user withdraws " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } }
Aphelion-im/SD-BE-JP-methods-opdracht
src/nl/novi/jp/methods/junior/JuniorFour.java
476
/** * Uitdagende opdracht! * Een stuk van de code is uitgecommentarieerd, omdat deze pas gaat werken, wanneer de methode doTransaction afgemaakt * is. * <p> * Maak doTransaction af. Deze moet twee waardes accepteren (welk datatype?). Een waarde is het banksaldo voor de * transactie, de andere waarde is de waarde van de transactie. * <p> * Wanneer de waarde van de transactie negatief is, gaat het om het opnemen (withdraw) van geld. Deze methode dient dan * ook aangeroepen te worden. Wanneer deze positief is, gaat het om geld storten (deposit). Dan dient de deposit methode * aangeroepen te worden. */
block_comment
nl
package nl.novi.jp.methods.junior; /** * Uitdagende opdracht! <SUF>*/ public class JuniorFour { public static void main(String[] args) { doTransaction(1000, -200); doTransaction(123, 3445); } public static void doTransaction(int banksaldo, int waardeTransactie) { if (waardeTransactie > 0) { deposit(banksaldo, waardeTransactie); } else { withdraw(banksaldo, waardeTransactie); } } public static void deposit(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user deposits: " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } public static void withdraw(int bankAccountBalance, int amount) { int updatedBalance = bankAccountBalance + amount; System.out.println("The user withdraws " + amount + " euro."); System.out.println("The new balance is: " + updatedBalance); } }
False
418
183
475
211
423
159
475
211
511
208
false
false
false
false
false
true
2,773
172277_5
/* * Copyright (C) 2012 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.admin.stripes; import java.text.SimpleDateFormat; import java.util.*; import javax.annotation.security.RolesAllowed; import javax.persistence.NoResultException; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.*; import nl.b3p.viewer.config.ClobElement; import nl.b3p.viewer.config.app.*; import nl.b3p.viewer.config.security.Group; import nl.b3p.viewer.config.security.User; import nl.b3p.viewer.config.services.BoundingBox; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @UrlBinding("/action/applicationsettings/") @StrictBinding @RolesAllowed({Group.ADMIN,Group.APPLICATION_ADMIN}) public class ApplicationSettingsActionBean extends ApplicationActionBean { private static final Log log = LogFactory.getLog(ApplicationSettingsActionBean.class); private static final String JSP = "/WEB-INF/jsp/application/applicationSettings.jsp"; private static final String DEFAULT_SPRITE = "/resources/images/default_sprite.png"; @Validate private String name; @Validate private String version; @Validate private String owner; @Validate private boolean authenticatedRequired; @Validate private String mashupName; @Validate private Map<String,ClobElement> details = new HashMap<String,ClobElement>(); @ValidateNestedProperties({ @Validate(field="minx", maxlength=255), @Validate(field="miny", maxlength=255), @Validate(field="maxx", maxlength=255), @Validate(field="maxy", maxlength=255) }) private BoundingBox startExtent; @ValidateNestedProperties({ @Validate(field="minx", maxlength=255), @Validate(field="miny", maxlength=255), @Validate(field="maxx", maxlength=255), @Validate(field="maxy", maxlength=255) }) private BoundingBox maxExtent; //<editor-fold defaultstate="collapsed" desc="getters & setters"> public Map<String,ClobElement> getDetails() { return details; } public void setDetails(Map<String, ClobElement> details) { this.details = details; } public boolean getAuthenticatedRequired() { return authenticatedRequired; } public void setAuthenticatedRequired(boolean authenticatedRequired) { this.authenticatedRequired = authenticatedRequired; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public BoundingBox getStartExtent() { return startExtent; } public void setStartExtent(BoundingBox startExtent) { this.startExtent = startExtent; } public BoundingBox getMaxExtent() { return maxExtent; } public void setMaxExtent(BoundingBox maxExtent) { this.maxExtent = maxExtent; } public String getMashupName() { return mashupName; } public void setMashupName(String mashupName) { this.mashupName = mashupName; } //</editor-fold> @DefaultHandler @DontValidate public Resolution view(){ if(application != null){ details = application.getDetails(); if(application.getOwner() != null){ owner = application.getOwner().getUsername(); } startExtent = application.getStartExtent(); maxExtent = application.getMaxExtent(); name = application.getName(); version = application.getVersion(); authenticatedRequired = application.isAuthenticatedRequired(); } // DEFAULT VALUES if(!details.containsKey("iconSprite")) { details.put("iconSprite", new ClobElement(DEFAULT_SPRITE)); } if(!details.containsKey("stylesheetMetadata")) { // TODO: Default value stylesheet metadata details.put("stylesheetMetadata", new ClobElement("")); } if(!details.containsKey("stylesheetPrint")) { // TODO: Default value stylesheet printen details.put("stylesheetPrint", new ClobElement("")); } return new ForwardResolution(JSP); } @DontValidate public Resolution newApplication(){ application = null; applicationId = -1L; // DEFAULT VALUES details.put("iconSprite", new ClobElement(DEFAULT_SPRITE)); // TODO: Default value stylesheet metadata details.put("stylesheetMetadata", new ClobElement("")); // TODO: Default value stylesheet printen details.put("stylesheetPrint", new ClobElement("")); return new ForwardResolution(JSP); } @DontBind public Resolution cancel() { return new ForwardResolution(JSP); } public Resolution save() { if(application == null){ application = new Application(); /* * A new application always has a root and a background level. */ Level root = new Level(); root.setName("Applicatie"); Level background = new Level(); background.setName("Achtergrond"); background.setBackground(true); root.getChildren().add(background); background.setParent(root); Stripersist.getEntityManager().persist(background); Stripersist.getEntityManager().persist(root); application.setRoot(root); } bindAppProperties(); Stripersist.getEntityManager().persist(application); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Applicatie is opgeslagen")); setApplication(application); return new ForwardResolution(JSP); } /* XXX */ private void bindAppProperties() { application.setName(name); application.setVersion(version); if(owner != null){ User appOwner = Stripersist.getEntityManager().find(User.class, owner); application.setOwner(appOwner); } application.setStartExtent(startExtent); application.setMaxExtent(maxExtent); application.setAuthenticatedRequired(authenticatedRequired); application.getDetails().putAll(details); } @ValidationMethod(on="save") public void validate(ValidationErrors errors) throws Exception { if(name == null) { errors.add("name", new SimpleError("Naam is verplicht")); return; } try { Long foundId = null; if(version == null){ foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version is null") .setMaxResults(1) .setParameter("name", name) .getSingleResult(); }else{ foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version = :version") .setMaxResults(1) .setParameter("name", name) .setParameter("version", version) .getSingleResult(); } if(application != null && application.getId() != null){ if( !foundId.equals(application.getId()) ){ errors.add("name", new SimpleError("Naam en versie moeten een unieke combinatie vormen.")); } }else{ errors.add("name", new SimpleError("Naam en versie moeten een unieke combinatie vormen.")); } } catch(NoResultException nre) { // name version combination is unique } /* * Check if owner is an excisting user */ if(owner != null){ try { User appOwner = Stripersist.getEntityManager().find(User.class, owner); if(appOwner == null){ errors.add("owner", new SimpleError("Gebruiker met deze naam bestaat niet.")); } } catch(NoResultException nre) { errors.add("owner", new SimpleError("Gebruiker met deze naam bestaat niet.")); } } if(startExtent != null){ if(startExtent.getMinx() == null || startExtent.getMiny() == null || startExtent.getMaxx() == null || startExtent.getMaxy() == null ){ errors.add("startExtent", new SimpleError("Alle velden van de start extentie moeten ingevult worden.")); } } if(maxExtent != null){ if(maxExtent.getMinx() == null || maxExtent.getMiny() == null || maxExtent.getMaxx() == null || maxExtent.getMaxy() == null ){ errors.add("maxExtent", new SimpleError("Alle velden van de max extentie moeten ingevult worden.")); } } } public Resolution copy() throws Exception { try { Object o = Stripersist.getEntityManager().createQuery("select 1 from Application where name = :name") .setMaxResults(1) .setParameter("name", name) .getSingleResult(); getContext().getMessages().add(new SimpleMessage("Kan niet kopieren; applicatie met naam \"{0}\" bestaat al", name)); return new RedirectResolution(this.getClass()); } catch(NoResultException nre) { // name is unique } try { bindAppProperties(); Application copy = application.deepCopy(); // don't save changes to original app Stripersist.getEntityManager().detach(application); Stripersist.getEntityManager().persist(copy); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Applicatie is gekopieerd")); setApplication(copy); return new RedirectResolution(this.getClass()); } catch(Exception e) { log.error(String.format("Error copying application #%d named %s %swith new name %s", application.getId(), application.getName(), application.getVersion() == null ? "" : "v" + application.getVersion() + " ", name), e); String ex = e.toString(); Throwable cause = e.getCause(); while(cause != null) { ex += ";\n<br>" + cause.toString(); cause = cause.getCause(); } getContext().getValidationErrors().addGlobalError(new SimpleError("Fout bij kopieren applicatie: " + ex)); return new ForwardResolution(JSP); } } public Resolution mashup(){ ValidationErrors errors = context.getValidationErrors(); try { Level root = application.getRoot(); // Prevent copy-ing levels/layers application.setRoot(null); Application mashup = application.deepCopy(); Stripersist.getEntityManager().detach(application); mashup.setRoot(root); mashup.getDetails().put("isMashup", new ClobElement(Boolean.TRUE + "")); mashup.setName(mashup.getName() + "_" + mashupName); Stripersist.getEntityManager().persist(mashup); Stripersist.getEntityManager().getTransaction().commit(); setApplication(mashup); } catch (Exception ex) { errors.add("Fout", new SimpleError("De mashup kan niet worden gemaakt.")); } return new RedirectResolution(ApplicationSettingsActionBean.class); } public Resolution publish (){ // Find current published application and make backup try { Application oldPublished = (Application)Stripersist.getEntityManager().createQuery("from Application where name = :name AND version IS null") .setMaxResults(1) .setParameter("name", name) .getSingleResult(); Date nowDate = new Date(System.currentTimeMillis()); SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(); sdf.applyPattern("HH-mm_dd-MM-yyyy"); String now = sdf.format(nowDate); String uniqueVersion = findUniqueVersion(name, "B_"+now ); oldPublished.setVersion(uniqueVersion); Stripersist.getEntityManager().persist(oldPublished); Stripersist.getEntityManager().getTransaction().commit(); } catch(NoResultException nre) { } application.setVersion(null); Stripersist.getEntityManager().persist(application); Stripersist.getEntityManager().getTransaction().commit(); setApplication(null); return new RedirectResolution(ChooseApplicationActionBean.class); } /** * Checks if a Application with given name already exists and if needed * returns name with sequence number in brackets added to make it unique. * @param name Name to make unique * @return A unique name for a FeatureSource */ public static String findUniqueVersion(String name, String version) { int uniqueCounter = 0; while(true) { String testVersion; if(uniqueCounter == 0) { testVersion = version; } else { testVersion = version + " (" + uniqueCounter + ")"; } try { Stripersist.getEntityManager().createQuery("select 1 from Application where name = :name AND version = :version") .setParameter("name", name) .setParameter("version", testVersion) .setMaxResults(1) .getSingleResult(); uniqueCounter++; } catch(NoResultException nre) { version = testVersion; break; } } return version; } }
geertplaisier/flamingo
viewer-admin/src/main/java/nl/b3p/viewer/admin/stripes/ApplicationSettingsActionBean.java
4,051
// TODO: Default value stylesheet metadata
line_comment
nl
/* * Copyright (C) 2012 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.admin.stripes; import java.text.SimpleDateFormat; import java.util.*; import javax.annotation.security.RolesAllowed; import javax.persistence.NoResultException; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.*; import nl.b3p.viewer.config.ClobElement; import nl.b3p.viewer.config.app.*; import nl.b3p.viewer.config.security.Group; import nl.b3p.viewer.config.security.User; import nl.b3p.viewer.config.services.BoundingBox; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.stripesstuff.stripersist.Stripersist; /** * * @author Jytte Schaeffer */ @UrlBinding("/action/applicationsettings/") @StrictBinding @RolesAllowed({Group.ADMIN,Group.APPLICATION_ADMIN}) public class ApplicationSettingsActionBean extends ApplicationActionBean { private static final Log log = LogFactory.getLog(ApplicationSettingsActionBean.class); private static final String JSP = "/WEB-INF/jsp/application/applicationSettings.jsp"; private static final String DEFAULT_SPRITE = "/resources/images/default_sprite.png"; @Validate private String name; @Validate private String version; @Validate private String owner; @Validate private boolean authenticatedRequired; @Validate private String mashupName; @Validate private Map<String,ClobElement> details = new HashMap<String,ClobElement>(); @ValidateNestedProperties({ @Validate(field="minx", maxlength=255), @Validate(field="miny", maxlength=255), @Validate(field="maxx", maxlength=255), @Validate(field="maxy", maxlength=255) }) private BoundingBox startExtent; @ValidateNestedProperties({ @Validate(field="minx", maxlength=255), @Validate(field="miny", maxlength=255), @Validate(field="maxx", maxlength=255), @Validate(field="maxy", maxlength=255) }) private BoundingBox maxExtent; //<editor-fold defaultstate="collapsed" desc="getters & setters"> public Map<String,ClobElement> getDetails() { return details; } public void setDetails(Map<String, ClobElement> details) { this.details = details; } public boolean getAuthenticatedRequired() { return authenticatedRequired; } public void setAuthenticatedRequired(boolean authenticatedRequired) { this.authenticatedRequired = authenticatedRequired; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public BoundingBox getStartExtent() { return startExtent; } public void setStartExtent(BoundingBox startExtent) { this.startExtent = startExtent; } public BoundingBox getMaxExtent() { return maxExtent; } public void setMaxExtent(BoundingBox maxExtent) { this.maxExtent = maxExtent; } public String getMashupName() { return mashupName; } public void setMashupName(String mashupName) { this.mashupName = mashupName; } //</editor-fold> @DefaultHandler @DontValidate public Resolution view(){ if(application != null){ details = application.getDetails(); if(application.getOwner() != null){ owner = application.getOwner().getUsername(); } startExtent = application.getStartExtent(); maxExtent = application.getMaxExtent(); name = application.getName(); version = application.getVersion(); authenticatedRequired = application.isAuthenticatedRequired(); } // DEFAULT VALUES if(!details.containsKey("iconSprite")) { details.put("iconSprite", new ClobElement(DEFAULT_SPRITE)); } if(!details.containsKey("stylesheetMetadata")) { // TODO: Default value stylesheet metadata details.put("stylesheetMetadata", new ClobElement("")); } if(!details.containsKey("stylesheetPrint")) { // TODO: Default value stylesheet printen details.put("stylesheetPrint", new ClobElement("")); } return new ForwardResolution(JSP); } @DontValidate public Resolution newApplication(){ application = null; applicationId = -1L; // DEFAULT VALUES details.put("iconSprite", new ClobElement(DEFAULT_SPRITE)); // TODO: Default<SUF> details.put("stylesheetMetadata", new ClobElement("")); // TODO: Default value stylesheet printen details.put("stylesheetPrint", new ClobElement("")); return new ForwardResolution(JSP); } @DontBind public Resolution cancel() { return new ForwardResolution(JSP); } public Resolution save() { if(application == null){ application = new Application(); /* * A new application always has a root and a background level. */ Level root = new Level(); root.setName("Applicatie"); Level background = new Level(); background.setName("Achtergrond"); background.setBackground(true); root.getChildren().add(background); background.setParent(root); Stripersist.getEntityManager().persist(background); Stripersist.getEntityManager().persist(root); application.setRoot(root); } bindAppProperties(); Stripersist.getEntityManager().persist(application); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Applicatie is opgeslagen")); setApplication(application); return new ForwardResolution(JSP); } /* XXX */ private void bindAppProperties() { application.setName(name); application.setVersion(version); if(owner != null){ User appOwner = Stripersist.getEntityManager().find(User.class, owner); application.setOwner(appOwner); } application.setStartExtent(startExtent); application.setMaxExtent(maxExtent); application.setAuthenticatedRequired(authenticatedRequired); application.getDetails().putAll(details); } @ValidationMethod(on="save") public void validate(ValidationErrors errors) throws Exception { if(name == null) { errors.add("name", new SimpleError("Naam is verplicht")); return; } try { Long foundId = null; if(version == null){ foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version is null") .setMaxResults(1) .setParameter("name", name) .getSingleResult(); }else{ foundId = (Long)Stripersist.getEntityManager().createQuery("select id from Application where name = :name and version = :version") .setMaxResults(1) .setParameter("name", name) .setParameter("version", version) .getSingleResult(); } if(application != null && application.getId() != null){ if( !foundId.equals(application.getId()) ){ errors.add("name", new SimpleError("Naam en versie moeten een unieke combinatie vormen.")); } }else{ errors.add("name", new SimpleError("Naam en versie moeten een unieke combinatie vormen.")); } } catch(NoResultException nre) { // name version combination is unique } /* * Check if owner is an excisting user */ if(owner != null){ try { User appOwner = Stripersist.getEntityManager().find(User.class, owner); if(appOwner == null){ errors.add("owner", new SimpleError("Gebruiker met deze naam bestaat niet.")); } } catch(NoResultException nre) { errors.add("owner", new SimpleError("Gebruiker met deze naam bestaat niet.")); } } if(startExtent != null){ if(startExtent.getMinx() == null || startExtent.getMiny() == null || startExtent.getMaxx() == null || startExtent.getMaxy() == null ){ errors.add("startExtent", new SimpleError("Alle velden van de start extentie moeten ingevult worden.")); } } if(maxExtent != null){ if(maxExtent.getMinx() == null || maxExtent.getMiny() == null || maxExtent.getMaxx() == null || maxExtent.getMaxy() == null ){ errors.add("maxExtent", new SimpleError("Alle velden van de max extentie moeten ingevult worden.")); } } } public Resolution copy() throws Exception { try { Object o = Stripersist.getEntityManager().createQuery("select 1 from Application where name = :name") .setMaxResults(1) .setParameter("name", name) .getSingleResult(); getContext().getMessages().add(new SimpleMessage("Kan niet kopieren; applicatie met naam \"{0}\" bestaat al", name)); return new RedirectResolution(this.getClass()); } catch(NoResultException nre) { // name is unique } try { bindAppProperties(); Application copy = application.deepCopy(); // don't save changes to original app Stripersist.getEntityManager().detach(application); Stripersist.getEntityManager().persist(copy); Stripersist.getEntityManager().getTransaction().commit(); getContext().getMessages().add(new SimpleMessage("Applicatie is gekopieerd")); setApplication(copy); return new RedirectResolution(this.getClass()); } catch(Exception e) { log.error(String.format("Error copying application #%d named %s %swith new name %s", application.getId(), application.getName(), application.getVersion() == null ? "" : "v" + application.getVersion() + " ", name), e); String ex = e.toString(); Throwable cause = e.getCause(); while(cause != null) { ex += ";\n<br>" + cause.toString(); cause = cause.getCause(); } getContext().getValidationErrors().addGlobalError(new SimpleError("Fout bij kopieren applicatie: " + ex)); return new ForwardResolution(JSP); } } public Resolution mashup(){ ValidationErrors errors = context.getValidationErrors(); try { Level root = application.getRoot(); // Prevent copy-ing levels/layers application.setRoot(null); Application mashup = application.deepCopy(); Stripersist.getEntityManager().detach(application); mashup.setRoot(root); mashup.getDetails().put("isMashup", new ClobElement(Boolean.TRUE + "")); mashup.setName(mashup.getName() + "_" + mashupName); Stripersist.getEntityManager().persist(mashup); Stripersist.getEntityManager().getTransaction().commit(); setApplication(mashup); } catch (Exception ex) { errors.add("Fout", new SimpleError("De mashup kan niet worden gemaakt.")); } return new RedirectResolution(ApplicationSettingsActionBean.class); } public Resolution publish (){ // Find current published application and make backup try { Application oldPublished = (Application)Stripersist.getEntityManager().createQuery("from Application where name = :name AND version IS null") .setMaxResults(1) .setParameter("name", name) .getSingleResult(); Date nowDate = new Date(System.currentTimeMillis()); SimpleDateFormat sdf = (SimpleDateFormat) SimpleDateFormat.getDateInstance(); sdf.applyPattern("HH-mm_dd-MM-yyyy"); String now = sdf.format(nowDate); String uniqueVersion = findUniqueVersion(name, "B_"+now ); oldPublished.setVersion(uniqueVersion); Stripersist.getEntityManager().persist(oldPublished); Stripersist.getEntityManager().getTransaction().commit(); } catch(NoResultException nre) { } application.setVersion(null); Stripersist.getEntityManager().persist(application); Stripersist.getEntityManager().getTransaction().commit(); setApplication(null); return new RedirectResolution(ChooseApplicationActionBean.class); } /** * Checks if a Application with given name already exists and if needed * returns name with sequence number in brackets added to make it unique. * @param name Name to make unique * @return A unique name for a FeatureSource */ public static String findUniqueVersion(String name, String version) { int uniqueCounter = 0; while(true) { String testVersion; if(uniqueCounter == 0) { testVersion = version; } else { testVersion = version + " (" + uniqueCounter + ")"; } try { Stripersist.getEntityManager().createQuery("select 1 from Application where name = :name AND version = :version") .setParameter("name", name) .setParameter("version", testVersion) .setMaxResults(1) .getSingleResult(); uniqueCounter++; } catch(NoResultException nre) { version = testVersion; break; } } return version; } }
False
2,984
7
3,247
7
3,576
8
3,247
7
4,062
8
false
false
false
false
false
true
1,122
7486_0
package InleverOpdrachten;_x000D_ public class maincalcu {_x000D_ public static void main(String[] args) {_x000D_ _x000D_ Calculator calc = new Calculator();_x000D_ _x000D_ System.out.println(calc.add(5, 9)); // deze doet +_x000D_ _x000D_ System.out.println(calc.subtract(8, 3)); // deze doet -_x000D_ _x000D_ System.out.println(calc.multiply(4, 4)); // deze doet vermenigvuldigen dus x_x000D_ _x000D_ System.out.println(calc.devide(25, 5)); // deze doet delen door :_x000D_ _x000D_ System.out.println(calc.square(7)); // Dit vermenigvuldigd zichzelf meerdere keren zoals dus bijvoorbeeld als je 3.3 hebt doe je 3+3+3_x000D_ _x000D_ System.out.println(calc.exponentiation(7, 7)); // machten woorden gebruikt_x000D_ _x000D_ }_x000D_ }
Milanvanderburgh/Rekenmachine-Opdracht
InleverOpdrachten/maincalcu.java
249
// deze doet +_x000D_
line_comment
nl
package InleverOpdrachten;_x000D_ public class maincalcu {_x000D_ public static void main(String[] args) {_x000D_ _x000D_ Calculator calc = new Calculator();_x000D_ _x000D_ System.out.println(calc.add(5, 9)); // deze doet<SUF> _x000D_ System.out.println(calc.subtract(8, 3)); // deze doet -_x000D_ _x000D_ System.out.println(calc.multiply(4, 4)); // deze doet vermenigvuldigen dus x_x000D_ _x000D_ System.out.println(calc.devide(25, 5)); // deze doet delen door :_x000D_ _x000D_ System.out.println(calc.square(7)); // Dit vermenigvuldigd zichzelf meerdere keren zoals dus bijvoorbeeld als je 3.3 hebt doe je 3+3+3_x000D_ _x000D_ System.out.println(calc.exponentiation(7, 7)); // machten woorden gebruikt_x000D_ _x000D_ }_x000D_ }
True
301
12
367
12
344
11
367
12
371
12
false
false
false
false
false
true
1,717
144282_0
package com.topdesk.sqltransfer;_x000D_ _x000D_ import java.sql.ResultSet;_x000D_ import java.sql.SQLException;_x000D_ import java.sql.Statement;_x000D_ import java.text.NumberFormat;_x000D_ import java.util.Collections;_x000D_ import java.util.HashMap;_x000D_ import java.util.List;_x000D_ import java.util.Map;_x000D_ import java.util.NoSuchElementException;_x000D_ _x000D_ import org.slf4j.LoggerFactory;_x000D_ _x000D_ public class SQLtransferSQLResultSet implements SQLtransferResultSet {_x000D_ private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SQLtransferResultSet.class);_x000D_ _x000D_ @SuppressWarnings("unused")_x000D_ private final Object finalizerGuardian = new Object() {_x000D_ @Override_x000D_ protected void finalize() throws Throwable {_x000D_ try {_x000D_ internalClose(false);_x000D_ }_x000D_ catch (Exception e) {_x000D_ // Ignore_x000D_ }_x000D_ }_x000D_ };_x000D_ _x000D_ private final Statement statement;_x000D_ private final ResultSet rs;_x000D_ private final List<ColumnMetaData> metaData;_x000D_ _x000D_ boolean needsNext = true;_x000D_ boolean hasNext;_x000D_ _x000D_ public SQLtransferSQLResultSet(SQLtransferSQLConnection connection, ImportTable table) throws SQLtransferException {_x000D_ statement = connection.createStatement();_x000D_ try {_x000D_ long begin = System.currentTimeMillis();_x000D_ rs = statement.executeQuery(table.getQuery());_x000D_ NumberFormat nf = NumberFormat.getInstance();_x000D_ logger.info(String.format(" Duration : %s ms", nf.format(System.currentTimeMillis() - begin)));_x000D_ metaData = connection.createMetaData(rs.getMetaData());_x000D_ } _x000D_ catch (SQLException e) {_x000D_ throw new SQLtransferException(e);_x000D_ }_x000D_ }_x000D_ _x000D_ public List<ColumnMetaData> getMetaData() throws SQLtransferException {_x000D_ return metaData;_x000D_ }_x000D_ _x000D_ private Object getValue(ColumnMetaData column) throws SQLtransferException {_x000D_ try {_x000D_ int index = column.getIndex();_x000D_ // Vieze fix voor Oracle, volgens MetaData is het opeens 2005 en omzetten lukt niet_x000D_ if (column.getType() == 2005) {_x000D_ return rs.getString(index);_x000D_ }_x000D_ return column.getValue(rs.getObject(index));_x000D_ } _x000D_ catch (SQLException e) {_x000D_ throw new SQLtransferException(e);_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ public boolean hasNext() {_x000D_ if (needsNext) {_x000D_ needsNext = false;_x000D_ try {_x000D_ hasNext = rs.next();_x000D_ } _x000D_ catch (SQLException e) {_x000D_ throw new RuntimeException(e);_x000D_ } _x000D_ }_x000D_ return hasNext;_x000D_ }_x000D_ _x000D_ public Map<String, Object> next() {_x000D_ if (!hasNext()) {_x000D_ throw new NoSuchElementException();_x000D_ }_x000D_ needsNext = true;_x000D_ _x000D_ Map<String, Object> data = new HashMap<String, Object>(); _x000D_ for (ColumnMetaData column : metaData) {_x000D_ try {_x000D_ data.put(column.getName().toLowerCase(), getValue(column));_x000D_ } _x000D_ catch (SQLtransferException e) {_x000D_ throw new RuntimeException(e);_x000D_ } _x000D_ }_x000D_ _x000D_ if (!hasNext()) {_x000D_ internalClose(true);_x000D_ }_x000D_ return Collections.unmodifiableMap(data);_x000D_ }_x000D_ _x000D_ public void remove() {_x000D_ throw new UnsupportedOperationException();_x000D_ }_x000D_ _x000D_ private void internalClose(boolean log) {_x000D_ try {_x000D_ rs.close();_x000D_ } _x000D_ catch (SQLException e) {_x000D_ if (log) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ try {_x000D_ statement.close();_x000D_ } _x000D_ catch (SQLException e) {_x000D_ if (log) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
TheProjecter/sqltransfer
src/main/java/com/topdesk/sqltransfer/SQLtransferSQLResultSet.java
1,017
// Vieze fix voor Oracle, volgens MetaData is het opeens 2005 en omzetten lukt niet_x000D_
line_comment
nl
package com.topdesk.sqltransfer;_x000D_ _x000D_ import java.sql.ResultSet;_x000D_ import java.sql.SQLException;_x000D_ import java.sql.Statement;_x000D_ import java.text.NumberFormat;_x000D_ import java.util.Collections;_x000D_ import java.util.HashMap;_x000D_ import java.util.List;_x000D_ import java.util.Map;_x000D_ import java.util.NoSuchElementException;_x000D_ _x000D_ import org.slf4j.LoggerFactory;_x000D_ _x000D_ public class SQLtransferSQLResultSet implements SQLtransferResultSet {_x000D_ private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SQLtransferResultSet.class);_x000D_ _x000D_ @SuppressWarnings("unused")_x000D_ private final Object finalizerGuardian = new Object() {_x000D_ @Override_x000D_ protected void finalize() throws Throwable {_x000D_ try {_x000D_ internalClose(false);_x000D_ }_x000D_ catch (Exception e) {_x000D_ // Ignore_x000D_ }_x000D_ }_x000D_ };_x000D_ _x000D_ private final Statement statement;_x000D_ private final ResultSet rs;_x000D_ private final List<ColumnMetaData> metaData;_x000D_ _x000D_ boolean needsNext = true;_x000D_ boolean hasNext;_x000D_ _x000D_ public SQLtransferSQLResultSet(SQLtransferSQLConnection connection, ImportTable table) throws SQLtransferException {_x000D_ statement = connection.createStatement();_x000D_ try {_x000D_ long begin = System.currentTimeMillis();_x000D_ rs = statement.executeQuery(table.getQuery());_x000D_ NumberFormat nf = NumberFormat.getInstance();_x000D_ logger.info(String.format(" Duration : %s ms", nf.format(System.currentTimeMillis() - begin)));_x000D_ metaData = connection.createMetaData(rs.getMetaData());_x000D_ } _x000D_ catch (SQLException e) {_x000D_ throw new SQLtransferException(e);_x000D_ }_x000D_ }_x000D_ _x000D_ public List<ColumnMetaData> getMetaData() throws SQLtransferException {_x000D_ return metaData;_x000D_ }_x000D_ _x000D_ private Object getValue(ColumnMetaData column) throws SQLtransferException {_x000D_ try {_x000D_ int index = column.getIndex();_x000D_ // Vieze fix<SUF> if (column.getType() == 2005) {_x000D_ return rs.getString(index);_x000D_ }_x000D_ return column.getValue(rs.getObject(index));_x000D_ } _x000D_ catch (SQLException e) {_x000D_ throw new SQLtransferException(e);_x000D_ }_x000D_ }_x000D_ _x000D_ _x000D_ public boolean hasNext() {_x000D_ if (needsNext) {_x000D_ needsNext = false;_x000D_ try {_x000D_ hasNext = rs.next();_x000D_ } _x000D_ catch (SQLException e) {_x000D_ throw new RuntimeException(e);_x000D_ } _x000D_ }_x000D_ return hasNext;_x000D_ }_x000D_ _x000D_ public Map<String, Object> next() {_x000D_ if (!hasNext()) {_x000D_ throw new NoSuchElementException();_x000D_ }_x000D_ needsNext = true;_x000D_ _x000D_ Map<String, Object> data = new HashMap<String, Object>(); _x000D_ for (ColumnMetaData column : metaData) {_x000D_ try {_x000D_ data.put(column.getName().toLowerCase(), getValue(column));_x000D_ } _x000D_ catch (SQLtransferException e) {_x000D_ throw new RuntimeException(e);_x000D_ } _x000D_ }_x000D_ _x000D_ if (!hasNext()) {_x000D_ internalClose(true);_x000D_ }_x000D_ return Collections.unmodifiableMap(data);_x000D_ }_x000D_ _x000D_ public void remove() {_x000D_ throw new UnsupportedOperationException();_x000D_ }_x000D_ _x000D_ private void internalClose(boolean log) {_x000D_ try {_x000D_ rs.close();_x000D_ } _x000D_ catch (SQLException e) {_x000D_ if (log) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ try {_x000D_ statement.close();_x000D_ } _x000D_ catch (SQLException e) {_x000D_ if (log) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
False
1,512
34
1,699
37
1,718
32
1,699
37
1,970
35
false
false
false
false
false
true
3,427
161592_23
/*******************************************************************************_x000D_ * Copyright (c) 2008, 2018 SWTChart project._x000D_ *_x000D_ * All rights reserved. This program and the accompanying materials_x000D_ * are made available under the terms of the Eclipse Public License v1.0_x000D_ * which accompanies this distribution, and is available at_x000D_ * http://www.eclipse.org/legal/epl-v10.html_x000D_ * _x000D_ * Contributors:_x000D_ * yoshitaka - initial API and implementation_x000D_ *******************************************************************************/_x000D_ package org.eclipse.swtchart.internal.axis;_x000D_ _x000D_ import java.text.Format;_x000D_ import java.util.List;_x000D_ _x000D_ import org.eclipse.swt.SWT;_x000D_ import org.eclipse.swt.graphics.Color;_x000D_ import org.eclipse.swt.graphics.Font;_x000D_ import org.eclipse.swt.graphics.Rectangle;_x000D_ import org.eclipse.swtchart.Chart;_x000D_ import org.eclipse.swtchart.IAxis.Position;_x000D_ import org.eclipse.swtchart.IAxisTick;_x000D_ _x000D_ /**_x000D_ * An axis tick._x000D_ */_x000D_ public class AxisTick implements IAxisTick {_x000D_ _x000D_ /** the chart */_x000D_ private Chart chart;_x000D_ /** the axis */_x000D_ private Axis axis;_x000D_ /** the axis tick labels */_x000D_ private AxisTickLabels axisTickLabels;_x000D_ /** the axis tick marks */_x000D_ private AxisTickMarks axisTickMarks;_x000D_ /** true if tick is visible */_x000D_ private boolean isVisible;_x000D_ /** the tick mark step hint */_x000D_ private int tickMarkStepHint;_x000D_ /** the tick label angle in degree */_x000D_ private int tickLabelAngle;_x000D_ /** the default tick mark step hint */_x000D_ private static final int DEFAULT_TICK_MARK_STEP_HINT = 64;_x000D_ _x000D_ /**_x000D_ * Constructor._x000D_ *_x000D_ * @param chart_x000D_ * the chart_x000D_ * @param axis_x000D_ * the axis_x000D_ */_x000D_ protected AxisTick(Chart chart, Axis axis) {_x000D_ this.chart = chart;_x000D_ this.axis = axis;_x000D_ axisTickLabels = new AxisTickLabels(chart, axis);_x000D_ axisTickMarks = new AxisTickMarks(chart, axis);_x000D_ isVisible = true;_x000D_ tickLabelAngle = 0;_x000D_ tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gets the axis tick marks._x000D_ *_x000D_ * @return the axis tick marks_x000D_ */_x000D_ public AxisTickMarks getAxisTickMarks() {_x000D_ _x000D_ return axisTickMarks;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gets the axis tick labels._x000D_ *_x000D_ * @return the axis tick labels_x000D_ */_x000D_ public AxisTickLabels getAxisTickLabels() {_x000D_ _x000D_ return axisTickLabels;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setForeground(Color)_x000D_ */_x000D_ public void setForeground(Color color) {_x000D_ _x000D_ if(color != null && color.isDisposed()) {_x000D_ SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_ }_x000D_ axisTickMarks.setForeground(color);_x000D_ axisTickLabels.setForeground(color);_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getForeground()_x000D_ */_x000D_ public Color getForeground() {_x000D_ _x000D_ return axisTickMarks.getForeground();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setFont(Font)_x000D_ */_x000D_ public void setFont(Font font) {_x000D_ _x000D_ if(font != null && font.isDisposed()) {_x000D_ SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_ }_x000D_ axisTickLabels.setFont(font);_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getFont()_x000D_ */_x000D_ public Font getFont() {_x000D_ _x000D_ return axisTickLabels.getFont();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#isVisible()_x000D_ */_x000D_ public boolean isVisible() {_x000D_ _x000D_ return isVisible;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setVisible(boolean)_x000D_ */_x000D_ public void setVisible(boolean isVisible) {_x000D_ _x000D_ this.isVisible = isVisible;_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getTickMarkStepHint()_x000D_ */_x000D_ public int getTickMarkStepHint() {_x000D_ _x000D_ return tickMarkStepHint;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setTickMarkStepHint(int)_x000D_ */_x000D_ public void setTickMarkStepHint(int tickMarkStepHint) {_x000D_ _x000D_ if(tickMarkStepHint < MIN_GRID_STEP_HINT) {_x000D_ this.tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_ } else {_x000D_ this.tickMarkStepHint = tickMarkStepHint;_x000D_ }_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getTickLabelAngle()_x000D_ */_x000D_ public int getTickLabelAngle() {_x000D_ _x000D_ return tickLabelAngle;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setTickLabelAngle(int)_x000D_ */_x000D_ public void setTickLabelAngle(int angle) {_x000D_ _x000D_ if(angle < 0 || 90 < angle) {_x000D_ SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_ }_x000D_ if(tickLabelAngle != angle) {_x000D_ tickLabelAngle = angle;_x000D_ chart.updateLayout();_x000D_ }_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setFormat(Format)_x000D_ */_x000D_ public void setFormat(Format format) {_x000D_ _x000D_ axisTickLabels.setFormat(format);_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getFormat()_x000D_ */_x000D_ public Format getFormat() {_x000D_ _x000D_ return axisTickLabels.getFormat();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getBounds()_x000D_ */_x000D_ public Rectangle getBounds() {_x000D_ _x000D_ Rectangle r1 = axisTickMarks.getBounds();_x000D_ Rectangle r2 = axisTickLabels.getBounds();_x000D_ Position position = axis.getPosition();_x000D_ if(position == Position.Primary && axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r1.x, r1.y, r1.width, r1.height + r2.height);_x000D_ } else if(position == Position.Secondary && axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r1.x, r2.y, r1.width, r1.height + r2.height);_x000D_ } else if(position == Position.Primary && !axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r2.x, r1.y, r1.width + r2.width, r1.height);_x000D_ } else if(position == Position.Secondary && !axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r1.x, r1.y, r1.width + r2.width, r1.height);_x000D_ } else {_x000D_ throw new IllegalStateException("unknown axis position");_x000D_ }_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getTickLabelValues()_x000D_ */_x000D_ public double[] getTickLabelValues() {_x000D_ _x000D_ List<Double> list = axisTickLabels.getTickLabelValues();_x000D_ double[] values = new double[list.size()];_x000D_ for(int i = 0; i < values.length; i++) {_x000D_ values[i] = list.get(i);_x000D_ }_x000D_ return values;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Updates the tick around per 64 pixel._x000D_ *_x000D_ * @param length_x000D_ * the axis length_x000D_ */_x000D_ public void updateTick(int length) {_x000D_ _x000D_ if(length <= 0) {_x000D_ axisTickLabels.update(1);_x000D_ } else {_x000D_ axisTickLabels.update(length);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Updates the tick layout._x000D_ */_x000D_ protected void updateLayoutData() {_x000D_ _x000D_ axisTickLabels.updateLayoutData();_x000D_ axisTickMarks.updateLayoutData();_x000D_ }_x000D_ }_x000D_
laeubi/swtchart
org.eclipse.swtchart/src/org/eclipse/swtchart/internal/axis/AxisTick.java
2,198
/*_x000D_ * @see IAxisTick#getBounds()_x000D_ */
block_comment
nl
/*******************************************************************************_x000D_ * Copyright (c) 2008, 2018 SWTChart project._x000D_ *_x000D_ * All rights reserved. This program and the accompanying materials_x000D_ * are made available under the terms of the Eclipse Public License v1.0_x000D_ * which accompanies this distribution, and is available at_x000D_ * http://www.eclipse.org/legal/epl-v10.html_x000D_ * _x000D_ * Contributors:_x000D_ * yoshitaka - initial API and implementation_x000D_ *******************************************************************************/_x000D_ package org.eclipse.swtchart.internal.axis;_x000D_ _x000D_ import java.text.Format;_x000D_ import java.util.List;_x000D_ _x000D_ import org.eclipse.swt.SWT;_x000D_ import org.eclipse.swt.graphics.Color;_x000D_ import org.eclipse.swt.graphics.Font;_x000D_ import org.eclipse.swt.graphics.Rectangle;_x000D_ import org.eclipse.swtchart.Chart;_x000D_ import org.eclipse.swtchart.IAxis.Position;_x000D_ import org.eclipse.swtchart.IAxisTick;_x000D_ _x000D_ /**_x000D_ * An axis tick._x000D_ */_x000D_ public class AxisTick implements IAxisTick {_x000D_ _x000D_ /** the chart */_x000D_ private Chart chart;_x000D_ /** the axis */_x000D_ private Axis axis;_x000D_ /** the axis tick labels */_x000D_ private AxisTickLabels axisTickLabels;_x000D_ /** the axis tick marks */_x000D_ private AxisTickMarks axisTickMarks;_x000D_ /** true if tick is visible */_x000D_ private boolean isVisible;_x000D_ /** the tick mark step hint */_x000D_ private int tickMarkStepHint;_x000D_ /** the tick label angle in degree */_x000D_ private int tickLabelAngle;_x000D_ /** the default tick mark step hint */_x000D_ private static final int DEFAULT_TICK_MARK_STEP_HINT = 64;_x000D_ _x000D_ /**_x000D_ * Constructor._x000D_ *_x000D_ * @param chart_x000D_ * the chart_x000D_ * @param axis_x000D_ * the axis_x000D_ */_x000D_ protected AxisTick(Chart chart, Axis axis) {_x000D_ this.chart = chart;_x000D_ this.axis = axis;_x000D_ axisTickLabels = new AxisTickLabels(chart, axis);_x000D_ axisTickMarks = new AxisTickMarks(chart, axis);_x000D_ isVisible = true;_x000D_ tickLabelAngle = 0;_x000D_ tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gets the axis tick marks._x000D_ *_x000D_ * @return the axis tick marks_x000D_ */_x000D_ public AxisTickMarks getAxisTickMarks() {_x000D_ _x000D_ return axisTickMarks;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Gets the axis tick labels._x000D_ *_x000D_ * @return the axis tick labels_x000D_ */_x000D_ public AxisTickLabels getAxisTickLabels() {_x000D_ _x000D_ return axisTickLabels;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setForeground(Color)_x000D_ */_x000D_ public void setForeground(Color color) {_x000D_ _x000D_ if(color != null && color.isDisposed()) {_x000D_ SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_ }_x000D_ axisTickMarks.setForeground(color);_x000D_ axisTickLabels.setForeground(color);_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getForeground()_x000D_ */_x000D_ public Color getForeground() {_x000D_ _x000D_ return axisTickMarks.getForeground();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setFont(Font)_x000D_ */_x000D_ public void setFont(Font font) {_x000D_ _x000D_ if(font != null && font.isDisposed()) {_x000D_ SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_ }_x000D_ axisTickLabels.setFont(font);_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getFont()_x000D_ */_x000D_ public Font getFont() {_x000D_ _x000D_ return axisTickLabels.getFont();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#isVisible()_x000D_ */_x000D_ public boolean isVisible() {_x000D_ _x000D_ return isVisible;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setVisible(boolean)_x000D_ */_x000D_ public void setVisible(boolean isVisible) {_x000D_ _x000D_ this.isVisible = isVisible;_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getTickMarkStepHint()_x000D_ */_x000D_ public int getTickMarkStepHint() {_x000D_ _x000D_ return tickMarkStepHint;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setTickMarkStepHint(int)_x000D_ */_x000D_ public void setTickMarkStepHint(int tickMarkStepHint) {_x000D_ _x000D_ if(tickMarkStepHint < MIN_GRID_STEP_HINT) {_x000D_ this.tickMarkStepHint = DEFAULT_TICK_MARK_STEP_HINT;_x000D_ } else {_x000D_ this.tickMarkStepHint = tickMarkStepHint;_x000D_ }_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getTickLabelAngle()_x000D_ */_x000D_ public int getTickLabelAngle() {_x000D_ _x000D_ return tickLabelAngle;_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setTickLabelAngle(int)_x000D_ */_x000D_ public void setTickLabelAngle(int angle) {_x000D_ _x000D_ if(angle < 0 || 90 < angle) {_x000D_ SWT.error(SWT.ERROR_INVALID_ARGUMENT);_x000D_ }_x000D_ if(tickLabelAngle != angle) {_x000D_ tickLabelAngle = angle;_x000D_ chart.updateLayout();_x000D_ }_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#setFormat(Format)_x000D_ */_x000D_ public void setFormat(Format format) {_x000D_ _x000D_ axisTickLabels.setFormat(format);_x000D_ chart.updateLayout();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getFormat()_x000D_ */_x000D_ public Format getFormat() {_x000D_ _x000D_ return axisTickLabels.getFormat();_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getBounds()_x000D_ <SUF>*/_x000D_ public Rectangle getBounds() {_x000D_ _x000D_ Rectangle r1 = axisTickMarks.getBounds();_x000D_ Rectangle r2 = axisTickLabels.getBounds();_x000D_ Position position = axis.getPosition();_x000D_ if(position == Position.Primary && axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r1.x, r1.y, r1.width, r1.height + r2.height);_x000D_ } else if(position == Position.Secondary && axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r1.x, r2.y, r1.width, r1.height + r2.height);_x000D_ } else if(position == Position.Primary && !axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r2.x, r1.y, r1.width + r2.width, r1.height);_x000D_ } else if(position == Position.Secondary && !axis.isHorizontalAxis()) {_x000D_ return new Rectangle(r1.x, r1.y, r1.width + r2.width, r1.height);_x000D_ } else {_x000D_ throw new IllegalStateException("unknown axis position");_x000D_ }_x000D_ }_x000D_ _x000D_ /*_x000D_ * @see IAxisTick#getTickLabelValues()_x000D_ */_x000D_ public double[] getTickLabelValues() {_x000D_ _x000D_ List<Double> list = axisTickLabels.getTickLabelValues();_x000D_ double[] values = new double[list.size()];_x000D_ for(int i = 0; i < values.length; i++) {_x000D_ values[i] = list.get(i);_x000D_ }_x000D_ return values;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Updates the tick around per 64 pixel._x000D_ *_x000D_ * @param length_x000D_ * the axis length_x000D_ */_x000D_ public void updateTick(int length) {_x000D_ _x000D_ if(length <= 0) {_x000D_ axisTickLabels.update(1);_x000D_ } else {_x000D_ axisTickLabels.update(length);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Updates the tick layout._x000D_ */_x000D_ protected void updateLayoutData() {_x000D_ _x000D_ axisTickLabels.updateLayoutData();_x000D_ axisTickMarks.updateLayoutData();_x000D_ }_x000D_ }_x000D_
False
3,144
27
3,537
28
3,620
29
3,537
28
3,941
31
false
false
false
false
false
true
4,534
23515_5
package org.aikodi.chameleon.oo.type.generics; import org.aikodi.chameleon.core.lookup.LookupException; public class InstantiatedTypeParameter extends AbstractInstantiatedTypeParameter { public InstantiatedTypeParameter(String name, TypeArgument argument) { super(name,argument); } @Override protected InstantiatedTypeParameter cloneSelf() { return new InstantiatedTypeParameter(name(),argument()); } /** * @return * @throws LookupException */ public boolean hasWildCardBound() throws LookupException { return argument().isWildCardBound(); } // /** // * A generic parameter introduces itself. During lookup, the resolve() method will // * introduce an alias. // */ // public List<Member> getIntroducedMembers() { // List<Member> result = new ArrayList<Member>(); // result.add(this); // return result; // } // // upper en lower naar type param verhuizen? Wat met formal parameter? Moet dat daar niet hetzelfde blijven? // public boolean compatibleWith(TypeParameter other) throws LookupException { // return (other instanceof InstantiatedTypeParameter) && ((InstantiatedTypeParameter)other).argument().contains(argument()); // } }
tivervac/chameleon
src/org/aikodi/chameleon/oo/type/generics/InstantiatedTypeParameter.java
341
// // upper en lower naar type param verhuizen? Wat met formal parameter? Moet dat daar niet hetzelfde blijven?
line_comment
nl
package org.aikodi.chameleon.oo.type.generics; import org.aikodi.chameleon.core.lookup.LookupException; public class InstantiatedTypeParameter extends AbstractInstantiatedTypeParameter { public InstantiatedTypeParameter(String name, TypeArgument argument) { super(name,argument); } @Override protected InstantiatedTypeParameter cloneSelf() { return new InstantiatedTypeParameter(name(),argument()); } /** * @return * @throws LookupException */ public boolean hasWildCardBound() throws LookupException { return argument().isWildCardBound(); } // /** // * A generic parameter introduces itself. During lookup, the resolve() method will // * introduce an alias. // */ // public List<Member> getIntroducedMembers() { // List<Member> result = new ArrayList<Member>(); // result.add(this); // return result; // } // // upper en<SUF> // public boolean compatibleWith(TypeParameter other) throws LookupException { // return (other instanceof InstantiatedTypeParameter) && ((InstantiatedTypeParameter)other).argument().contains(argument()); // } }
True
263
29
327
33
321
25
327
33
360
31
false
false
false
false
false
true
1,050
22119_4
package eu.magisterapp.magisterapi; import org.joda.time.DateTime; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.CookieManager; import java.net.HttpCookie; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import eu.magisterapp.magisterapi.afwijkingen.ZernikeAfwijking; /** * Created by max on 7-12-15. */ public class Sessie { public static final Integer SESSION_TIMEOUT = 60*20*1000; // 20 minuten in ms public static final String ERROR_LOGIN = "Er is iets fout gegaan tijdens het inloggen."; private Long loggedInAt = 0L; private final String username; private final String password; private final String school; private final Map<String, String> payload; private String apiKeyHeader; private String apiKey; private MagisterConnection connection; private final URLS urls; private CookieManager cookies = new CookieManager(); private Account account; private AanmeldingenList aanmeldingen; public final String id; public Sessie(String gebruikersnaam, String wachtwoord, String school, MagisterConnection connection) { this.username = gebruikersnaam; this.password = wachtwoord; this.school = school; this.connection = connection; urls = new URLS(school); payload = new HashMap<String, String>() {{ put("Gebruikersnaam", username); put("Wachtwoord", password); }}; id = "un:" + gebruikersnaam + "sc:" + school; } public boolean loggedIn() { return ! isExpired() && cookies.getCookieStore().getCookies().size() > 0; } public synchronized void logOut() { cookies.getCookieStore().removeAll(); loggedInAt = 0L; } private boolean isExpired() { return loggedInAt + (SESSION_TIMEOUT - 1000) < System.currentTimeMillis(); } public synchronized void login() throws IOException { cookies.getCookieStore().removeAll(); connection.delete(urls.session(), this); Response response = connection.post(urls.login(), payload, this); if (response.isError() && response.isJson()) { try { JSONObject json; if ((json = response.getJson()) != null) { throw new BadResponseException(json.getString("message")); } } catch (JSONException e) { throw new BadResponseException(ERROR_LOGIN); } } else if(! response.isJson()) { // Als het response geen JSON is, kunnen we vrij // weinig. Daarom boeken we 'm hier maar voordat // we Nullpointers naar niet-bestaande json krijgen. throw new BadResponseException(ERROR_LOGIN); } if (response.headers.get("Set-Cookie") != null && response.headers.get("Set-Cookie").size() > 0) { // Cookies worden op de sessie gezet door de connection. loggedInAt = System.currentTimeMillis(); } else { throw new BadResponseException(ERROR_LOGIN); } } private synchronized void loginIfNotLoggedIn() throws IOException { if (! loggedIn()) login(); } public String getCookies() { if (cookies.getCookieStore().getCookies().size() == 0) { return ""; } StringBuilder builder = new StringBuilder(); for (HttpCookie cookie : cookies.getCookieStore().getCookies()) { builder.append(cookie.toString()).append(';'); } return builder.toString(); } public String getApiKeyHeader() throws IOException { if (shouldRefresh()) refresh(); return apiKeyHeader; } public String getApiKey() throws IOException { if (shouldRefresh()) refresh(); return apiKey; } private boolean shouldRefresh() { return apiKeyHeader == null || "".equals(apiKeyHeader) || apiKey == null || "".equals(apiKey); } private void refresh() throws IOException { String body = MagisterConnection.anonymousGet(urls.base()).body; Pattern headerPattern = Pattern.compile("apiKeyHeader: '([a-zA-Z0-9-]+)'"); Pattern keyPattern = Pattern.compile("apiKey: '([a-zA-Z0-9-]+)'"); Matcher headerMatcher = headerPattern.matcher(body); Matcher keyMatcher = keyPattern.matcher(body); if (headerMatcher.find()) apiKeyHeader = headerMatcher.group(1); if (keyMatcher.find()) apiKey = keyMatcher.group(1); } public synchronized void storeCookies(String cookieString) { cookies.getCookieStore().add(null, HttpCookie.parse(cookieString).get(0)); } public Account getAccount() throws IOException { if (account != null) return account; loginIfNotLoggedIn(); try { return account = new Account(connection, urls.account(), this); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van account gegevens."); } } public AfspraakList getAfspraken(DateTime van, DateTime tot) throws IOException { return getAfspraken(van, tot, true); } public AfspraakList getAfspraken(DateTime van, DateTime tot, boolean geenUitval) throws IOException { loginIfNotLoggedIn(); String url = urls.afspraken(getAccount(), van, tot, geenUitval); Response response = connection.get(url, this); try { AfspraakList afspraken = AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding()); afspraken.filterBullshitAfspraken(); return afspraken; } catch (ParseException e) { throw new BadResponseException("Fout bij het ophalen van afspraken"); } } public AanmeldingenList getAanmeldingen() throws IOException { if (aanmeldingen != null) return aanmeldingen; loginIfNotLoggedIn(); String url = urls.aanmeldingen(getAccount()); Response response = connection.get(url, this); try { return aanmeldingen = AanmeldingenList.fromResponse(response); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van aanmeldingen"); } } public CijferPerioden getCijferPerioden(Aanmelding aanmelding) throws IOException { loginIfNotLoggedIn(); String url = urls.cijferPerioden(getAccount(), aanmelding); Response response = connection.get(url, this); try { return CijferPerioden.fromResponse(response); } catch (ParseException | JSONException e) { throw new BadResponseException("Fout bij het ophalen van de cijferperioden."); } } public VakList getVakken(Aanmelding aanmelding) throws IOException { loginIfNotLoggedIn(); String url = urls.vakken(getAccount(), aanmelding); Response response = connection.get(url, this); try { return VakList.fromResponse(response); } catch (ParseException | JSONException e) { throw new BadResponseException("Fout bij het ophalen van de vakken"); } } public CijferList getCijfers(Aanmelding aanmelding, VakList vakken) throws IOException { loginIfNotLoggedIn(); String url = urls.cijfers(getAccount(), aanmelding); Response response = connection.get(url, this); try { return CijferList.fromResponse(response, vakken, aanmelding); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van cijfers"); } } public CijferList getCijfers() throws IOException { Aanmelding aanmelding = getAanmeldingen().getCurrentAanmelding(); return getCijfers(aanmelding, getVakken(aanmelding)); } public CijferList getRecentCijfers(Aanmelding aanmelding, VakList vakken) throws IOException { loginIfNotLoggedIn(); String url = urls.recentCijfers(getAccount(), aanmelding); Response response = connection.get(url, this); try { return CijferList.fromResponse(response, vakken, aanmelding); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van recente cijfers."); } } public Cijfer.CijferInfo getCijferInfo(Cijfer cijfer) throws IOException { Aanmelding aanmelding = cijfer.aanmelding; loginIfNotLoggedIn(); String url = urls.cijferDetails(getAccount(), aanmelding, cijfer); Response response = connection.get(url, this); try { return cijfer.new CijferInfo(response); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van cijfer gegevens"); } } public Cijfer attachCijferInfo(Cijfer cijfer) throws IOException { return attachCijferInfo(getCijferInfo(cijfer), cijfer); } public Cijfer attachCijferInfo(Cijfer.CijferInfo info, Cijfer cijfer) { cijfer.setInfo(info); return cijfer; } public AfspraakList getRoosterWijzigingen(DateTime van, DateTime tot) throws IOException { loginIfNotLoggedIn(); String url = urls.roosterWijzigingen(getAccount(), van, tot); Response response = connection.get(url, this); try { return AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding()); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van roosterwijzigingen"); } } }
Magister-Android/magister-api
src/main/java/eu/magisterapp/magisterapi/Sessie.java
2,981
// we Nullpointers naar niet-bestaande json krijgen.
line_comment
nl
package eu.magisterapp.magisterapi; import org.joda.time.DateTime; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.net.CookieManager; import java.net.HttpCookie; import java.text.ParseException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import eu.magisterapp.magisterapi.afwijkingen.ZernikeAfwijking; /** * Created by max on 7-12-15. */ public class Sessie { public static final Integer SESSION_TIMEOUT = 60*20*1000; // 20 minuten in ms public static final String ERROR_LOGIN = "Er is iets fout gegaan tijdens het inloggen."; private Long loggedInAt = 0L; private final String username; private final String password; private final String school; private final Map<String, String> payload; private String apiKeyHeader; private String apiKey; private MagisterConnection connection; private final URLS urls; private CookieManager cookies = new CookieManager(); private Account account; private AanmeldingenList aanmeldingen; public final String id; public Sessie(String gebruikersnaam, String wachtwoord, String school, MagisterConnection connection) { this.username = gebruikersnaam; this.password = wachtwoord; this.school = school; this.connection = connection; urls = new URLS(school); payload = new HashMap<String, String>() {{ put("Gebruikersnaam", username); put("Wachtwoord", password); }}; id = "un:" + gebruikersnaam + "sc:" + school; } public boolean loggedIn() { return ! isExpired() && cookies.getCookieStore().getCookies().size() > 0; } public synchronized void logOut() { cookies.getCookieStore().removeAll(); loggedInAt = 0L; } private boolean isExpired() { return loggedInAt + (SESSION_TIMEOUT - 1000) < System.currentTimeMillis(); } public synchronized void login() throws IOException { cookies.getCookieStore().removeAll(); connection.delete(urls.session(), this); Response response = connection.post(urls.login(), payload, this); if (response.isError() && response.isJson()) { try { JSONObject json; if ((json = response.getJson()) != null) { throw new BadResponseException(json.getString("message")); } } catch (JSONException e) { throw new BadResponseException(ERROR_LOGIN); } } else if(! response.isJson()) { // Als het response geen JSON is, kunnen we vrij // weinig. Daarom boeken we 'm hier maar voordat // we Nullpointers<SUF> throw new BadResponseException(ERROR_LOGIN); } if (response.headers.get("Set-Cookie") != null && response.headers.get("Set-Cookie").size() > 0) { // Cookies worden op de sessie gezet door de connection. loggedInAt = System.currentTimeMillis(); } else { throw new BadResponseException(ERROR_LOGIN); } } private synchronized void loginIfNotLoggedIn() throws IOException { if (! loggedIn()) login(); } public String getCookies() { if (cookies.getCookieStore().getCookies().size() == 0) { return ""; } StringBuilder builder = new StringBuilder(); for (HttpCookie cookie : cookies.getCookieStore().getCookies()) { builder.append(cookie.toString()).append(';'); } return builder.toString(); } public String getApiKeyHeader() throws IOException { if (shouldRefresh()) refresh(); return apiKeyHeader; } public String getApiKey() throws IOException { if (shouldRefresh()) refresh(); return apiKey; } private boolean shouldRefresh() { return apiKeyHeader == null || "".equals(apiKeyHeader) || apiKey == null || "".equals(apiKey); } private void refresh() throws IOException { String body = MagisterConnection.anonymousGet(urls.base()).body; Pattern headerPattern = Pattern.compile("apiKeyHeader: '([a-zA-Z0-9-]+)'"); Pattern keyPattern = Pattern.compile("apiKey: '([a-zA-Z0-9-]+)'"); Matcher headerMatcher = headerPattern.matcher(body); Matcher keyMatcher = keyPattern.matcher(body); if (headerMatcher.find()) apiKeyHeader = headerMatcher.group(1); if (keyMatcher.find()) apiKey = keyMatcher.group(1); } public synchronized void storeCookies(String cookieString) { cookies.getCookieStore().add(null, HttpCookie.parse(cookieString).get(0)); } public Account getAccount() throws IOException { if (account != null) return account; loginIfNotLoggedIn(); try { return account = new Account(connection, urls.account(), this); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van account gegevens."); } } public AfspraakList getAfspraken(DateTime van, DateTime tot) throws IOException { return getAfspraken(van, tot, true); } public AfspraakList getAfspraken(DateTime van, DateTime tot, boolean geenUitval) throws IOException { loginIfNotLoggedIn(); String url = urls.afspraken(getAccount(), van, tot, geenUitval); Response response = connection.get(url, this); try { AfspraakList afspraken = AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding()); afspraken.filterBullshitAfspraken(); return afspraken; } catch (ParseException e) { throw new BadResponseException("Fout bij het ophalen van afspraken"); } } public AanmeldingenList getAanmeldingen() throws IOException { if (aanmeldingen != null) return aanmeldingen; loginIfNotLoggedIn(); String url = urls.aanmeldingen(getAccount()); Response response = connection.get(url, this); try { return aanmeldingen = AanmeldingenList.fromResponse(response); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van aanmeldingen"); } } public CijferPerioden getCijferPerioden(Aanmelding aanmelding) throws IOException { loginIfNotLoggedIn(); String url = urls.cijferPerioden(getAccount(), aanmelding); Response response = connection.get(url, this); try { return CijferPerioden.fromResponse(response); } catch (ParseException | JSONException e) { throw new BadResponseException("Fout bij het ophalen van de cijferperioden."); } } public VakList getVakken(Aanmelding aanmelding) throws IOException { loginIfNotLoggedIn(); String url = urls.vakken(getAccount(), aanmelding); Response response = connection.get(url, this); try { return VakList.fromResponse(response); } catch (ParseException | JSONException e) { throw new BadResponseException("Fout bij het ophalen van de vakken"); } } public CijferList getCijfers(Aanmelding aanmelding, VakList vakken) throws IOException { loginIfNotLoggedIn(); String url = urls.cijfers(getAccount(), aanmelding); Response response = connection.get(url, this); try { return CijferList.fromResponse(response, vakken, aanmelding); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van cijfers"); } } public CijferList getCijfers() throws IOException { Aanmelding aanmelding = getAanmeldingen().getCurrentAanmelding(); return getCijfers(aanmelding, getVakken(aanmelding)); } public CijferList getRecentCijfers(Aanmelding aanmelding, VakList vakken) throws IOException { loginIfNotLoggedIn(); String url = urls.recentCijfers(getAccount(), aanmelding); Response response = connection.get(url, this); try { return CijferList.fromResponse(response, vakken, aanmelding); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van recente cijfers."); } } public Cijfer.CijferInfo getCijferInfo(Cijfer cijfer) throws IOException { Aanmelding aanmelding = cijfer.aanmelding; loginIfNotLoggedIn(); String url = urls.cijferDetails(getAccount(), aanmelding, cijfer); Response response = connection.get(url, this); try { return cijfer.new CijferInfo(response); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van cijfer gegevens"); } } public Cijfer attachCijferInfo(Cijfer cijfer) throws IOException { return attachCijferInfo(getCijferInfo(cijfer), cijfer); } public Cijfer attachCijferInfo(Cijfer.CijferInfo info, Cijfer cijfer) { cijfer.setInfo(info); return cijfer; } public AfspraakList getRoosterWijzigingen(DateTime van, DateTime tot) throws IOException { loginIfNotLoggedIn(); String url = urls.roosterWijzigingen(getAccount(), van, tot); Response response = connection.get(url, this); try { return AfspraakFactory.make(response, school, getAanmeldingen().getCurrentAanmelding()); } catch (ParseException | JSONException e) { e.printStackTrace(); throw new BadResponseException("Fout bij het ophalen van roosterwijzigingen"); } } }
True
2,317
14
2,511
15
2,600
13
2,511
15
3,041
16
false
false
false
false
false
true
3,801
26580_1
/* * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.hosted.image; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.graalvm.compiler.core.common.NumUtil; import org.graalvm.nativeimage.c.function.CFunctionPointer; import org.graalvm.nativeimage.c.function.RelocatedPointer; import com.oracle.objectfile.ObjectFile; import com.oracle.svm.hosted.meta.HostedMethod; import com.oracle.svm.hosted.meta.MethodPointer; public final class RelocatableBuffer { public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) { return new RelocatableBuffer(name, size, byteOrder); } /* * Map methods. */ public RelocatableBuffer.Info getInfo(final int key) { return getMap().get(key); } // The only place is is used is to add the ObjectHeader bits to a DynamicHub, // which is otherwise just a reference to a class. // In the future, this could be used for any offset from a relocated object reference. public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public int mapSize() { return getMap().size(); } // TODO: Replace with a visitor pattern rather than exposing the entrySet. public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() { return getMap().entrySet(); } /** Raw map access. */ private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) { return getMap().put(key, value); } /** Raw map access. */ protected Map<Integer, RelocatableBuffer.Info> getMap() { return map; } /* * ByteBuffer methods. */ public byte getByte(final int index) { return getBuffer().get(index); } public RelocatableBuffer putByte(final byte value) { getBuffer().put(value); return this; } public RelocatableBuffer putByte(final int index, final byte value) { getBuffer().put(index, value); return this; } public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) { getBuffer().put(source, offset, length); return this; } public RelocatableBuffer putInt(final int index, final int value) { getBuffer().putInt(index, value); return this; } public int getPosition() { return getBuffer().position(); } public RelocatableBuffer setPosition(final int newPosition) { getBuffer().position(newPosition); return this; } // TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer. protected byte[] getBytes() { return getBuffer().array(); } // TODO: This should become a private method. protected ByteBuffer getBuffer() { return buffer; } /* * Info factory. */ private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { return new Info(kind, relocationSize, explicitAddend, targetObject); } /* * Debugging. */ public String getName() { return name; } protected static String targetObjectClassification(final Object targetObject) { final StringBuilder result = new StringBuilder(); if (targetObject == null) { result.append("null"); } else { if (targetObject instanceof CFunctionPointer) { result.append("pointer to function"); if (targetObject instanceof MethodPointer) { final MethodPointer mp = (MethodPointer) targetObject; final HostedMethod hm = mp.getMethod(); result.append(" name: "); result.append(hm.getName()); } } else { result.append("pointer to data"); } } return result.toString(); } /** Constructor. */ private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) { this.name = name; this.size = size; final int intSize = NumUtil.safeToInt(size); this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder); this.map = new TreeMap<>(); } // Immutable fields. /** For debugging. */ protected final String name; /** The size of the ByteBuffer. */ protected final long size; /** The ByteBuffer itself. */ protected final ByteBuffer buffer; /** The map itself. */ private final TreeMap<Integer, RelocatableBuffer.Info> map; // Constants. static final long serialVersionUID = 0; static final int WORD_SIZE = 8; // HACK: hard-code for now // Note: A non-static inner class. // Note: To keep the RelocatableBuffer from getting separated from this Info. public class Info { /* * Access methods. */ public int getRelocationSize() { return relocationSize; } public ObjectFile.RelocationKind getRelocationKind() { return relocationKind; } public boolean hasExplicitAddend() { return (explicitAddend != null); } // May return null. public Long getExplicitAddend() { return explicitAddend; } public Object getTargetObject() { return targetObject; } // Protected constructor called only from RelocatableBuffer.infoFactory method. protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { this.relocationKind = kind; this.relocationSize = relocationSize; this.explicitAddend = explicitAddend; this.targetObject = targetObject; } // Immutable state. private final int relocationSize; private final ObjectFile.RelocationKind relocationKind; private final Long explicitAddend; /** * The referenced object on the heap. If this is an instance of a {@link RelocatedPointer}, * than the relocation is not treated as a data relocation but has a special meaning, e.g. a * code (text section) or constants (rodata section) relocation. */ private final Object targetObject; } }
nezihyigitbasi/graal
substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/image/RelocatableBuffer.java
2,283
/* * Map methods. */
block_comment
nl
/* * Copyright (c) 2014, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.svm.hosted.image; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.graalvm.compiler.core.common.NumUtil; import org.graalvm.nativeimage.c.function.CFunctionPointer; import org.graalvm.nativeimage.c.function.RelocatedPointer; import com.oracle.objectfile.ObjectFile; import com.oracle.svm.hosted.meta.HostedMethod; import com.oracle.svm.hosted.meta.MethodPointer; public final class RelocatableBuffer { public static RelocatableBuffer factory(final String name, final long size, final ByteOrder byteOrder) { return new RelocatableBuffer(name, size, byteOrder); } /* * Map methods. <SUF>*/ public RelocatableBuffer.Info getInfo(final int key) { return getMap().get(key); } // The only place is is used is to add the ObjectHeader bits to a DynamicHub, // which is otherwise just a reference to a class. // In the future, this could be used for any offset from a relocated object reference. public RelocatableBuffer.Info addDirectRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addDirectRelocationWithoutAddend(int key, int relocationSize, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.DIRECT, relocationSize, null, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public RelocatableBuffer.Info addPCRelativeRelocationWithAddend(int key, int relocationSize, Long explicitAddend, Object targetObject) { final RelocatableBuffer.Info info = infoFactory(ObjectFile.RelocationKind.PC_RELATIVE, relocationSize, explicitAddend, targetObject); final RelocatableBuffer.Info result = putInfo(key, info); return result; } public int mapSize() { return getMap().size(); } // TODO: Replace with a visitor pattern rather than exposing the entrySet. public Set<Map.Entry<Integer, RelocatableBuffer.Info>> entrySet() { return getMap().entrySet(); } /** Raw map access. */ private RelocatableBuffer.Info putInfo(final int key, final RelocatableBuffer.Info value) { return getMap().put(key, value); } /** Raw map access. */ protected Map<Integer, RelocatableBuffer.Info> getMap() { return map; } /* * ByteBuffer methods. */ public byte getByte(final int index) { return getBuffer().get(index); } public RelocatableBuffer putByte(final byte value) { getBuffer().put(value); return this; } public RelocatableBuffer putByte(final int index, final byte value) { getBuffer().put(index, value); return this; } public RelocatableBuffer putBytes(final byte[] source, final int offset, final int length) { getBuffer().put(source, offset, length); return this; } public RelocatableBuffer putInt(final int index, final int value) { getBuffer().putInt(index, value); return this; } public int getPosition() { return getBuffer().position(); } public RelocatableBuffer setPosition(final int newPosition) { getBuffer().position(newPosition); return this; } // TODO: Eliminate this method to avoid separating the byte[] from the RelocatableBuffer. protected byte[] getBytes() { return getBuffer().array(); } // TODO: This should become a private method. protected ByteBuffer getBuffer() { return buffer; } /* * Info factory. */ private Info infoFactory(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { return new Info(kind, relocationSize, explicitAddend, targetObject); } /* * Debugging. */ public String getName() { return name; } protected static String targetObjectClassification(final Object targetObject) { final StringBuilder result = new StringBuilder(); if (targetObject == null) { result.append("null"); } else { if (targetObject instanceof CFunctionPointer) { result.append("pointer to function"); if (targetObject instanceof MethodPointer) { final MethodPointer mp = (MethodPointer) targetObject; final HostedMethod hm = mp.getMethod(); result.append(" name: "); result.append(hm.getName()); } } else { result.append("pointer to data"); } } return result.toString(); } /** Constructor. */ private RelocatableBuffer(final String name, final long size, final ByteOrder byteOrder) { this.name = name; this.size = size; final int intSize = NumUtil.safeToInt(size); this.buffer = ByteBuffer.wrap(new byte[intSize]).order(byteOrder); this.map = new TreeMap<>(); } // Immutable fields. /** For debugging. */ protected final String name; /** The size of the ByteBuffer. */ protected final long size; /** The ByteBuffer itself. */ protected final ByteBuffer buffer; /** The map itself. */ private final TreeMap<Integer, RelocatableBuffer.Info> map; // Constants. static final long serialVersionUID = 0; static final int WORD_SIZE = 8; // HACK: hard-code for now // Note: A non-static inner class. // Note: To keep the RelocatableBuffer from getting separated from this Info. public class Info { /* * Access methods. */ public int getRelocationSize() { return relocationSize; } public ObjectFile.RelocationKind getRelocationKind() { return relocationKind; } public boolean hasExplicitAddend() { return (explicitAddend != null); } // May return null. public Long getExplicitAddend() { return explicitAddend; } public Object getTargetObject() { return targetObject; } // Protected constructor called only from RelocatableBuffer.infoFactory method. protected Info(ObjectFile.RelocationKind kind, int relocationSize, Long explicitAddend, Object targetObject) { this.relocationKind = kind; this.relocationSize = relocationSize; this.explicitAddend = explicitAddend; this.targetObject = targetObject; } // Immutable state. private final int relocationSize; private final ObjectFile.RelocationKind relocationKind; private final Long explicitAddend; /** * The referenced object on the heap. If this is an instance of a {@link RelocatedPointer}, * than the relocation is not treated as a data relocation but has a special meaning, e.g. a * code (text section) or constants (rodata section) relocation. */ private final Object targetObject; } }
False
1,856
8
2,035
8
2,168
10
2,035
8
2,338
10
false
false
false
false
false
true
4,193
29771_3
// 1 Naam Enscapsulation // 2 Probleem / Effect Een field kan een ongewenste waarde hebben // 3 OOP onderdelen ingezet 1 acces modifier 2 parameters 3 returntype // 4 Programmeren // 5 Use Cases Bank, leeftijd, nummerbord, postcode public class MyClass { public static void main(String args[]) { Overboeking ov = new Overboeking(); // ov.bedrag = -50; ov.setBedrag(-50); ov.overboeken(); System.out.println("Demo werkt"); } } class Overboeking{ private int bedrag; void overboeken() { System.out.println("Bij mij gaat er "+bedrag+" af"); System.out.println("Bij mij gaat er "+bedrag+" bij"); } public void setBedrag(int amount) { if(amount < 0) { System.out.println("Dit is een illigale hoeveelheid"); } else{ bedrag = amount; } } }
rodivanrooijen/YCN_Public
1. JAVA/MyClass (1).java
305
// 5 Use Cases Bank, leeftijd, nummerbord, postcode
line_comment
nl
// 1 Naam Enscapsulation // 2 Probleem / Effect Een field kan een ongewenste waarde hebben // 3 OOP onderdelen ingezet 1 acces modifier 2 parameters 3 returntype // 4 Programmeren // 5 Use<SUF> public class MyClass { public static void main(String args[]) { Overboeking ov = new Overboeking(); // ov.bedrag = -50; ov.setBedrag(-50); ov.overboeken(); System.out.println("Demo werkt"); } } class Overboeking{ private int bedrag; void overboeken() { System.out.println("Bij mij gaat er "+bedrag+" af"); System.out.println("Bij mij gaat er "+bedrag+" bij"); } public void setBedrag(int amount) { if(amount < 0) { System.out.println("Dit is een illigale hoeveelheid"); } else{ bedrag = amount; } } }
True
246
18
284
21
264
14
284
21
306
21
false
false
false
false
false
true
4,294
29633_4
package de.l3s.eventkg.nlp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import de.l3s.eventkg.meta.Language; import jep.Interpreter; import jep.JepException; import jep.SharedInterpreter; import opennlp.tools.util.Span; public class NLPCubeUtils implements NLPUtils { private Interpreter interp; // // returns sentence annotations - but just the strings // public String[] sentenceSplitter(String text) { // String[] sentences = sentenceDetector.sentDetect(text); // return sentences; // } // -Djava.library.path=/home/simon/.local/lib/python3.5/site-packages/jep // -Djava.library.path=/usr/local/lib/python2.7/dist-packages/jep // What was done? // Jep in maven // pip install jep public static void main(String[] args) throws JepException { System.out.println( "res = ''\nfor sentence in sentencesDe :\n\tfor token in sentence:\n\t\tline += token.word + '\t'\n\t\tline += token.space_after\n\t\tres += line + '\\n'"); Set<String> sentences = new HashSet<String>(); // sentences.add("Dies ist ein Satz. Und hier ist noch ein Satz."); // sentences.add("Morgen ist's Wochenende. Ich weiß, das ist gut."); // sentences.add("Pius II. ging nach Hause. Das war in Rom."); sentences.add("Die Skulpturenmeile in Hannover ist ein zwischen 1986 und 2000 geschaffener Skulpturenweg entlang der Straßen Brühlstraße und Leibnizufer in Hannover. Er besteht aus übergroßen Skulpturen und Plastiken im öffentlichen Straßenraum. Die Kunstwerke sind auf einer Länge von etwa 1.200 Meter zwischen dem Königsworther Platz und dem Niedersächsischen Landtag aufgestellt. Die sehr unterschiedlichen Arbeiten befinden sich überwiegend auf der grünen Mittelinsel des sechsspurigen, stark befahrenen Straßenzuges."); NLPCubeUtils nlpUtils = new NLPCubeUtils(Language.DE); for (String sentence : sentences) { for (Span span : nlpUtils.sentenceSplitterPositions(sentence)) { System.out.println(span.getCoveredText(sentence)); System.out.println(" " + span.getStart() + ", " + span.getEnd()); } } } public NLPCubeUtils(Language language) throws JepException { this.interp = new SharedInterpreter(); interp.eval("import sys"); interp.eval("if not hasattr(sys, 'argv'):\n sys.argv = ['']"); interp.eval("import sys"); interp.eval("from cube.api import Cube"); interp.eval("cube=Cube(verbose=True)"); interp.eval("cube.load('" + language.getLanguageLowerCase() + "')"); } // returns sentence annotations - but just the spans public Span[] sentenceSplitterPositions(String text) { System.out.println("Split: "+text); try { text=text.replace("'", "\\'"); interp.eval("text='" + text + "'"); interp.eval("sentences=cube(text)"); Object result1 = interp.getValue("sentences"); String res = result1.toString(); List<Span> spans = new ArrayList<Span>(); int startPosition = 0; int endPosition = 0; for (String sentenceRes : res.split("\\], \\[")) { // sentenceRes = sentenceRes.substring(2, // sentenceRes.length() - 2); String[] parts = sentenceRes.split("\t"); String space = null; for (int i = 1; i < parts.length; i += 9) { space = parts[i + 8]; if (space.contains(",")) space = space.substring(0, space.indexOf(",")); endPosition += parts[i].length(); if (!space.contains("SpaceAfter=No")) endPosition += 1; } if (!space.contains("SpaceAfter=No")) endPosition -= 1; Span span = new Span(startPosition, endPosition); spans.add(span); if (!space.contains("SpaceAfter=No")) endPosition += 1; startPosition = endPosition; } Span[] spanArray = new Span[spans.size()]; for (int i = 0; i < spanArray.length; i++) spanArray[i] = spans.get(i); return spanArray; } catch (JepException e) { e.printStackTrace(); } return null; } }
sgottsch/eventkg
src/de/l3s/eventkg/nlp/NLPCubeUtils.java
1,321
// Jep in maven
line_comment
nl
package de.l3s.eventkg.nlp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import de.l3s.eventkg.meta.Language; import jep.Interpreter; import jep.JepException; import jep.SharedInterpreter; import opennlp.tools.util.Span; public class NLPCubeUtils implements NLPUtils { private Interpreter interp; // // returns sentence annotations - but just the strings // public String[] sentenceSplitter(String text) { // String[] sentences = sentenceDetector.sentDetect(text); // return sentences; // } // -Djava.library.path=/home/simon/.local/lib/python3.5/site-packages/jep // -Djava.library.path=/usr/local/lib/python2.7/dist-packages/jep // What was done? // Jep in<SUF> // pip install jep public static void main(String[] args) throws JepException { System.out.println( "res = ''\nfor sentence in sentencesDe :\n\tfor token in sentence:\n\t\tline += token.word + '\t'\n\t\tline += token.space_after\n\t\tres += line + '\\n'"); Set<String> sentences = new HashSet<String>(); // sentences.add("Dies ist ein Satz. Und hier ist noch ein Satz."); // sentences.add("Morgen ist's Wochenende. Ich weiß, das ist gut."); // sentences.add("Pius II. ging nach Hause. Das war in Rom."); sentences.add("Die Skulpturenmeile in Hannover ist ein zwischen 1986 und 2000 geschaffener Skulpturenweg entlang der Straßen Brühlstraße und Leibnizufer in Hannover. Er besteht aus übergroßen Skulpturen und Plastiken im öffentlichen Straßenraum. Die Kunstwerke sind auf einer Länge von etwa 1.200 Meter zwischen dem Königsworther Platz und dem Niedersächsischen Landtag aufgestellt. Die sehr unterschiedlichen Arbeiten befinden sich überwiegend auf der grünen Mittelinsel des sechsspurigen, stark befahrenen Straßenzuges."); NLPCubeUtils nlpUtils = new NLPCubeUtils(Language.DE); for (String sentence : sentences) { for (Span span : nlpUtils.sentenceSplitterPositions(sentence)) { System.out.println(span.getCoveredText(sentence)); System.out.println(" " + span.getStart() + ", " + span.getEnd()); } } } public NLPCubeUtils(Language language) throws JepException { this.interp = new SharedInterpreter(); interp.eval("import sys"); interp.eval("if not hasattr(sys, 'argv'):\n sys.argv = ['']"); interp.eval("import sys"); interp.eval("from cube.api import Cube"); interp.eval("cube=Cube(verbose=True)"); interp.eval("cube.load('" + language.getLanguageLowerCase() + "')"); } // returns sentence annotations - but just the spans public Span[] sentenceSplitterPositions(String text) { System.out.println("Split: "+text); try { text=text.replace("'", "\\'"); interp.eval("text='" + text + "'"); interp.eval("sentences=cube(text)"); Object result1 = interp.getValue("sentences"); String res = result1.toString(); List<Span> spans = new ArrayList<Span>(); int startPosition = 0; int endPosition = 0; for (String sentenceRes : res.split("\\], \\[")) { // sentenceRes = sentenceRes.substring(2, // sentenceRes.length() - 2); String[] parts = sentenceRes.split("\t"); String space = null; for (int i = 1; i < parts.length; i += 9) { space = parts[i + 8]; if (space.contains(",")) space = space.substring(0, space.indexOf(",")); endPosition += parts[i].length(); if (!space.contains("SpaceAfter=No")) endPosition += 1; } if (!space.contains("SpaceAfter=No")) endPosition -= 1; Span span = new Span(startPosition, endPosition); spans.add(span); if (!space.contains("SpaceAfter=No")) endPosition += 1; startPosition = endPosition; } Span[] spanArray = new Span[spans.size()]; for (int i = 0; i < spanArray.length; i++) spanArray[i] = spans.get(i); return spanArray; } catch (JepException e) { e.printStackTrace(); } return null; } }
False
1,048
6
1,271
5
1,174
4
1,271
5
1,454
5
false
false
false
false
false
true
4,669
6675_3
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.intset; import com.ibm.wala.util.debug.Assertions; import java.util.Iterator; /** A bit set is a set of elements, each of which corresponds to a unique integer from [0,MAX]. */ public final class BitSet<T> { /** The backing bit vector that determines set membership. */ private final BitVector vector; /** The bijection between integer to object. */ private OrdinalSetMapping<T> map; /** * Constructor: create an empty set corresponding to a given mapping * * @throws IllegalArgumentException if map is null */ public BitSet(OrdinalSetMapping<T> map) { if (map == null) { throw new IllegalArgumentException("map is null"); } int length = map.getMaximumIndex(); vector = new BitVector(length); this.map = map; } public static <T> BitSet<T> createBitSet(BitSet<T> B) { if (B == null) { throw new IllegalArgumentException("null B"); } return new BitSet<>(B); } private BitSet(BitSet<T> B) { this(B.map); addAll(B); } /** * Add all elements in bitset B to this bit set * * @throws IllegalArgumentException if B is null */ public void addAll(BitSet<?> B) { if (B == null) { throw new IllegalArgumentException("B is null"); } vector.or(B.vector); } /** Add all bits in BitVector B to this bit set */ public void addAll(BitVector B) { vector.or(B); } /** Add an object to this bit set. */ public void add(T o) { int n = map.getMappedIndex(o); vector.set(n); } /** * Remove an object from this bit set. * * @param o the object to remove */ public void clear(T o) { int n = map.getMappedIndex(o); if (n == -1) { return; } vector.clear(n); } /** Does this set contain a certain object? */ public boolean contains(T o) { int n = map.getMappedIndex(o); if (n == -1) { return false; } return vector.get(n); } /** * @return a String representation */ @Override public String toString() { return vector.toString(); } /** * Method copy. Copies the bits in the bit vector, but only assigns the object map. No need to * create a new object/bit bijection object. * * @throws IllegalArgumentException if other is null */ public void copyBits(BitSet<T> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.copyBits(other.vector); map = other.map; } /** * Does this object hold the same bits as other? * * @throws IllegalArgumentException if other is null */ public boolean sameBits(BitSet<?> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } return vector.equals(other.vector); } /** Not very efficient. */ public Iterator<T> iterator() { return new Iterator<>() { private int nextCounter = -1; { for (int i = 0; i < vector.length(); i++) { if (vector.get(i)) { nextCounter = i; break; } } } @Override public boolean hasNext() { return (nextCounter != -1); } @Override public T next() { T result = map.getMappedObject(nextCounter); int start = nextCounter + 1; nextCounter = -1; for (int i = start; i < vector.length(); i++) { if (vector.get(i)) { nextCounter = i; break; } } return result; } @Override public void remove() { Assertions.UNREACHABLE(); } }; } public int size() { return vector.populationCount(); } public int length() { return vector.length(); } /** Set all the bits to 0. */ public void clearAll() { vector.clearAll(); } /** Set all the bits to 1. */ public void setAll() { vector.setAll(); } /** * Perform intersection of two bitsets * * @param other the other bitset in the operation * @throws IllegalArgumentException if other is null */ public void intersect(BitSet<?> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.and(other.vector); } /** * Perform the difference of two bit sets * * @param other the other bitset in the operation * @throws IllegalArgumentException if other is null */ public void difference(BitSet<T> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.and(BitVector.not(other.vector)); } /** */ public boolean isEmpty() { return size() == 0; } }
wala/WALA
util/src/main/java/com/ibm/wala/util/intset/BitSet.java
1,577
/** The bijection between integer to object. */
block_comment
nl
/* * Copyright (c) 2002 - 2006 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation */ package com.ibm.wala.util.intset; import com.ibm.wala.util.debug.Assertions; import java.util.Iterator; /** A bit set is a set of elements, each of which corresponds to a unique integer from [0,MAX]. */ public final class BitSet<T> { /** The backing bit vector that determines set membership. */ private final BitVector vector; /** The bijection between<SUF>*/ private OrdinalSetMapping<T> map; /** * Constructor: create an empty set corresponding to a given mapping * * @throws IllegalArgumentException if map is null */ public BitSet(OrdinalSetMapping<T> map) { if (map == null) { throw new IllegalArgumentException("map is null"); } int length = map.getMaximumIndex(); vector = new BitVector(length); this.map = map; } public static <T> BitSet<T> createBitSet(BitSet<T> B) { if (B == null) { throw new IllegalArgumentException("null B"); } return new BitSet<>(B); } private BitSet(BitSet<T> B) { this(B.map); addAll(B); } /** * Add all elements in bitset B to this bit set * * @throws IllegalArgumentException if B is null */ public void addAll(BitSet<?> B) { if (B == null) { throw new IllegalArgumentException("B is null"); } vector.or(B.vector); } /** Add all bits in BitVector B to this bit set */ public void addAll(BitVector B) { vector.or(B); } /** Add an object to this bit set. */ public void add(T o) { int n = map.getMappedIndex(o); vector.set(n); } /** * Remove an object from this bit set. * * @param o the object to remove */ public void clear(T o) { int n = map.getMappedIndex(o); if (n == -1) { return; } vector.clear(n); } /** Does this set contain a certain object? */ public boolean contains(T o) { int n = map.getMappedIndex(o); if (n == -1) { return false; } return vector.get(n); } /** * @return a String representation */ @Override public String toString() { return vector.toString(); } /** * Method copy. Copies the bits in the bit vector, but only assigns the object map. No need to * create a new object/bit bijection object. * * @throws IllegalArgumentException if other is null */ public void copyBits(BitSet<T> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.copyBits(other.vector); map = other.map; } /** * Does this object hold the same bits as other? * * @throws IllegalArgumentException if other is null */ public boolean sameBits(BitSet<?> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } return vector.equals(other.vector); } /** Not very efficient. */ public Iterator<T> iterator() { return new Iterator<>() { private int nextCounter = -1; { for (int i = 0; i < vector.length(); i++) { if (vector.get(i)) { nextCounter = i; break; } } } @Override public boolean hasNext() { return (nextCounter != -1); } @Override public T next() { T result = map.getMappedObject(nextCounter); int start = nextCounter + 1; nextCounter = -1; for (int i = start; i < vector.length(); i++) { if (vector.get(i)) { nextCounter = i; break; } } return result; } @Override public void remove() { Assertions.UNREACHABLE(); } }; } public int size() { return vector.populationCount(); } public int length() { return vector.length(); } /** Set all the bits to 0. */ public void clearAll() { vector.clearAll(); } /** Set all the bits to 1. */ public void setAll() { vector.setAll(); } /** * Perform intersection of two bitsets * * @param other the other bitset in the operation * @throws IllegalArgumentException if other is null */ public void intersect(BitSet<?> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.and(other.vector); } /** * Perform the difference of two bit sets * * @param other the other bitset in the operation * @throws IllegalArgumentException if other is null */ public void difference(BitSet<T> other) { if (other == null) { throw new IllegalArgumentException("other is null"); } vector.and(BitVector.not(other.vector)); } /** */ public boolean isEmpty() { return size() == 0; } }
False
1,232
10
1,325
10
1,489
10
1,325
10
1,599
10
false
false
false
false
false
true
2,675
58834_1
package antifraud; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.http.HttpMethod; @Configuration public class SecurityConfig { private final RestAuthenticationEntryPoint restAuthenticationEntryPoint; public SecurityConfig(RestAuthenticationEntryPoint restAuthenticationEntryPoint) { this.restAuthenticationEntryPoint = restAuthenticationEntryPoint; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .httpBasic(Customizer.withDefaults()) .csrf(CsrfConfigurer::disable) // For modifying requests via Postman .exceptionHandling(handing -> handing .authenticationEntryPoint(restAuthenticationEntryPoint) // Handles auth error: Voorheen stond hier restAuthenticationEntryPoint als value, maar in het voorbeeld verwees die nergens heen. ) .headers(headers -> headers.frameOptions().disable()) // for Postman, the H2 console .authorizeHttpRequests(requests -> requests // manage access .requestMatchers(HttpMethod.POST, "/api/auth/user").permitAll() .requestMatchers("/actuator/shutdown").permitAll() // needs to run test .requestMatchers(HttpMethod.POST, "/api/antifraud/transaction").hasAuthority("MERCHANT") .requestMatchers(HttpMethod.GET, "/api/auth/list/**").hasAnyAuthority("ADMINISTRATOR", "SUPPORT") .requestMatchers(HttpMethod.DELETE, "/api/auth/user/{username}").hasAuthority("ADMINISTRATOR") .requestMatchers(HttpMethod.PUT, "/api/auth/access/**").hasAuthority("ADMINISTRATOR") .requestMatchers(HttpMethod.PUT, "/api/auth/role/**").hasAuthority("ADMINISTRATOR") .requestMatchers(HttpMethod.GET, "/api/antifraud/stolencard").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.POST, "/api/antifraud/stolencard").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.DELETE, "/api/antifraud/stolencard/{number}").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.GET, "/api/antifraud/suspicious-ip").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.POST, "/api/antifraud/suspicious-ip").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.DELETE, "/api/antifraud/suspicious-ip/{ip}").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.PUT, "/api/antifraud/transaction").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.GET, "/api/antifraud/history/{number}").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.GET, "/api/antifraud/history").hasAuthority("SUPPORT") ) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // no session ) // other configurations .build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
ernstjanhoek/Anti-Fraud-System-java
Anti-Fraud System/task/src/antifraud/SecurityConfig.java
1,010
// Handles auth error: Voorheen stond hier restAuthenticationEntryPoint als value, maar in het voorbeeld verwees die nergens heen.
line_comment
nl
package antifraud; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.http.HttpMethod; @Configuration public class SecurityConfig { private final RestAuthenticationEntryPoint restAuthenticationEntryPoint; public SecurityConfig(RestAuthenticationEntryPoint restAuthenticationEntryPoint) { this.restAuthenticationEntryPoint = restAuthenticationEntryPoint; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { return http .httpBasic(Customizer.withDefaults()) .csrf(CsrfConfigurer::disable) // For modifying requests via Postman .exceptionHandling(handing -> handing .authenticationEntryPoint(restAuthenticationEntryPoint) // Handles auth<SUF> ) .headers(headers -> headers.frameOptions().disable()) // for Postman, the H2 console .authorizeHttpRequests(requests -> requests // manage access .requestMatchers(HttpMethod.POST, "/api/auth/user").permitAll() .requestMatchers("/actuator/shutdown").permitAll() // needs to run test .requestMatchers(HttpMethod.POST, "/api/antifraud/transaction").hasAuthority("MERCHANT") .requestMatchers(HttpMethod.GET, "/api/auth/list/**").hasAnyAuthority("ADMINISTRATOR", "SUPPORT") .requestMatchers(HttpMethod.DELETE, "/api/auth/user/{username}").hasAuthority("ADMINISTRATOR") .requestMatchers(HttpMethod.PUT, "/api/auth/access/**").hasAuthority("ADMINISTRATOR") .requestMatchers(HttpMethod.PUT, "/api/auth/role/**").hasAuthority("ADMINISTRATOR") .requestMatchers(HttpMethod.GET, "/api/antifraud/stolencard").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.POST, "/api/antifraud/stolencard").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.DELETE, "/api/antifraud/stolencard/{number}").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.GET, "/api/antifraud/suspicious-ip").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.POST, "/api/antifraud/suspicious-ip").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.DELETE, "/api/antifraud/suspicious-ip/{ip}").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.PUT, "/api/antifraud/transaction").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.GET, "/api/antifraud/history/{number}").hasAuthority("SUPPORT") .requestMatchers(HttpMethod.GET, "/api/antifraud/history").hasAuthority("SUPPORT") ) .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS) // no session ) // other configurations .build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
True
716
32
799
35
803
26
799
35
997
34
false
false
false
false
false
true
141
101970_3
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package asap.faceengine.lipsync; import hmi.faceanimation.FaceController; import hmi.tts.TTSTiming; import hmi.tts.Visime; import java.util.ArrayList; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; import saiba.bml.core.Behaviour; import asap.faceengine.faceunit.TimedFaceUnit; import asap.faceengine.viseme.VisemeBinding; import asap.realizer.lipsync.LipSynchProvider; import asap.realizer.pegboard.BMLBlockPeg; import asap.realizer.pegboard.OffsetPeg; import asap.realizer.pegboard.PegBoard; import asap.realizer.pegboard.TimePeg; import asap.realizer.planunit.PlanManager; import asap.realizer.planunit.TimedPlanUnit; /** * Creates TimedFaceUnits for lipsync * @author Herwin * */ @Slf4j public class TimedFaceUnitLipSynchProvider implements LipSynchProvider { private final VisemeBinding visimeBinding; private final FaceController faceController; private final PlanManager<TimedFaceUnit>facePlanManager; private final PegBoard pegBoard; public TimedFaceUnitLipSynchProvider(VisemeBinding visBinding, FaceController fc, PlanManager<TimedFaceUnit>facePlanManager, PegBoard pb) { visimeBinding = visBinding; faceController = fc; pegBoard = pb; this.facePlanManager= facePlanManager; } @Override public void addLipSyncMovement(BMLBlockPeg bbPeg, Behaviour beh, TimedPlanUnit bs, TTSTiming timing) { ArrayList<TimedFaceUnit> tfus = new ArrayList<TimedFaceUnit>(); double totalDuration = 0d; double prevDuration = 0d; // add null viseme before TimedFaceUnit tfu = null; HashMap<TimedFaceUnit, Double> startTimes = new HashMap<TimedFaceUnit, Double>(); HashMap<TimedFaceUnit, Double> endTimes = new HashMap<TimedFaceUnit, Double>(); for (Visime vis : timing.getVisimes()) { // OOK: de visemen zijn nu te kort (sluiten aan op interpolatie 0/0 // ipv 50/50) // make visemeunit, add to faceplanner... double start = totalDuration / 1000d - prevDuration / 2000; double peak = totalDuration / 1000d + vis.getDuration() / 2000d; double end = totalDuration / 1000d + vis.getDuration() / 1000d; if(tfu!=null) { endTimes.put(tfu, peak); // extend previous tfu to the peak of this } // one! tfu = visimeBinding.getVisemeUnit(bbPeg, beh, vis.getNumber(), faceController, pegBoard); startTimes.put(tfu, start); endTimes.put(tfu, end); tfus.add(tfu); totalDuration += vis.getDuration(); prevDuration = vis.getDuration(); } for (TimedFaceUnit vfu : tfus) { vfu.setSubUnit(true); facePlanManager.addPlanUnit(vfu); } // and now link viseme units to the speech timepeg! for (TimedFaceUnit plannedFU : tfus) { TimePeg startPeg = new OffsetPeg(bs.getTimePeg("start"), startTimes.get(plannedFU)); plannedFU.setTimePeg("start", startPeg); TimePeg endPeg = new OffsetPeg(bs.getTimePeg("start"), endTimes.get(plannedFU)); plannedFU.setTimePeg("end", endPeg); log.debug("adding face movement at {}-{}", plannedFU.getStartTime(), plannedFU.getEndTime()); } } }
ArticulatedSocialAgentsPlatform/AsapRealizer
Engines/AsapFaceEngine/src/asap/faceengine/lipsync/TimedFaceUnitLipSynchProvider.java
1,330
// OOK: de visemen zijn nu te kort (sluiten aan op interpolatie 0/0
line_comment
nl
/******************************************************************************* * Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands * * This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer). * * ASAPRealizer is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License (LGPL) as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ASAPRealizer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with ASAPRealizer. If not, see http://www.gnu.org/licenses/. ******************************************************************************/ package asap.faceengine.lipsync; import hmi.faceanimation.FaceController; import hmi.tts.TTSTiming; import hmi.tts.Visime; import java.util.ArrayList; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; import saiba.bml.core.Behaviour; import asap.faceengine.faceunit.TimedFaceUnit; import asap.faceengine.viseme.VisemeBinding; import asap.realizer.lipsync.LipSynchProvider; import asap.realizer.pegboard.BMLBlockPeg; import asap.realizer.pegboard.OffsetPeg; import asap.realizer.pegboard.PegBoard; import asap.realizer.pegboard.TimePeg; import asap.realizer.planunit.PlanManager; import asap.realizer.planunit.TimedPlanUnit; /** * Creates TimedFaceUnits for lipsync * @author Herwin * */ @Slf4j public class TimedFaceUnitLipSynchProvider implements LipSynchProvider { private final VisemeBinding visimeBinding; private final FaceController faceController; private final PlanManager<TimedFaceUnit>facePlanManager; private final PegBoard pegBoard; public TimedFaceUnitLipSynchProvider(VisemeBinding visBinding, FaceController fc, PlanManager<TimedFaceUnit>facePlanManager, PegBoard pb) { visimeBinding = visBinding; faceController = fc; pegBoard = pb; this.facePlanManager= facePlanManager; } @Override public void addLipSyncMovement(BMLBlockPeg bbPeg, Behaviour beh, TimedPlanUnit bs, TTSTiming timing) { ArrayList<TimedFaceUnit> tfus = new ArrayList<TimedFaceUnit>(); double totalDuration = 0d; double prevDuration = 0d; // add null viseme before TimedFaceUnit tfu = null; HashMap<TimedFaceUnit, Double> startTimes = new HashMap<TimedFaceUnit, Double>(); HashMap<TimedFaceUnit, Double> endTimes = new HashMap<TimedFaceUnit, Double>(); for (Visime vis : timing.getVisimes()) { // OOK: de<SUF> // ipv 50/50) // make visemeunit, add to faceplanner... double start = totalDuration / 1000d - prevDuration / 2000; double peak = totalDuration / 1000d + vis.getDuration() / 2000d; double end = totalDuration / 1000d + vis.getDuration() / 1000d; if(tfu!=null) { endTimes.put(tfu, peak); // extend previous tfu to the peak of this } // one! tfu = visimeBinding.getVisemeUnit(bbPeg, beh, vis.getNumber(), faceController, pegBoard); startTimes.put(tfu, start); endTimes.put(tfu, end); tfus.add(tfu); totalDuration += vis.getDuration(); prevDuration = vis.getDuration(); } for (TimedFaceUnit vfu : tfus) { vfu.setSubUnit(true); facePlanManager.addPlanUnit(vfu); } // and now link viseme units to the speech timepeg! for (TimedFaceUnit plannedFU : tfus) { TimePeg startPeg = new OffsetPeg(bs.getTimePeg("start"), startTimes.get(plannedFU)); plannedFU.setTimePeg("start", startPeg); TimePeg endPeg = new OffsetPeg(bs.getTimePeg("start"), endTimes.get(plannedFU)); plannedFU.setTimePeg("end", endPeg); log.debug("adding face movement at {}-{}", plannedFU.getStartTime(), plannedFU.getEndTime()); } } }
True
1,078
22
1,194
25
1,212
22
1,194
25
1,366
24
false
false
false
false
false
true
3,841
204926_1
package edu.cmu.lti.algorithm.learning.gm; import java.io.BufferedWriter; import edu.cmu.lti.algorithm.container.VectorX; import edu.cmu.lti.algorithm.container.VectorD; import edu.cmu.lti.algorithm.container.VectorI; import edu.cmu.lti.algorithm.container.VecVecI; import edu.cmu.lti.algorithm.math.rand.FRand; import edu.cmu.lti.util.file.FFile; import edu.cmu.lti.util.html.EColor; import edu.cmu.lti.util.system.FSystem; /** * this is the first draft, now it is bloated to a package * @author nlao * */ public class CRFB { public static class Param extends edu.cmu.lti.util.run.Param{ private static final long serialVersionUID = 2008042701L; // YYYYMMDD public Param(Class c) { super(c); parse(); } public void parse(){ //m = getInt("m",5); //eps = getDouble("eps",1e-5); //lang = getString("lang"); //diagco=getBoolean("diagco", false); } } public static enum EVType { IN(0,EColor.azure)/*conditioned on*/ , OUT(1,EColor.lightskyblue)/*to be evaluated*/ , MID(2,EColor.rosybrown2);//hidden nodes //really a nice place to put data! public EColor color; public int id; EVType(int id, EColor color){ this.id = id; this.color = color; } } public static class Factor{ public int id; public double w=0; public int iV1,iV2; //assume iV1<iV2, if iV1==-1 then it is a bias feature public Factor(int id, int iV1, int iV2){ this.iV2= iV2; this.iV1= iV1; } public String toString(){ return String.format("(%d,%d)%.1f",iV1,iV2,w); } public String print(){ return String.format("%d\t%d\t%.3f",iV1,iV2,w); } } public static class Variable{ //public SetI mi= new SetI(); public VectorX<Factor> vf= new VectorX<Factor>(Factor.class); //use reference to update it outside the model //public Variable(SetI mia,SetI mid){ this.mia= mi; } EVType type; int id; public Variable(int id, EVType type){ this.id = id; //mia= new SetI(); //mid= new SetI(); this.type=type; } } // variables public VectorX<Variable> vVar= new VectorX<Variable>(Variable.class); // factors public VectorX<Factor> vFactor= new VectorX<Factor>(Factor.class); // weights //VectorD vW; double[] x ; // expectations//in log domain? public VectorD vEVar=new VectorD(); public VectorD vEFa; public VectorI viZ=new VectorI(); public VectorI viY=new VectorI(); public VectorI viH=new VectorI(); public VectorI viX=new VectorI(); public VectorI viA=new VectorI(); /*public void selectSubNet(VectorI viY, VectorI viH , VectorI viZ){ this.viH = viH; this.viY = viY; this.viX = viH; viX.addAll(viY); this.viZ = viZ; }*/ /** * x={y,h}, * estimate p(x|z) * @param viZ: ids of z variables * @param viX: ids of x variables */ public void meanField(VectorI vi){ vEVar.extend(viA.size()); for (int iScan=0; iScan<5; ++iScan) for (int ix : vi) expectVar(ix); } private double expectVar(int id){ double e=0; for (Factor fa: vVar.get(id).vf) e+= expectFactor(id,fa); //exp(e1)/(exp(e0)+exp(e1))=1/(1+exp(e0-e1)) double p=1/(1+Math.exp(-e)); vEVar.set(id, p); return p; } private double expectFactor(int iVar, Factor fa){//int iF){ //= vFactor.get(iF); if (fa.w==0) return 0.0; double e=1; if (fa.iV2!=iVar) e*=vEVar.get(fa.iV2); if (fa.iV1>=0) if (fa.iV1!=iVar) e*=vEVar.get(fa.iV1); return e*fa.w; } private double expectFactor(int id){ Factor fa= vFactor.get(id); double e=vEVar.get(fa.iV2); if (fa.iV1>=0) e*=vEVar.get(fa.iV1); vEFa.set(id, e); return e; } /** * @param vY * @return loss=-log(p(y|z)) */ protected double getValue( VectorD vY){ double loss=0; //for (int iy: viY) for (int i=0; i<vY.size(); ++i){ if (vY.get(i)==1.0) loss += -Math.log(vEVar.get(viY.get(i))); else loss += -Math.log(1-vEVar.get(viY.get(i))); } return 0; } //public void setData( VectorD vZ){ vEVar.set(viZ, vZ); } public VectorD vX; public VectorD vX_y; public double loss=0; public VectorD vG; public Variable addVar(EVType type){ int id = vVar.size(); Variable var=new Variable(id,type); vVar.add(var); viA.add(id); switch(type){ case OUT: viY.add(id);viX.add(id);break; case MID: viH.add(id);viX.add(id);break; case IN: viZ.add(id); break; } return var; } public String toString(){ return String.format("|vVar|=%d, |vFa|=%d" , vVar.size(), vFactor.size()); } public Factor addFactor(int V1, int V2){ if (V1==V2) FSystem.dieShouldNotHappen(); if (V1>V2){ int a=V2; V2=V1;V1=a; } Factor f=new Factor(vFactor.size(), V1,V2); vFactor.add(f); if (V1!=-1) vVar.get(V1).vf.add(f); if (V2!=-1) vVar.get(V2).vf.add(f); return f; } public void test(VectorD vZ){//Sample s){ vEVar.set(viZ, vZ); //test(); meanField(viX); vX= (VectorD) vEVar.clone();//vEVar.sub(viX); } //public void test(){} //public void train(){} public void train(VectorD vY, VectorD vZ){//Sample s){// test(vZ); loss = getValue(vY); vEVar.set(viY, vY); meanField(viH); vX_y= (VectorD) vEVar.clone();//vEVar.sub(viX); vG=vX_y.minus(vX); } /** * vector of all variables * @param vA */ public void trainA(VectorD vA){ train(vA.sub(viY), vA.sub(viZ)); } public void testA(VectorD vA){ test(vA.sub(viZ)); } public VecVecI sampleGibbs(int n, int nBurnIn,int nThining){ vEVar.extend(viA.size()); vEVar.setAll(0.5); VectorI vi= this.viX; //if (withHidden) vi.addAll(b.viA); //else vi.addOn(b.viZ).addOn(b.viY).sortOn(); VecVecI vv=new VecVecI (); if (nBurnIn>0) for (int i=0;i< nBurnIn; ++i) scanGibbs(vi); for (int i=0;i<n; ++i){ if (nBurnIn<=0) for (int j=0;j<vEVar.size(); ++j) vEVar.set(j,(double)FRand.drawBinary(0.5)); for (int j=0;j<nThining; ++j) scanGibbs(vi); vv.add(vEVar.sub(vi).toVectorI()); System.out.print("."); } System.out.println(); return vv; //return null; } protected void scanGibbs(VectorI vi){ for (int i : vi){ expectVar(i); if (FRand.drawBoolean( vEVar.get(i))) vEVar.set(i,1.0); else vEVar.set(i,0.0); } return; } public boolean save(String fn){ BufferedWriter bw = FFile.newWriter(fn); FFile.write(bw,vVar.size()+"\n"); for ( Factor f :vFactor ) FFile.write(bw, f.print()+"\n"); FFile.flush(bw); return true; } /** * estimate p(y|x) * @param yb: starting id of y variables * @param ye: ending id of y variables */ //public void variational(int yb, int ye){ } public static void main(String[] args) { //TODO: test it with data from GM hw try { } catch ( Exception e ) { e.printStackTrace(); } } }
noon99jaki/pra
edu/cmu/lti/algorithm/learning/gm/CRFB.java
3,016
//m = getInt("m",5);
line_comment
nl
package edu.cmu.lti.algorithm.learning.gm; import java.io.BufferedWriter; import edu.cmu.lti.algorithm.container.VectorX; import edu.cmu.lti.algorithm.container.VectorD; import edu.cmu.lti.algorithm.container.VectorI; import edu.cmu.lti.algorithm.container.VecVecI; import edu.cmu.lti.algorithm.math.rand.FRand; import edu.cmu.lti.util.file.FFile; import edu.cmu.lti.util.html.EColor; import edu.cmu.lti.util.system.FSystem; /** * this is the first draft, now it is bloated to a package * @author nlao * */ public class CRFB { public static class Param extends edu.cmu.lti.util.run.Param{ private static final long serialVersionUID = 2008042701L; // YYYYMMDD public Param(Class c) { super(c); parse(); } public void parse(){ //m =<SUF> //eps = getDouble("eps",1e-5); //lang = getString("lang"); //diagco=getBoolean("diagco", false); } } public static enum EVType { IN(0,EColor.azure)/*conditioned on*/ , OUT(1,EColor.lightskyblue)/*to be evaluated*/ , MID(2,EColor.rosybrown2);//hidden nodes //really a nice place to put data! public EColor color; public int id; EVType(int id, EColor color){ this.id = id; this.color = color; } } public static class Factor{ public int id; public double w=0; public int iV1,iV2; //assume iV1<iV2, if iV1==-1 then it is a bias feature public Factor(int id, int iV1, int iV2){ this.iV2= iV2; this.iV1= iV1; } public String toString(){ return String.format("(%d,%d)%.1f",iV1,iV2,w); } public String print(){ return String.format("%d\t%d\t%.3f",iV1,iV2,w); } } public static class Variable{ //public SetI mi= new SetI(); public VectorX<Factor> vf= new VectorX<Factor>(Factor.class); //use reference to update it outside the model //public Variable(SetI mia,SetI mid){ this.mia= mi; } EVType type; int id; public Variable(int id, EVType type){ this.id = id; //mia= new SetI(); //mid= new SetI(); this.type=type; } } // variables public VectorX<Variable> vVar= new VectorX<Variable>(Variable.class); // factors public VectorX<Factor> vFactor= new VectorX<Factor>(Factor.class); // weights //VectorD vW; double[] x ; // expectations//in log domain? public VectorD vEVar=new VectorD(); public VectorD vEFa; public VectorI viZ=new VectorI(); public VectorI viY=new VectorI(); public VectorI viH=new VectorI(); public VectorI viX=new VectorI(); public VectorI viA=new VectorI(); /*public void selectSubNet(VectorI viY, VectorI viH , VectorI viZ){ this.viH = viH; this.viY = viY; this.viX = viH; viX.addAll(viY); this.viZ = viZ; }*/ /** * x={y,h}, * estimate p(x|z) * @param viZ: ids of z variables * @param viX: ids of x variables */ public void meanField(VectorI vi){ vEVar.extend(viA.size()); for (int iScan=0; iScan<5; ++iScan) for (int ix : vi) expectVar(ix); } private double expectVar(int id){ double e=0; for (Factor fa: vVar.get(id).vf) e+= expectFactor(id,fa); //exp(e1)/(exp(e0)+exp(e1))=1/(1+exp(e0-e1)) double p=1/(1+Math.exp(-e)); vEVar.set(id, p); return p; } private double expectFactor(int iVar, Factor fa){//int iF){ //= vFactor.get(iF); if (fa.w==0) return 0.0; double e=1; if (fa.iV2!=iVar) e*=vEVar.get(fa.iV2); if (fa.iV1>=0) if (fa.iV1!=iVar) e*=vEVar.get(fa.iV1); return e*fa.w; } private double expectFactor(int id){ Factor fa= vFactor.get(id); double e=vEVar.get(fa.iV2); if (fa.iV1>=0) e*=vEVar.get(fa.iV1); vEFa.set(id, e); return e; } /** * @param vY * @return loss=-log(p(y|z)) */ protected double getValue( VectorD vY){ double loss=0; //for (int iy: viY) for (int i=0; i<vY.size(); ++i){ if (vY.get(i)==1.0) loss += -Math.log(vEVar.get(viY.get(i))); else loss += -Math.log(1-vEVar.get(viY.get(i))); } return 0; } //public void setData( VectorD vZ){ vEVar.set(viZ, vZ); } public VectorD vX; public VectorD vX_y; public double loss=0; public VectorD vG; public Variable addVar(EVType type){ int id = vVar.size(); Variable var=new Variable(id,type); vVar.add(var); viA.add(id); switch(type){ case OUT: viY.add(id);viX.add(id);break; case MID: viH.add(id);viX.add(id);break; case IN: viZ.add(id); break; } return var; } public String toString(){ return String.format("|vVar|=%d, |vFa|=%d" , vVar.size(), vFactor.size()); } public Factor addFactor(int V1, int V2){ if (V1==V2) FSystem.dieShouldNotHappen(); if (V1>V2){ int a=V2; V2=V1;V1=a; } Factor f=new Factor(vFactor.size(), V1,V2); vFactor.add(f); if (V1!=-1) vVar.get(V1).vf.add(f); if (V2!=-1) vVar.get(V2).vf.add(f); return f; } public void test(VectorD vZ){//Sample s){ vEVar.set(viZ, vZ); //test(); meanField(viX); vX= (VectorD) vEVar.clone();//vEVar.sub(viX); } //public void test(){} //public void train(){} public void train(VectorD vY, VectorD vZ){//Sample s){// test(vZ); loss = getValue(vY); vEVar.set(viY, vY); meanField(viH); vX_y= (VectorD) vEVar.clone();//vEVar.sub(viX); vG=vX_y.minus(vX); } /** * vector of all variables * @param vA */ public void trainA(VectorD vA){ train(vA.sub(viY), vA.sub(viZ)); } public void testA(VectorD vA){ test(vA.sub(viZ)); } public VecVecI sampleGibbs(int n, int nBurnIn,int nThining){ vEVar.extend(viA.size()); vEVar.setAll(0.5); VectorI vi= this.viX; //if (withHidden) vi.addAll(b.viA); //else vi.addOn(b.viZ).addOn(b.viY).sortOn(); VecVecI vv=new VecVecI (); if (nBurnIn>0) for (int i=0;i< nBurnIn; ++i) scanGibbs(vi); for (int i=0;i<n; ++i){ if (nBurnIn<=0) for (int j=0;j<vEVar.size(); ++j) vEVar.set(j,(double)FRand.drawBinary(0.5)); for (int j=0;j<nThining; ++j) scanGibbs(vi); vv.add(vEVar.sub(vi).toVectorI()); System.out.print("."); } System.out.println(); return vv; //return null; } protected void scanGibbs(VectorI vi){ for (int i : vi){ expectVar(i); if (FRand.drawBoolean( vEVar.get(i))) vEVar.set(i,1.0); else vEVar.set(i,0.0); } return; } public boolean save(String fn){ BufferedWriter bw = FFile.newWriter(fn); FFile.write(bw,vVar.size()+"\n"); for ( Factor f :vFactor ) FFile.write(bw, f.print()+"\n"); FFile.flush(bw); return true; } /** * estimate p(y|x) * @param yb: starting id of y variables * @param ye: ending id of y variables */ //public void variational(int yb, int ye){ } public static void main(String[] args) { //TODO: test it with data from GM hw try { } catch ( Exception e ) { e.printStackTrace(); } } }
False
2,376
9
2,826
10
2,858
9
2,826
10
3,259
10
false
false
false
false
false
true
4,365
185157_1
package autoChirp.tweeting;_x000D_ _x000D_ import java.net.MalformedURLException;_x000D_ _x000D_ import javax.annotation.PostConstruct;_x000D_ _x000D_ import org.springframework.beans.factory.annotation.Value;_x000D_ import org.springframework.core.io.Resource;_x000D_ import org.springframework.core.io.UrlResource;_x000D_ import org.springframework.social.twitter.api.StatusDetails;_x000D_ import org.springframework.social.twitter.api.TweetData;_x000D_ import org.springframework.social.twitter.api.Twitter;_x000D_ import org.springframework.social.twitter.api.impl.TwitterTemplate;_x000D_ import org.springframework.stereotype.Component;_x000D_ _x000D_ import autoChirp.DBConnector;_x000D_ import autoChirp.tweetCreation.Tweet;_x000D_ import autoChirp.tweetCreation.TweetFactory;_x000D_ _x000D_ /**_x000D_ * This class executes the actual twitter status-update using Spring Social_x000D_ * Twitter API_x000D_ *_x000D_ * @author Alena Geduldig_x000D_ *_x000D_ */_x000D_ @Component_x000D_ public class TwitterConnection {_x000D_ _x000D_ @Value("${spring.social.twitter.appId}")_x000D_ private String appIDProp;_x000D_ _x000D_ @Value("${spring.social.twitter.appSecret}")_x000D_ private String appSecretProp;_x000D_ _x000D_ @Value("${autochirp.domain}")_x000D_ private String appDomainProp;_x000D_ _x000D_ @Value("${autochirp.parser.dateformats}")_x000D_ private String dateformatsProp;_x000D_ _x000D_ private static String appID;_x000D_ private static String appSecret;_x000D_ private static String appDomain;_x000D_ private static String dateformats;_x000D_ _x000D_ /**_x000D_ * get appToken and appSecret_x000D_ */_x000D_ @PostConstruct_x000D_ public void initializeConnection() {_x000D_ this.appID = appIDProp;_x000D_ this.appSecret = appSecretProp;_x000D_ this.appDomain = appDomainProp;_x000D_ this.dateformats = dateformatsProp;_x000D_ }_x000D_ _x000D_ /**_x000D_ * updates the users twitter-status to the tweets content. 1. reads the_x000D_ * tweet with the given tweetID from the database 2. checks if the related_x000D_ * tweetGroup is still enabled and tweet wasn't tweeted already 3. reads the_x000D_ * users oAuthToken and oAuthTokenSecret from the database 4. updates the_x000D_ * users twitter status to the tweets tweetContent_x000D_ *_x000D_ * @param userID_x000D_ * userID_x000D_ * @param tweetID_x000D_ * tweetID_x000D_ */_x000D_ public void run(int userID, int tweetID) {_x000D_ // read tweet from DB_x000D_ Tweet toTweet = DBConnector.getTweetByID(tweetID, userID);_x000D_ _x000D_ // check if tweet exists_x000D_ if (toTweet == null) {_x000D_ return;_x000D_ }_x000D_ // check if tweetGroup is still enabled_x000D_ if (!DBConnector.isEnabledGroup(toTweet.groupID, userID)) {_x000D_ return;_x000D_ }_x000D_ // check if tweet was not tweeted already_x000D_ if (toTweet.tweeted) {_x000D_ return;_x000D_ }_x000D_ _x000D_ _x000D_ _x000D_ // read userConfig (oAuthToken, tokenSecret) from DB_x000D_ String[] userConfig = DBConnector.getUserConfig(userID);_x000D_ String token = userConfig[1];_x000D_ String tokenSecret = userConfig[2];_x000D_ _x000D_ // tweeting_x000D_ Twitter twitter = new TwitterTemplate(appID, appSecret, token, tokenSecret);_x000D_ _x000D_ // TweetData tweetData = new TweetData(toTweet.content);_x000D_ String tweet = toTweet.content;_x000D_ TweetData tweetData = new TweetData(tweet);_x000D_ _x000D_ //check if tweet is a reply_x000D_ long replyID = 0;_x000D_ if(DBConnector.isThreadedGroup(toTweet.groupID, userID)){_x000D_ System.out.println("is threaded Group");_x000D_ replyID = DBConnector.getReplyID(tweetID, toTweet.groupID, userID);_x000D_ System.out.println("replyID: " + replyID);_x000D_ }_x000D_ _x000D_ // add image_x000D_ if (toTweet.imageUrl != null) {_x000D_ try {_x000D_ Resource img = new UrlResource(toTweet.imageUrl);_x000D_ tweetData = tweetData.withMedia(img);_x000D_ } catch (MalformedURLException e) {_x000D_ tweetData = new TweetData(tweet + " " + toTweet.imageUrl);_x000D_ }_x000D_ }_x000D_ _x000D_ // add flashcard_x000D_ if (toTweet.adjustedLength() > Tweet.MAX_TWEET_LENGTH) {_x000D_ String flashcard = appDomain + "/flashcard/" + toTweet.tweetID;_x000D_ _x000D_ try {_x000D_ tweetData = new TweetData(toTweet.trimmedContent()).withMedia(new UrlResource(flashcard));_x000D_ } catch (MalformedURLException e) {_x000D_ tweetData = new TweetData(toTweet.trimmedContent()+" " + flashcard);_x000D_ }_x000D_ }_x000D_ _x000D_ // add Geo-Locations_x000D_ if (toTweet.longitude != 0 || toTweet.latitude != 0) {_x000D_ tweetData = tweetData.atLocation(toTweet.longitude, toTweet.latitude).displayCoordinates(true);_x000D_ }_x000D_ _x000D_ _x000D_ _x000D_ // update Tweet-Status in DB_x000D_ DBConnector.flagAsTweeted(tweetID, userID);_x000D_ _x000D_ // update Status_x000D_ org.springframework.social.twitter.api.Tweet statusUpdate = null;_x000D_ if(replyID > 0){_x000D_ try{_x000D_ statusUpdate = twitter.timelineOperations().updateStatus(tweetData.inReplyToStatus(replyID));_x000D_ }_x000D_ catch(Exception e){_x000D_ e.printStackTrace();_x000D_ }_x000D_ DBConnector.addStatusID(tweetID, statusUpdate.getId());_x000D_ }_x000D_ else{_x000D_ try{_x000D_ statusUpdate = twitter.timelineOperations().updateStatus(tweetData);_x000D_ }_x000D_ catch(Exception e){_x000D_ e.printStackTrace();_x000D_ }_x000D_ DBConnector.addStatusID(tweetID, statusUpdate.getId());_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
spinfo/autoChirp
src/main/java/autoChirp/tweeting/TwitterConnection.java
1,589
/**_x000D_ * get appToken and appSecret_x000D_ */
block_comment
nl
package autoChirp.tweeting;_x000D_ _x000D_ import java.net.MalformedURLException;_x000D_ _x000D_ import javax.annotation.PostConstruct;_x000D_ _x000D_ import org.springframework.beans.factory.annotation.Value;_x000D_ import org.springframework.core.io.Resource;_x000D_ import org.springframework.core.io.UrlResource;_x000D_ import org.springframework.social.twitter.api.StatusDetails;_x000D_ import org.springframework.social.twitter.api.TweetData;_x000D_ import org.springframework.social.twitter.api.Twitter;_x000D_ import org.springframework.social.twitter.api.impl.TwitterTemplate;_x000D_ import org.springframework.stereotype.Component;_x000D_ _x000D_ import autoChirp.DBConnector;_x000D_ import autoChirp.tweetCreation.Tweet;_x000D_ import autoChirp.tweetCreation.TweetFactory;_x000D_ _x000D_ /**_x000D_ * This class executes the actual twitter status-update using Spring Social_x000D_ * Twitter API_x000D_ *_x000D_ * @author Alena Geduldig_x000D_ *_x000D_ */_x000D_ @Component_x000D_ public class TwitterConnection {_x000D_ _x000D_ @Value("${spring.social.twitter.appId}")_x000D_ private String appIDProp;_x000D_ _x000D_ @Value("${spring.social.twitter.appSecret}")_x000D_ private String appSecretProp;_x000D_ _x000D_ @Value("${autochirp.domain}")_x000D_ private String appDomainProp;_x000D_ _x000D_ @Value("${autochirp.parser.dateformats}")_x000D_ private String dateformatsProp;_x000D_ _x000D_ private static String appID;_x000D_ private static String appSecret;_x000D_ private static String appDomain;_x000D_ private static String dateformats;_x000D_ _x000D_ /**_x000D_ * get appToken and<SUF>*/_x000D_ @PostConstruct_x000D_ public void initializeConnection() {_x000D_ this.appID = appIDProp;_x000D_ this.appSecret = appSecretProp;_x000D_ this.appDomain = appDomainProp;_x000D_ this.dateformats = dateformatsProp;_x000D_ }_x000D_ _x000D_ /**_x000D_ * updates the users twitter-status to the tweets content. 1. reads the_x000D_ * tweet with the given tweetID from the database 2. checks if the related_x000D_ * tweetGroup is still enabled and tweet wasn't tweeted already 3. reads the_x000D_ * users oAuthToken and oAuthTokenSecret from the database 4. updates the_x000D_ * users twitter status to the tweets tweetContent_x000D_ *_x000D_ * @param userID_x000D_ * userID_x000D_ * @param tweetID_x000D_ * tweetID_x000D_ */_x000D_ public void run(int userID, int tweetID) {_x000D_ // read tweet from DB_x000D_ Tweet toTweet = DBConnector.getTweetByID(tweetID, userID);_x000D_ _x000D_ // check if tweet exists_x000D_ if (toTweet == null) {_x000D_ return;_x000D_ }_x000D_ // check if tweetGroup is still enabled_x000D_ if (!DBConnector.isEnabledGroup(toTweet.groupID, userID)) {_x000D_ return;_x000D_ }_x000D_ // check if tweet was not tweeted already_x000D_ if (toTweet.tweeted) {_x000D_ return;_x000D_ }_x000D_ _x000D_ _x000D_ _x000D_ // read userConfig (oAuthToken, tokenSecret) from DB_x000D_ String[] userConfig = DBConnector.getUserConfig(userID);_x000D_ String token = userConfig[1];_x000D_ String tokenSecret = userConfig[2];_x000D_ _x000D_ // tweeting_x000D_ Twitter twitter = new TwitterTemplate(appID, appSecret, token, tokenSecret);_x000D_ _x000D_ // TweetData tweetData = new TweetData(toTweet.content);_x000D_ String tweet = toTweet.content;_x000D_ TweetData tweetData = new TweetData(tweet);_x000D_ _x000D_ //check if tweet is a reply_x000D_ long replyID = 0;_x000D_ if(DBConnector.isThreadedGroup(toTweet.groupID, userID)){_x000D_ System.out.println("is threaded Group");_x000D_ replyID = DBConnector.getReplyID(tweetID, toTweet.groupID, userID);_x000D_ System.out.println("replyID: " + replyID);_x000D_ }_x000D_ _x000D_ // add image_x000D_ if (toTweet.imageUrl != null) {_x000D_ try {_x000D_ Resource img = new UrlResource(toTweet.imageUrl);_x000D_ tweetData = tweetData.withMedia(img);_x000D_ } catch (MalformedURLException e) {_x000D_ tweetData = new TweetData(tweet + " " + toTweet.imageUrl);_x000D_ }_x000D_ }_x000D_ _x000D_ // add flashcard_x000D_ if (toTweet.adjustedLength() > Tweet.MAX_TWEET_LENGTH) {_x000D_ String flashcard = appDomain + "/flashcard/" + toTweet.tweetID;_x000D_ _x000D_ try {_x000D_ tweetData = new TweetData(toTweet.trimmedContent()).withMedia(new UrlResource(flashcard));_x000D_ } catch (MalformedURLException e) {_x000D_ tweetData = new TweetData(toTweet.trimmedContent()+" " + flashcard);_x000D_ }_x000D_ }_x000D_ _x000D_ // add Geo-Locations_x000D_ if (toTweet.longitude != 0 || toTweet.latitude != 0) {_x000D_ tweetData = tweetData.atLocation(toTweet.longitude, toTweet.latitude).displayCoordinates(true);_x000D_ }_x000D_ _x000D_ _x000D_ _x000D_ // update Tweet-Status in DB_x000D_ DBConnector.flagAsTweeted(tweetID, userID);_x000D_ _x000D_ // update Status_x000D_ org.springframework.social.twitter.api.Tweet statusUpdate = null;_x000D_ if(replyID > 0){_x000D_ try{_x000D_ statusUpdate = twitter.timelineOperations().updateStatus(tweetData.inReplyToStatus(replyID));_x000D_ }_x000D_ catch(Exception e){_x000D_ e.printStackTrace();_x000D_ }_x000D_ DBConnector.addStatusID(tweetID, statusUpdate.getId());_x000D_ }_x000D_ else{_x000D_ try{_x000D_ statusUpdate = twitter.timelineOperations().updateStatus(tweetData);_x000D_ }_x000D_ catch(Exception e){_x000D_ e.printStackTrace();_x000D_ }_x000D_ DBConnector.addStatusID(tweetID, statusUpdate.getId());_x000D_ }_x000D_ _x000D_ }_x000D_ _x000D_ }_x000D_
False
2,138
24
2,419
25
2,437
27
2,411
25
2,757
27
false
false
false
false
false
true
4,140
119378_26
package io.lettuce.core; import io.lettuce.core.internal.LettuceAssert; import io.lettuce.core.protocol.CommandArgs; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.ProtocolKeyword; /** * * Argument list builder for the Redis <a href="https://redis.io/commands/georadius">GEORADIUS</a> and * <a href="https://redis.io/commands/georadiusbymember">GEORADIUSBYMEMBER</a> commands. * <p> * {@link GeoArgs} is a mutable object and instances should be used only once to avoid shared mutable state. * * @author Mark Paluch */ public class GeoArgs implements CompositeArgument { private boolean withdistance; private boolean withcoordinates; private boolean withhash; private Long count; private boolean any; private Sort sort = Sort.none; /** * Builder entry points for {@link GeoArgs}. */ public static class Builder { /** * Utility constructor. */ private Builder() { } /** * Creates new {@link GeoArgs} with {@literal WITHDIST} enabled. * * @return new {@link GeoArgs} with {@literal WITHDIST} enabled. * @see GeoArgs#withDistance() */ public static GeoArgs distance() { return new GeoArgs().withDistance(); } /** * Creates new {@link GeoArgs} with {@literal WITHCOORD} enabled. * * @return new {@link GeoArgs} with {@literal WITHCOORD} enabled. * @see GeoArgs#withCoordinates() */ public static GeoArgs coordinates() { return new GeoArgs().withCoordinates(); } /** * Creates new {@link GeoArgs} with {@literal WITHHASH} enabled. * * @return new {@link GeoArgs} with {@literal WITHHASH} enabled. * @see GeoArgs#withHash() */ public static GeoArgs hash() { return new GeoArgs().withHash(); } /** * Creates new {@link GeoArgs} with distance, coordinates and hash enabled. * * @return new {@link GeoArgs} with {@literal WITHDIST}, {@literal WITHCOORD}, {@literal WITHHASH} enabled. * @see GeoArgs#withDistance() * @see GeoArgs#withCoordinates() * @see GeoArgs#withHash() */ public static GeoArgs full() { return new GeoArgs().withDistance().withCoordinates().withHash(); } /** * Creates new {@link GeoArgs} with {@literal COUNT} set. * * @param count number greater 0. * @return new {@link GeoArgs} with {@literal COUNT} set. * @see GeoArgs#withCount(long) */ public static GeoArgs count(long count) { return new GeoArgs().withCount(count); } } /** * Request distance for results. * * @return {@code this} {@link GeoArgs}. */ public GeoArgs withDistance() { withdistance = true; return this; } /** * Request coordinates for results. * * @return {@code this} {@link GeoArgs}. */ public GeoArgs withCoordinates() { withcoordinates = true; return this; } /** * Request geohash for results. * * @return {@code this} {@link GeoArgs}. */ public GeoArgs withHash() { withhash = true; return this; } /** * Limit results to {@code count} entries. * * @param count number greater 0. * @return {@code this} {@link GeoArgs}. */ public GeoArgs withCount(long count) { return withCount(count, false); } /** * Limit results to {@code count} entries. * * @param count number greater 0. * @param any whether to complete the command as soon as enough matches are found, so the results may not be the ones * closest to the specified point. * @return {@code this} {@link GeoArgs}. * @since 6.1 */ public GeoArgs withCount(long count, boolean any) { LettuceAssert.isTrue(count > 0, "Count must be greater 0"); this.count = count; this.any = any; return this; } /** * * @return {@code true} if distance is requested. */ public boolean isWithDistance() { return withdistance; } /** * * @return {@code true} if coordinates are requested. */ public boolean isWithCoordinates() { return withcoordinates; } /** * * @return {@code true} if geohash is requested. */ public boolean isWithHash() { return withhash; } /** * Sort results ascending. * * @return {@code this} */ public GeoArgs asc() { return sort(Sort.asc); } /** * Sort results descending. * * @return {@code this} */ public GeoArgs desc() { return sort(Sort.desc); } /** * Sort results. * * @param sort sort order, must not be {@code null} * @return {@code this} */ public GeoArgs sort(Sort sort) { LettuceAssert.notNull(sort, "Sort must not be null"); this.sort = sort; return this; } /** * Sort order. */ public enum Sort { /** * ascending. */ asc, /** * descending. */ desc, /** * no sort order. */ none; } /** * Supported geo unit. */ public enum Unit implements ProtocolKeyword { /** * meter. */ m, /** * kilometer. */ km, /** * feet. */ ft, /** * mile. */ mi; private final byte[] asBytes; Unit() { asBytes = name().getBytes(); } @Override public byte[] getBytes() { return asBytes; } } public <K, V> void build(CommandArgs<K, V> args) { if (withdistance) { args.add("WITHDIST"); } if (withhash) { args.add("WITHHASH"); } if (withcoordinates) { args.add("WITHCOORD"); } if (sort != null && sort != Sort.none) { args.add(sort.name()); } if (count != null) { args.add(CommandKeyword.COUNT).add(count); if (any) { args.add("ANY"); } } } }
redis/lettuce
src/main/java/io/lettuce/core/GeoArgs.java
1,900
/** * feet. */
block_comment
nl
package io.lettuce.core; import io.lettuce.core.internal.LettuceAssert; import io.lettuce.core.protocol.CommandArgs; import io.lettuce.core.protocol.CommandKeyword; import io.lettuce.core.protocol.ProtocolKeyword; /** * * Argument list builder for the Redis <a href="https://redis.io/commands/georadius">GEORADIUS</a> and * <a href="https://redis.io/commands/georadiusbymember">GEORADIUSBYMEMBER</a> commands. * <p> * {@link GeoArgs} is a mutable object and instances should be used only once to avoid shared mutable state. * * @author Mark Paluch */ public class GeoArgs implements CompositeArgument { private boolean withdistance; private boolean withcoordinates; private boolean withhash; private Long count; private boolean any; private Sort sort = Sort.none; /** * Builder entry points for {@link GeoArgs}. */ public static class Builder { /** * Utility constructor. */ private Builder() { } /** * Creates new {@link GeoArgs} with {@literal WITHDIST} enabled. * * @return new {@link GeoArgs} with {@literal WITHDIST} enabled. * @see GeoArgs#withDistance() */ public static GeoArgs distance() { return new GeoArgs().withDistance(); } /** * Creates new {@link GeoArgs} with {@literal WITHCOORD} enabled. * * @return new {@link GeoArgs} with {@literal WITHCOORD} enabled. * @see GeoArgs#withCoordinates() */ public static GeoArgs coordinates() { return new GeoArgs().withCoordinates(); } /** * Creates new {@link GeoArgs} with {@literal WITHHASH} enabled. * * @return new {@link GeoArgs} with {@literal WITHHASH} enabled. * @see GeoArgs#withHash() */ public static GeoArgs hash() { return new GeoArgs().withHash(); } /** * Creates new {@link GeoArgs} with distance, coordinates and hash enabled. * * @return new {@link GeoArgs} with {@literal WITHDIST}, {@literal WITHCOORD}, {@literal WITHHASH} enabled. * @see GeoArgs#withDistance() * @see GeoArgs#withCoordinates() * @see GeoArgs#withHash() */ public static GeoArgs full() { return new GeoArgs().withDistance().withCoordinates().withHash(); } /** * Creates new {@link GeoArgs} with {@literal COUNT} set. * * @param count number greater 0. * @return new {@link GeoArgs} with {@literal COUNT} set. * @see GeoArgs#withCount(long) */ public static GeoArgs count(long count) { return new GeoArgs().withCount(count); } } /** * Request distance for results. * * @return {@code this} {@link GeoArgs}. */ public GeoArgs withDistance() { withdistance = true; return this; } /** * Request coordinates for results. * * @return {@code this} {@link GeoArgs}. */ public GeoArgs withCoordinates() { withcoordinates = true; return this; } /** * Request geohash for results. * * @return {@code this} {@link GeoArgs}. */ public GeoArgs withHash() { withhash = true; return this; } /** * Limit results to {@code count} entries. * * @param count number greater 0. * @return {@code this} {@link GeoArgs}. */ public GeoArgs withCount(long count) { return withCount(count, false); } /** * Limit results to {@code count} entries. * * @param count number greater 0. * @param any whether to complete the command as soon as enough matches are found, so the results may not be the ones * closest to the specified point. * @return {@code this} {@link GeoArgs}. * @since 6.1 */ public GeoArgs withCount(long count, boolean any) { LettuceAssert.isTrue(count > 0, "Count must be greater 0"); this.count = count; this.any = any; return this; } /** * * @return {@code true} if distance is requested. */ public boolean isWithDistance() { return withdistance; } /** * * @return {@code true} if coordinates are requested. */ public boolean isWithCoordinates() { return withcoordinates; } /** * * @return {@code true} if geohash is requested. */ public boolean isWithHash() { return withhash; } /** * Sort results ascending. * * @return {@code this} */ public GeoArgs asc() { return sort(Sort.asc); } /** * Sort results descending. * * @return {@code this} */ public GeoArgs desc() { return sort(Sort.desc); } /** * Sort results. * * @param sort sort order, must not be {@code null} * @return {@code this} */ public GeoArgs sort(Sort sort) { LettuceAssert.notNull(sort, "Sort must not be null"); this.sort = sort; return this; } /** * Sort order. */ public enum Sort { /** * ascending. */ asc, /** * descending. */ desc, /** * no sort order. */ none; } /** * Supported geo unit. */ public enum Unit implements ProtocolKeyword { /** * meter. */ m, /** * kilometer. */ km, /** * feet. <SUF>*/ ft, /** * mile. */ mi; private final byte[] asBytes; Unit() { asBytes = name().getBytes(); } @Override public byte[] getBytes() { return asBytes; } } public <K, V> void build(CommandArgs<K, V> args) { if (withdistance) { args.add("WITHDIST"); } if (withhash) { args.add("WITHHASH"); } if (withcoordinates) { args.add("WITHCOORD"); } if (sort != null && sort != Sort.none) { args.add(sort.name()); } if (count != null) { args.add(CommandKeyword.COUNT).add(count); if (any) { args.add("ANY"); } } } }
False
1,490
7
1,552
7
1,769
9
1,552
7
1,946
9
false
false
false
false
false
true
557
62222_1
package control; import java.io.IOException; import java.sql.Date; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import control.PersonaleDisponibileServlet.ComponenteComparator; import model.bean.ComponenteDellaSquadraBean; import model.bean.VigileDelFuocoBean; import model.dao.ComponenteDellaSquadraDao; import model.dao.VigileDelFuocoDao; import util.GiornoLavorativo; import util.Util; /** * Servlet implementation class PersonaleDisponibileAJAX */ @WebServlet("/PersonaleDisponibileAJAX") public class PersonaleDisponibileAJAX extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public PersonaleDisponibileAJAX() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Util.isCapoTurno(request); //Prendo l'email del VF da sostituire, il ruolo e il tipo di squadra String email=request.getParameter("email"); String ruolo= request.getParameter("mansione"); String tipo = request.getParameter("tiposquadra"); int tp= Integer.parseInt(tipo); HttpSession session = request.getSession(); HashMap<VigileDelFuocoBean, String> squadra=null; Date data = null; Date other= null; if(tp==1) { squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraDiurno"); data = Date.valueOf( request.getParameter("dataModifica")); other= Date.valueOf( request.getParameter("altroturno")); } else { if(tp==2) { squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraNotturno"); data = Date.valueOf( request.getParameter("dataModifica")); other= Date.valueOf( request.getParameter("altroturno")); }else { squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadra"); data = Date.valueOf( request.getParameter("dataModifica")); } } ArrayList<VigileDelFuocoBean> vigili=VigileDelFuocoDao.getDisponibili(data); //Confronto se nell'ArrayList dei vigili ci sono quelli gi� inseriti nelle squadre ArrayList<VigileDelFuocoBean> nuovoelenco = new ArrayList<VigileDelFuocoBean>(); for(int i=0; i<vigili.size();i++) { boolean trovato= false; Iterator it = squadra.entrySet().iterator(); while (it.hasNext()) { Map.Entry coppia = (Map.Entry) it.next(); VigileDelFuocoBean membro = (VigileDelFuocoBean) coppia.getKey(); //confronto il membro nella squadra con tutta la lista di vigili disponibili if(membro.getEmail().equalsIgnoreCase(vigili.get(i).getEmail())) { trovato = true; } if(trovato) break; } //Se il vigile non � presente nell'HashMap lo inserisco nel nuovo arrayList, controllando se � dello stesso ruolo del VF rimosso if(trovato==false) { if(ruolo!=null) { if(vigili.get(i).getMansione().equalsIgnoreCase(ruolo)) { nuovoelenco.add(vigili.get(i)); } } } } request.setAttribute("tiposquadra",tipo); request.setAttribute("vigili", nuovoelenco); request.setAttribute("email", email); request.setAttribute("dataModifica", data); request.setAttribute("altroturno", other); request.getRequestDispatcher("JSP/PersonaleDisponibileAJAXJSP.jsp").forward(request, response); } }
GSSDevelopmentTeam/ScheduFIRE
ScheduFIRE/src/control/PersonaleDisponibileAJAX.java
1,341
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package control; import java.io.IOException; import java.sql.Date; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import control.PersonaleDisponibileServlet.ComponenteComparator; import model.bean.ComponenteDellaSquadraBean; import model.bean.VigileDelFuocoBean; import model.dao.ComponenteDellaSquadraDao; import model.dao.VigileDelFuocoDao; import util.GiornoLavorativo; import util.Util; /** * Servlet implementation class PersonaleDisponibileAJAX */ @WebServlet("/PersonaleDisponibileAJAX") public class PersonaleDisponibileAJAX extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() <SUF>*/ public PersonaleDisponibileAJAX() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Util.isCapoTurno(request); //Prendo l'email del VF da sostituire, il ruolo e il tipo di squadra String email=request.getParameter("email"); String ruolo= request.getParameter("mansione"); String tipo = request.getParameter("tiposquadra"); int tp= Integer.parseInt(tipo); HttpSession session = request.getSession(); HashMap<VigileDelFuocoBean, String> squadra=null; Date data = null; Date other= null; if(tp==1) { squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraDiurno"); data = Date.valueOf( request.getParameter("dataModifica")); other= Date.valueOf( request.getParameter("altroturno")); } else { if(tp==2) { squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadraNotturno"); data = Date.valueOf( request.getParameter("dataModifica")); other= Date.valueOf( request.getParameter("altroturno")); }else { squadra = (HashMap<VigileDelFuocoBean, String>) session.getAttribute("squadra"); data = Date.valueOf( request.getParameter("dataModifica")); } } ArrayList<VigileDelFuocoBean> vigili=VigileDelFuocoDao.getDisponibili(data); //Confronto se nell'ArrayList dei vigili ci sono quelli gi� inseriti nelle squadre ArrayList<VigileDelFuocoBean> nuovoelenco = new ArrayList<VigileDelFuocoBean>(); for(int i=0; i<vigili.size();i++) { boolean trovato= false; Iterator it = squadra.entrySet().iterator(); while (it.hasNext()) { Map.Entry coppia = (Map.Entry) it.next(); VigileDelFuocoBean membro = (VigileDelFuocoBean) coppia.getKey(); //confronto il membro nella squadra con tutta la lista di vigili disponibili if(membro.getEmail().equalsIgnoreCase(vigili.get(i).getEmail())) { trovato = true; } if(trovato) break; } //Se il vigile non � presente nell'HashMap lo inserisco nel nuovo arrayList, controllando se � dello stesso ruolo del VF rimosso if(trovato==false) { if(ruolo!=null) { if(vigili.get(i).getMansione().equalsIgnoreCase(ruolo)) { nuovoelenco.add(vigili.get(i)); } } } } request.setAttribute("tiposquadra",tipo); request.setAttribute("vigili", nuovoelenco); request.setAttribute("email", email); request.setAttribute("dataModifica", data); request.setAttribute("altroturno", other); request.getRequestDispatcher("JSP/PersonaleDisponibileAJAXJSP.jsp").forward(request, response); } }
False
988
12
1,240
11
1,131
13
1,240
11
1,419
15
false
false
false
false
false
true
2,000
191865_0
package a08_product.products.clothes; import a08_product.products.Product; /** * gender: Jan de Rijke */ public class Shirt extends Product { private String gender; private String size; public Shirt(String code, String description, double price, String gender, String size){ super(code, description, price); this.gender=gender; this.size = size; } public String getGender() { return gender; } public String getSize() { return size; } @Override public double getVat() { return 0.21; } @Override public String toString() { return String.format("Shirt{ %s, gender='%s' , size='%s'}",super.toString(), getGender(),getSize()); } @Override public boolean equals(Object obj) { if (!super.equals(obj) || !(obj instanceof Shirt)) return false; Shirt other = (Shirt) obj; return (size == null ? other.size == null : size.equals(other.size)) && (gender == null ? other.gender == null : gender.equals(other.gender)); } @Override public int hashCode() { return super.hashCode() ^ (size==null?0:size.hashCode() ) ^ (gender==null?0:gender.hashCode()); } }
alecsiuh/java-exercises
Java/a06_salesperson/a08_product/products/clothes/Shirt.java
363
/** * gender: Jan de Rijke */
block_comment
nl
package a08_product.products.clothes; import a08_product.products.Product; /** * gender: Jan de<SUF>*/ public class Shirt extends Product { private String gender; private String size; public Shirt(String code, String description, double price, String gender, String size){ super(code, description, price); this.gender=gender; this.size = size; } public String getGender() { return gender; } public String getSize() { return size; } @Override public double getVat() { return 0.21; } @Override public String toString() { return String.format("Shirt{ %s, gender='%s' , size='%s'}",super.toString(), getGender(),getSize()); } @Override public boolean equals(Object obj) { if (!super.equals(obj) || !(obj instanceof Shirt)) return false; Shirt other = (Shirt) obj; return (size == null ? other.size == null : size.equals(other.size)) && (gender == null ? other.gender == null : gender.equals(other.gender)); } @Override public int hashCode() { return super.hashCode() ^ (size==null?0:size.hashCode() ) ^ (gender==null?0:gender.hashCode()); } }
False
278
10
356
12
344
11
356
12
388
12
false
false
false
false
false
true
1,495
14083_3
package game; import players.ComputerPlayer; import players.HumanPlayer; import players.Player; import views.View; import java.util.Observable; public class NetworkGame extends Observable implements Game { public static final int NUMBER_PLAYERS = 2; private Board board; private Player self; private Player other; private Player current; private View uIS; /** * @param s0 speler1 * @param s1 speler2 * @param v de UI * Deze functie initialiseerd een NetworkGame met spelers. */ public NetworkGame(Player s0, Player s1, View v) { board = new Board(); if (s0 instanceof HumanPlayer || s0 instanceof ComputerPlayer) { self = s0; other = s1; } else { self = s1; other = s0; } uIS = v; this.addObserver(uIS); } /** * Deze functie geeft het board terug. * @return Board */ public Board getBoard() { return board; } /** * Deze functie vraagt om een move. * @return int geeft een gekozen naam terug */ public int askForMove() { int move = -1; if (self instanceof HumanPlayer) { move = uIS.getHumanMove(self.getName()); } else if (self instanceof ComputerPlayer) { move = self.determineMove(board, uIS); } return move; } /** * @param name de naam van de speler * @param move de zet die gedaan is * Deze functie verwerkt een zet. */ public void moveDone(String name, int move) { if (self.getName().equals(name)) { board.makeMove(move, self.getMark()); current = self; } else if (other.getName().equals(name)) { board.makeMove(move, other.getMark()); current = other; } this.setChanged(); this.notifyObservers("printBoard"); } /** * @return Player geeft de winnaar van het spel terug */ public Player getWinner() { return current; } /** * @param winner naam van de winnaar * Deze functie zegt tegen de UI dat de game voorbij is en vraagt * of er nog een keer gespeeld moet worden. */ public void gameOver(String winner) { this.setChanged(); this.notifyObservers("gameOver " + winner); this.setChanged(); this.notifyObservers("askPlayAgain"); } }
RoyNijhuis/Connect-Four
src/game/NetworkGame.java
755
/** * @param name de naam van de speler * @param move de zet die gedaan is * Deze functie verwerkt een zet. */
block_comment
nl
package game; import players.ComputerPlayer; import players.HumanPlayer; import players.Player; import views.View; import java.util.Observable; public class NetworkGame extends Observable implements Game { public static final int NUMBER_PLAYERS = 2; private Board board; private Player self; private Player other; private Player current; private View uIS; /** * @param s0 speler1 * @param s1 speler2 * @param v de UI * Deze functie initialiseerd een NetworkGame met spelers. */ public NetworkGame(Player s0, Player s1, View v) { board = new Board(); if (s0 instanceof HumanPlayer || s0 instanceof ComputerPlayer) { self = s0; other = s1; } else { self = s1; other = s0; } uIS = v; this.addObserver(uIS); } /** * Deze functie geeft het board terug. * @return Board */ public Board getBoard() { return board; } /** * Deze functie vraagt om een move. * @return int geeft een gekozen naam terug */ public int askForMove() { int move = -1; if (self instanceof HumanPlayer) { move = uIS.getHumanMove(self.getName()); } else if (self instanceof ComputerPlayer) { move = self.determineMove(board, uIS); } return move; } /** * @param name de<SUF>*/ public void moveDone(String name, int move) { if (self.getName().equals(name)) { board.makeMove(move, self.getMark()); current = self; } else if (other.getName().equals(name)) { board.makeMove(move, other.getMark()); current = other; } this.setChanged(); this.notifyObservers("printBoard"); } /** * @return Player geeft de winnaar van het spel terug */ public Player getWinner() { return current; } /** * @param winner naam van de winnaar * Deze functie zegt tegen de UI dat de game voorbij is en vraagt * of er nog een keer gespeeld moet worden. */ public void gameOver(String winner) { this.setChanged(); this.notifyObservers("gameOver " + winner); this.setChanged(); this.notifyObservers("askPlayAgain"); } }
True
590
41
660
41
700
37
660
41
760
44
false
false
false
false
false
true
3,807
113787_3
package gem.sparseboolean.math; import java.util.ArrayList; public class Algorithm { public static int pointInside2DPolygon(ArrayList<Point2D> polygon, int n, Point2D pt, int onEdge) { if (n < 3) return 0; // cross points count of x int __count = 0; // neighbor bound vertices Point2D p1, p2; // left vertex p1 = polygon.get(0); // check all rays for (int i = 1; i <= n; ++i) { // point is an vertex if (pt == p1) return onEdge; // right vertex p2 = polygon.get(i % n); // ray is outside of our interests if (pt.getY() < Math.min(p1.getY(), p2.getY()) || pt.getY() > Math.max(p1.getY(), p2.getY())) { // next ray left point p1 = p2; continue; } // ray is crossing over by the algorithm (common part of) if (pt.getY() > Math.min(p1.getY(), p2.getY()) && pt.getY() < Math.max(p1.getY(), p2.getY())) { // x is before of ray if (pt.getX() <= Math.max(p1.getX(), p2.getX())) { // overlies on a horizontal ray if (p1.getY() == p2.getY() && pt.getX() >= Math.min(p1.getX(), p2.getX())) return onEdge; // ray is vertical if (p1.getX() == p2.getX()) { // overlies on a ray if (p1.getX() == pt.getX()) return onEdge; // before ray else ++__count; } // cross point on the left side else { // cross point of x double xinters = (pt.getY() - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()) + p1.getX(); // overlies on a ray if (Math.abs(pt.getX() - xinters) < Constants.DBL_EPSILON) return onEdge; // before ray if (pt.getX() < xinters) ++__count; } } } // special case when ray is crossing through the vertex else { // p crossing over p2 if (pt.getY() == p2.getY() && pt.getX() <= p2.getX()) { // next vertex Point2D p3 = polygon.get((i + 1) % n); if (pt.getY() >= Math.min(p1.getY(), p3.getY()) && pt.getY() <= Math.max(p1.getY(), p3.getY())) { ++__count; } else { __count += 2; } } } // next ray left point p1 = p2; } // EVEN if (__count % 2 == 0) { return (0); } // ODD else { return (1); } } }
nichollyn/chameleonbox
chameleonbox-library/src/gem/sparseboolean/math/Algorithm.java
946
// point is an vertex
line_comment
nl
package gem.sparseboolean.math; import java.util.ArrayList; public class Algorithm { public static int pointInside2DPolygon(ArrayList<Point2D> polygon, int n, Point2D pt, int onEdge) { if (n < 3) return 0; // cross points count of x int __count = 0; // neighbor bound vertices Point2D p1, p2; // left vertex p1 = polygon.get(0); // check all rays for (int i = 1; i <= n; ++i) { // point is<SUF> if (pt == p1) return onEdge; // right vertex p2 = polygon.get(i % n); // ray is outside of our interests if (pt.getY() < Math.min(p1.getY(), p2.getY()) || pt.getY() > Math.max(p1.getY(), p2.getY())) { // next ray left point p1 = p2; continue; } // ray is crossing over by the algorithm (common part of) if (pt.getY() > Math.min(p1.getY(), p2.getY()) && pt.getY() < Math.max(p1.getY(), p2.getY())) { // x is before of ray if (pt.getX() <= Math.max(p1.getX(), p2.getX())) { // overlies on a horizontal ray if (p1.getY() == p2.getY() && pt.getX() >= Math.min(p1.getX(), p2.getX())) return onEdge; // ray is vertical if (p1.getX() == p2.getX()) { // overlies on a ray if (p1.getX() == pt.getX()) return onEdge; // before ray else ++__count; } // cross point on the left side else { // cross point of x double xinters = (pt.getY() - p1.getY()) * (p2.getX() - p1.getX()) / (p2.getY() - p1.getY()) + p1.getX(); // overlies on a ray if (Math.abs(pt.getX() - xinters) < Constants.DBL_EPSILON) return onEdge; // before ray if (pt.getX() < xinters) ++__count; } } } // special case when ray is crossing through the vertex else { // p crossing over p2 if (pt.getY() == p2.getY() && pt.getX() <= p2.getX()) { // next vertex Point2D p3 = polygon.get((i + 1) % n); if (pt.getY() >= Math.min(p1.getY(), p3.getY()) && pt.getY() <= Math.max(p1.getY(), p3.getY())) { ++__count; } else { __count += 2; } } } // next ray left point p1 = p2; } // EVEN if (__count % 2 == 0) { return (0); } // ODD else { return (1); } } }
False
698
5
761
5
834
5
761
5
941
5
false
false
false
false
false
true
3,814
23611_5
package ship; /** * @author Nico van Ommen - 1030808 * @since 04/09/2022 */ public class TankerShip extends BaseShip { private int _capacity; private boolean _departed; /** * Constructor * * @param name */ public TankerShip(String name) { super(name); this.setCapacity(2000); this.setDeparted(false); } /** * Methode voor het leeghalen van het schip * * @param liters * @return int */ public int depleate(int liters) { int t = this.getCapacity(); this.setCapacity(t-=liters); return this.getCapacity(); } /** * Methode om de checken of het schip leeg is * * @return boolean */ public boolean isEmpty() { if (this._capacity == 0) { return true; } return false; } /** * Methode om de capacity te zetten voor het tankerschip * * @param liters */ public void setCapacity(int liters) { this._capacity = liters; } /** * Methode voor het ophalen van de capacity van het schip * * @return int */ public int getCapacity() { return this._capacity; } /** * Methode voor het zetten dat het schip kan vertrekken * * @param departed */ public void setDeparted(boolean departed) { this._departed = departed; } /** * Methode om te kijken of het schip al vertrokken is * * @return */ public boolean getDeparted() { return this._departed; } }
nicoripkip/TINPRO03-3
src/ship/TankerShip.java
547
/** * Methode voor het ophalen van de capacity van het schip * * @return int */
block_comment
nl
package ship; /** * @author Nico van Ommen - 1030808 * @since 04/09/2022 */ public class TankerShip extends BaseShip { private int _capacity; private boolean _departed; /** * Constructor * * @param name */ public TankerShip(String name) { super(name); this.setCapacity(2000); this.setDeparted(false); } /** * Methode voor het leeghalen van het schip * * @param liters * @return int */ public int depleate(int liters) { int t = this.getCapacity(); this.setCapacity(t-=liters); return this.getCapacity(); } /** * Methode om de checken of het schip leeg is * * @return boolean */ public boolean isEmpty() { if (this._capacity == 0) { return true; } return false; } /** * Methode om de capacity te zetten voor het tankerschip * * @param liters */ public void setCapacity(int liters) { this._capacity = liters; } /** * Methode voor het<SUF>*/ public int getCapacity() { return this._capacity; } /** * Methode voor het zetten dat het schip kan vertrekken * * @param departed */ public void setDeparted(boolean departed) { this._departed = departed; } /** * Methode om te kijken of het schip al vertrokken is * * @return */ public boolean getDeparted() { return this._departed; } }
True
435
29
447
27
497
29
447
27
568
32
false
false
false
false
false
true
2,824
203492_1
package main; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import daos.FileDAO; import entities.Element; import entities.Form; import entities.JSForm; import entities.LogEntry; import enums.ElementTypeID; import enums.Filename; import enums.LogLevel; import enums.LogType; import enums.UUIDmap; import exceptions.JSFormCreationException; // TODO : gekende problemen : /* * methodID = "-1" => -1 (zoniet : error in UUID string -1 * forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm * ng$ form heeft ALERTS ? */ public class JSFormCreator { public static List<LogEntry> logEntries = new ArrayList<>(); public static void main(String[] args) { try { // do not apply a default name if element has none Element.setAllowNullableName(true); //String path = "C:/Users/geert.haegens/workspaces/GO8ws_DO_NOT_USE/globis_articles/forms"; String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/struct_multiparents/forms/"; Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path); logEntries.addAll(FileDAO.logEntries); System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size()); Set<Form> oldForms = new HashSet<>(); Set<JSForm> newForms = new HashSet<>(); // read all forms for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) { oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt)); logEntries.addAll(FileDAO.logEntries); } // transform all forms String parentUuid = null; for (Form oldForm : oldForms) { JSForm newJSform = JSForm.createJSform(oldForm); if (newJSform != null) { newForms.add(newJSform); parentUuid = newJSform.getUUID(); JSForm newTMPform = JSForm.createTMPform(oldForm, parentUuid); if (newTMPform != null) { UUIDmap.uuidMapAdd(newTMPform.getUUID(), oldForm.getUUID()); newForms.add(newTMPform); } } // add log if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) { logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "INVALID_TRANSFORMATION")); } /* if (!oldForm.isTransformed()) { logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "TRANSFORMATION FAILED")); }*/ logEntries.addAll(oldForm.logEntries); } // WRITE all js$ & tmp$ forms for (Form newForm : newForms) { for (JSForm newForm : newForms) { FileDAO.writeForm(newForm); logEntries.addAll(FileDAO.logEntries); } // IF tmp$ : delete original + rename tmp$ for (JSForm newForm : newForms) { if (newForm.getName().startsWith(Filename.TMP_PREFIX)) { FileDAO.replaceOriginalByTMPform(newForm); logEntries.addAll(FileDAO.logEntries); } } // WRITE log file FileDAO.writeLog(path + "JSFormCreator", logEntries); System.out.println("Forms written : " + newForms.size()); System.err.println("Done."); } catch (JSFormCreationException e) { e.printStackTrace(); } } }
globisnv/servoy-8-transformation-tool
jsFormCreationTool/src/main/JSFormCreator.java
1,115
/* * methodID = "-1" => -1 (zoniet : error in UUID string -1 * forms met java beans = niet ondersteund ! zoeken : javax.swing in *.frm * ng$ form heeft ALERTS ? */
block_comment
nl
package main; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import daos.FileDAO; import entities.Element; import entities.Form; import entities.JSForm; import entities.LogEntry; import enums.ElementTypeID; import enums.Filename; import enums.LogLevel; import enums.LogType; import enums.UUIDmap; import exceptions.JSFormCreationException; // TODO : gekende problemen : /* * methodID = "-1"<SUF>*/ public class JSFormCreator { public static List<LogEntry> logEntries = new ArrayList<>(); public static void main(String[] args) { try { // do not apply a default name if element has none Element.setAllowNullableName(true); //String path = "C:/Users/geert.haegens/workspaces/GO8ws_DO_NOT_USE/globis_articles/forms"; String path = "C:/Users/geert.haegens/workspaces/servoy8testMagWeg/struct_multiparents/forms/"; Set<String> pathAndFilenamesNoExt = FileDAO.scanStructure(path); logEntries.addAll(FileDAO.logEntries); System.out.println("Forms to scan : " + pathAndFilenamesNoExt.size()); Set<Form> oldForms = new HashSet<>(); Set<JSForm> newForms = new HashSet<>(); // read all forms for (String formPathAndFilenamesNoExt : pathAndFilenamesNoExt) { oldForms.add(FileDAO.readForm(formPathAndFilenamesNoExt)); logEntries.addAll(FileDAO.logEntries); } // transform all forms String parentUuid = null; for (Form oldForm : oldForms) { JSForm newJSform = JSForm.createJSform(oldForm); if (newJSform != null) { newForms.add(newJSform); parentUuid = newJSform.getUUID(); JSForm newTMPform = JSForm.createTMPform(oldForm, parentUuid); if (newTMPform != null) { UUIDmap.uuidMapAdd(newTMPform.getUUID(), oldForm.getUUID()); newForms.add(newTMPform); } } // add log if (oldForm.getTypeId() == ElementTypeID.INVALID_TRANSFORMATION) { logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "INVALID_TRANSFORMATION")); } /* if (!oldForm.isTransformed()) { logEntries.add(new LogEntry(LogLevel.ERROR, LogType.CREATE, oldForm, "TRANSFORMATION FAILED")); }*/ logEntries.addAll(oldForm.logEntries); } // WRITE all js$ & tmp$ forms for (Form newForm : newForms) { for (JSForm newForm : newForms) { FileDAO.writeForm(newForm); logEntries.addAll(FileDAO.logEntries); } // IF tmp$ : delete original + rename tmp$ for (JSForm newForm : newForms) { if (newForm.getName().startsWith(Filename.TMP_PREFIX)) { FileDAO.replaceOriginalByTMPform(newForm); logEntries.addAll(FileDAO.logEntries); } } // WRITE log file FileDAO.writeLog(path + "JSFormCreator", logEntries); System.out.println("Forms written : " + newForms.size()); System.err.println("Done."); } catch (JSFormCreationException e) { e.printStackTrace(); } } }
False
807
53
955
60
976
54
955
60
1,276
60
false
false
false
false
false
true
4,560
118182_7
package nl.topicus.cambo.stubsis.client; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriBuilder; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import nl.topicus.cambo.stubsis.model.AccessTokenResponse; @ApplicationScoped public class StubSISCamboClient { private static final GenericType<Map<String, Object>> ANY_TYPE = new GenericType<>() { }; private Client client; private ObjectMapper mapper; private String accessToken; private Instant accessTokenExpiresAt = Instant.now(); private static final MediaType CAMBO_JSON_TYPE = MediaType.valueOf("application/vnd.topicus.cambo+json"); public StubSISCamboClient() { } /** * Maakt een Jackson ObjectMapper die overweg kan met datums als strings en de types in * java.time. VCA geeft datums terug in het formaat 'yyyy-MM-dd' en niet als een timestamp. */ private static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.setTimeZone(TimeZone.getDefault()); mapper.registerModule(new JavaTimeModule()); return mapper; } @PostConstruct private void init() { mapper = createMapper(); // Bouw een JAX-RS client met JSON support en registreer de keystore met het PKI Overheid // certificaat en private key. De client zal dit certificaat automatisch gebruiken voor // client authenticatie. client = ClientBuilder.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .keyStore(readStubSISKeyStore(), "password") .register(JacksonJaxbJsonProvider.class) .register(new JacksonObjectMapperProvider(mapper)) .build(); } private KeyStore readStubSISKeyStore() { try (FileInputStream fis = new FileInputStream(System.getProperty("stubsis/tlscertbundle"))) { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(fis, System.getProperty("stubsis/tlscertpassword").toCharArray()); return ks; } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) { throw new RuntimeException(e); } } private String getCamboUrl() { return "https://" + System.getProperty("cambo/hostname"); } /** * Haalt een nieuw access token op als dit nodig is. */ public String ensureToken() { // Als het token nog minimaal 5 minuten geldig is, gebruik dan de oude if (accessTokenExpiresAt.isAfter(Instant.now().plus(5, ChronoUnit.MINUTES))) return accessToken; // StubSIS gebruikt een dummy-OIN met 20x9. Het gebruikte nummer moet overeenkomen het het // OIN in het certificaat (serial number in het subjectDN) URI uri = UriBuilder.fromUri(getCamboUrl()).path("/login/oauth2/token").build(); MultivaluedMap<String, String> form = new MultivaluedHashMap<>(); form.putSingle("client_id", "99999999999999999999"); form.putSingle("grant_type", "client_credentials"); Response response = null; try { response = client.target(uri) .request() .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() != Status.OK.getStatusCode()) { throw new RuntimeException(toJsonString(response.readEntity(ANY_TYPE))); } AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class); accessToken = tokenResponse.getAccessToken().toString(); accessTokenExpiresAt = Instant.now().plus(tokenResponse.getExpiresIn(), ChronoUnit.SECONDS); return accessToken; } finally { close(response); } } protected void close(Response response) { if (response != null) response.close(); } public URI me() { return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/party/me").build(); } public URI endpoints() { return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/koppelpunt").build(); } public URI nieuweAanmeldingen(String endpoint) { return UriBuilder.fromUri(getCamboUrl()) .path("/cambo/rest/v1/koppelpunt") .path(endpoint) .path("aanmelding/nieuw") .build(); } public URI aanmeldingen(String endpoint) { return UriBuilder.fromUri(getCamboUrl()) .path("/cambo/rest/v1/koppelpunt") .path(endpoint) .path("aanmelding") .build(); } public Object read(URI uri, Class< ? > responseType) { Response response = null; try { response = client.target(uri) .request(CAMBO_JSON_TYPE) .header("Authorization", "Bearer " + ensureToken()) .get(); if (responseType == null) return response.readEntity(ANY_TYPE); else return response.readEntity(responseType); } finally { close(response); } } public String toJsonString(Object obj) { try { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
topicusonderwijs/vca-stubsis
src/main/java/nl/topicus/cambo/stubsis/client/StubSISCamboClient.java
1,960
// OIN in het certificaat (serial number in het subjectDN)
line_comment
nl
package nl.topicus.cambo.stubsis.client; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedHashMap; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.UriBuilder; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; import nl.topicus.cambo.stubsis.model.AccessTokenResponse; @ApplicationScoped public class StubSISCamboClient { private static final GenericType<Map<String, Object>> ANY_TYPE = new GenericType<>() { }; private Client client; private ObjectMapper mapper; private String accessToken; private Instant accessTokenExpiresAt = Instant.now(); private static final MediaType CAMBO_JSON_TYPE = MediaType.valueOf("application/vnd.topicus.cambo+json"); public StubSISCamboClient() { } /** * Maakt een Jackson ObjectMapper die overweg kan met datums als strings en de types in * java.time. VCA geeft datums terug in het formaat 'yyyy-MM-dd' en niet als een timestamp. */ private static ObjectMapper createMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); mapper.setTimeZone(TimeZone.getDefault()); mapper.registerModule(new JavaTimeModule()); return mapper; } @PostConstruct private void init() { mapper = createMapper(); // Bouw een JAX-RS client met JSON support en registreer de keystore met het PKI Overheid // certificaat en private key. De client zal dit certificaat automatisch gebruiken voor // client authenticatie. client = ClientBuilder.newBuilder() .connectTimeout(10, TimeUnit.SECONDS) .keyStore(readStubSISKeyStore(), "password") .register(JacksonJaxbJsonProvider.class) .register(new JacksonObjectMapperProvider(mapper)) .build(); } private KeyStore readStubSISKeyStore() { try (FileInputStream fis = new FileInputStream(System.getProperty("stubsis/tlscertbundle"))) { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(fis, System.getProperty("stubsis/tlscertpassword").toCharArray()); return ks; } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) { throw new RuntimeException(e); } } private String getCamboUrl() { return "https://" + System.getProperty("cambo/hostname"); } /** * Haalt een nieuw access token op als dit nodig is. */ public String ensureToken() { // Als het token nog minimaal 5 minuten geldig is, gebruik dan de oude if (accessTokenExpiresAt.isAfter(Instant.now().plus(5, ChronoUnit.MINUTES))) return accessToken; // StubSIS gebruikt een dummy-OIN met 20x9. Het gebruikte nummer moet overeenkomen het het // OIN in<SUF> URI uri = UriBuilder.fromUri(getCamboUrl()).path("/login/oauth2/token").build(); MultivaluedMap<String, String> form = new MultivaluedHashMap<>(); form.putSingle("client_id", "99999999999999999999"); form.putSingle("grant_type", "client_credentials"); Response response = null; try { response = client.target(uri) .request() .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() != Status.OK.getStatusCode()) { throw new RuntimeException(toJsonString(response.readEntity(ANY_TYPE))); } AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class); accessToken = tokenResponse.getAccessToken().toString(); accessTokenExpiresAt = Instant.now().plus(tokenResponse.getExpiresIn(), ChronoUnit.SECONDS); return accessToken; } finally { close(response); } } protected void close(Response response) { if (response != null) response.close(); } public URI me() { return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/party/me").build(); } public URI endpoints() { return UriBuilder.fromUri(getCamboUrl()).path("/cambo/rest/v1/koppelpunt").build(); } public URI nieuweAanmeldingen(String endpoint) { return UriBuilder.fromUri(getCamboUrl()) .path("/cambo/rest/v1/koppelpunt") .path(endpoint) .path("aanmelding/nieuw") .build(); } public URI aanmeldingen(String endpoint) { return UriBuilder.fromUri(getCamboUrl()) .path("/cambo/rest/v1/koppelpunt") .path(endpoint) .path("aanmelding") .build(); } public Object read(URI uri, Class< ? > responseType) { Response response = null; try { response = client.target(uri) .request(CAMBO_JSON_TYPE) .header("Authorization", "Bearer " + ensureToken()) .get(); if (responseType == null) return response.readEntity(ANY_TYPE); else return response.readEntity(responseType); } finally { close(response); } } public String toJsonString(Object obj) { try { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
True
1,432
16
1,778
15
1,726
15
1,778
15
2,110
16
false
false
false
false
false
true
115
48629_2
package nl.novi.les13.controller; import nl.novi.les13.dto.CourseDto; import nl.novi.les13.model.Course; import nl.novi.les13.model.Lesson; import nl.novi.les13.model.Teacher; import nl.novi.les13.repository.CourseRepository; import nl.novi.les13.repository.LessonRepository; import nl.novi.les13.repository.TeacherRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; @RestController @RequestMapping("/courses") public class CourseController { // ALWAYS USE SERVICES INSTEAD OF REPOSITORIES IN CONTROLLERS!!! private final CourseRepository courseRepository; private final TeacherRepository teacherRepository; private final LessonRepository lessonRepository; public CourseController(CourseRepository courseRepository, TeacherRepository teacherRepository, LessonRepository lessonRepository) { this.courseRepository = courseRepository; this.teacherRepository = teacherRepository; this.lessonRepository = lessonRepository; } @PostMapping public ResponseEntity<CourseDto> createCourse(@RequestBody CourseDto courseDto) { // Normaliter horen de onderstaande 3 regels (Mapper) in de Service: Course course = new Course(); course.setTitle(courseDto.title); course.setSp(courseDto.sp); // Zoiets als: Als docent bestaat, koppel deze dan toe aan de cursus // Het veld in CourseDto teacherIds: for (Long id : courseDto.teacherIds) { Optional<Teacher> ot = teacherRepository.findById(id); if (ot.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false. Teacher teacher = ot.get(); // Optional.get(); - Return the value that's inside the Optional course.getTeachers().add(teacher); } } for (Long id : courseDto.lessonIds) { Optional<Lesson> ol = lessonRepository.findById(id); if (ol.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false. Lesson lesson = ol.get(); // Optional.get(); - Return the value that's inside the Optional course.getLessons().add(lesson); } } courseRepository.save(course); courseDto.id = course.getId(); // Zonder deze regel geeft Postman null als id. return new ResponseEntity<>(courseDto, HttpStatus.CREATED); } }
Aphelion-im/Les-13-uitwerking-opdracht-lesson
src/main/java/nl/novi/les13/controller/CourseController.java
754
// Zoiets als: Als docent bestaat, koppel deze dan toe aan de cursus
line_comment
nl
package nl.novi.les13.controller; import nl.novi.les13.dto.CourseDto; import nl.novi.les13.model.Course; import nl.novi.les13.model.Lesson; import nl.novi.les13.model.Teacher; import nl.novi.les13.repository.CourseRepository; import nl.novi.les13.repository.LessonRepository; import nl.novi.les13.repository.TeacherRepository; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; @RestController @RequestMapping("/courses") public class CourseController { // ALWAYS USE SERVICES INSTEAD OF REPOSITORIES IN CONTROLLERS!!! private final CourseRepository courseRepository; private final TeacherRepository teacherRepository; private final LessonRepository lessonRepository; public CourseController(CourseRepository courseRepository, TeacherRepository teacherRepository, LessonRepository lessonRepository) { this.courseRepository = courseRepository; this.teacherRepository = teacherRepository; this.lessonRepository = lessonRepository; } @PostMapping public ResponseEntity<CourseDto> createCourse(@RequestBody CourseDto courseDto) { // Normaliter horen de onderstaande 3 regels (Mapper) in de Service: Course course = new Course(); course.setTitle(courseDto.title); course.setSp(courseDto.sp); // Zoiets als:<SUF> // Het veld in CourseDto teacherIds: for (Long id : courseDto.teacherIds) { Optional<Teacher> ot = teacherRepository.findById(id); if (ot.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false. Teacher teacher = ot.get(); // Optional.get(); - Return the value that's inside the Optional course.getTeachers().add(teacher); } } for (Long id : courseDto.lessonIds) { Optional<Lesson> ol = lessonRepository.findById(id); if (ol.isPresent()) { // Optional.isPresent(); - Vol of leeg: true/false. Lesson lesson = ol.get(); // Optional.get(); - Return the value that's inside the Optional course.getLessons().add(lesson); } } courseRepository.save(course); courseDto.id = course.getId(); // Zonder deze regel geeft Postman null als id. return new ResponseEntity<>(courseDto, HttpStatus.CREATED); } }
True
539
21
650
22
654
18
650
22
787
21
false
false
false
false
false
true
899
156510_0
package be.kuleuven.speculaas.opgave4; public class Verkoopster { private SpeculaasFabriek speculaasFabriek; public void setSpeculaasFabriek(SpeculaasFabriek speculaasFabriek) { this.speculaasFabriek = speculaasFabriek; } public Verkoopster() { } public double verkoop() { var gebakken = speculaasFabriek.bak(); if(gebakken.size() > 5) { // TODO opgave 4; zie README.md } return 0; } }
KULeuven-Diepenbeek/ses-tdd-exercise-1-template
java/src/main/java/be/kuleuven/speculaas/opgave4/Verkoopster.java
178
// TODO opgave 4; zie README.md
line_comment
nl
package be.kuleuven.speculaas.opgave4; public class Verkoopster { private SpeculaasFabriek speculaasFabriek; public void setSpeculaasFabriek(SpeculaasFabriek speculaasFabriek) { this.speculaasFabriek = speculaasFabriek; } public Verkoopster() { } public double verkoop() { var gebakken = speculaasFabriek.bak(); if(gebakken.size() > 5) { // TODO opgave<SUF> } return 0; } }
False
149
11
159
13
154
11
159
13
192
14
false
false
false
false
false
true
3,770
6529_12
/* ===========================================================_x000D_ * JFreeChart : a free chart library for the Java(tm) platform_x000D_ * ===========================================================_x000D_ *_x000D_ * (C) Copyright 2000-2022, by David Gilbert and Contributors._x000D_ *_x000D_ * Project Info: http://www.jfree.org/jfreechart/index.html_x000D_ *_x000D_ * This library is free software; you can redistribute it and/or modify it_x000D_ * under the terms of the GNU Lesser General Public License as published by_x000D_ * the Free Software Foundation; either version 2.1 of the License, or_x000D_ * (at your option) any later version._x000D_ *_x000D_ * This library is distributed in the hope that it will be useful, but_x000D_ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY_x000D_ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public_x000D_ * License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU Lesser General Public_x000D_ * License along with this library; if not, write to the Free Software_x000D_ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,_x000D_ * USA._x000D_ *_x000D_ * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. _x000D_ * Other names may be trademarks of their respective owners.]_x000D_ *_x000D_ * ---------------------------_x000D_ * NormalizedMatrixSeries.java_x000D_ * ---------------------------_x000D_ * (C) Copyright 2003-2020, by Barak Naveh and Contributors._x000D_ *_x000D_ * Original Author: Barak Naveh;_x000D_ * Contributor(s): David Gilbert;_x000D_ *_x000D_ */_x000D_ _x000D_ package org.jfree.data.xy;_x000D_ _x000D_ /**_x000D_ * Represents a dense normalized matrix M[i,j] where each Mij item of the_x000D_ * matrix has a value (default is 0). When a matrix item is observed using_x000D_ * {@code getItem()} method, it is normalized, that is, divided by the_x000D_ * total sum of all items. It can be also be scaled by setting a scale factor._x000D_ */_x000D_ public class NormalizedMatrixSeries extends MatrixSeries {_x000D_ _x000D_ /** The default scale factor. */_x000D_ public static final double DEFAULT_SCALE_FACTOR = 1.0;_x000D_ _x000D_ /**_x000D_ * A factor that multiplies each item in this series when observed using_x000D_ * getItem method._x000D_ */_x000D_ private double m_scaleFactor = DEFAULT_SCALE_FACTOR;_x000D_ _x000D_ /** The sum of all items in this matrix */_x000D_ private double m_totalSum;_x000D_ _x000D_ /**_x000D_ * Constructor for NormalizedMatrixSeries._x000D_ *_x000D_ * @param name the series name._x000D_ * @param rows the number of rows._x000D_ * @param columns the number of columns._x000D_ */_x000D_ public NormalizedMatrixSeries(String name, int rows, int columns) {_x000D_ super(name, rows, columns);_x000D_ _x000D_ /*_x000D_ * we assum super is always initialized to all-zero matrix, so the_x000D_ * total sum should be 0 upon initialization. However, we set it to_x000D_ * Double.MIN_VALUE to get the same effect and yet avoid division by 0_x000D_ * upon initialization._x000D_ */_x000D_ this.m_totalSum = Double.MIN_VALUE;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an item._x000D_ *_x000D_ * @param itemIndex the index._x000D_ *_x000D_ * @return The value._x000D_ *_x000D_ * @see org.jfree.data.xy.MatrixSeries#getItem(int)_x000D_ */_x000D_ @Override_x000D_ public Number getItem(int itemIndex) {_x000D_ int i = getItemRow(itemIndex);_x000D_ int j = getItemColumn(itemIndex);_x000D_ _x000D_ double mij = get(i, j) * this.m_scaleFactor;_x000D_ Number n = mij / this.m_totalSum;_x000D_ _x000D_ return n;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Sets the factor that multiplies each item in this series when observed_x000D_ * using getItem mehtod._x000D_ *_x000D_ * @param factor new factor to set._x000D_ *_x000D_ * @see #DEFAULT_SCALE_FACTOR_x000D_ */_x000D_ public void setScaleFactor(double factor) {_x000D_ this.m_scaleFactor = factor;_x000D_ // FIXME: this should generate a series change event_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Returns the factor that multiplies each item in this series when_x000D_ * observed using getItem mehtod._x000D_ *_x000D_ * @return The factor_x000D_ */_x000D_ public double getScaleFactor() {_x000D_ return this.m_scaleFactor;_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Updates the value of the specified item in this matrix series._x000D_ *_x000D_ * @param i the row of the item._x000D_ * @param j the column of the item._x000D_ * @param mij the new value for the item._x000D_ *_x000D_ * @see #get(int, int)_x000D_ */_x000D_ @Override_x000D_ public void update(int i, int j, double mij) {_x000D_ this.m_totalSum -= get(i, j);_x000D_ this.m_totalSum += mij;_x000D_ _x000D_ super.update(i, j, mij);_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see org.jfree.data.xy.MatrixSeries#zeroAll()_x000D_ */_x000D_ @Override_x000D_ public void zeroAll() {_x000D_ this.m_totalSum = 0;_x000D_ super.zeroAll();_x000D_ }_x000D_ }_x000D_
nagyist/jfreechart
src/main/java/org/jfree/data/xy/NormalizedMatrixSeries.java
1,382
/**_x000D_ * @see org.jfree.data.xy.MatrixSeries#zeroAll()_x000D_ */
block_comment
nl
/* ===========================================================_x000D_ * JFreeChart : a free chart library for the Java(tm) platform_x000D_ * ===========================================================_x000D_ *_x000D_ * (C) Copyright 2000-2022, by David Gilbert and Contributors._x000D_ *_x000D_ * Project Info: http://www.jfree.org/jfreechart/index.html_x000D_ *_x000D_ * This library is free software; you can redistribute it and/or modify it_x000D_ * under the terms of the GNU Lesser General Public License as published by_x000D_ * the Free Software Foundation; either version 2.1 of the License, or_x000D_ * (at your option) any later version._x000D_ *_x000D_ * This library is distributed in the hope that it will be useful, but_x000D_ * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY_x000D_ * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public_x000D_ * License for more details._x000D_ *_x000D_ * You should have received a copy of the GNU Lesser General Public_x000D_ * License along with this library; if not, write to the Free Software_x000D_ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,_x000D_ * USA._x000D_ *_x000D_ * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. _x000D_ * Other names may be trademarks of their respective owners.]_x000D_ *_x000D_ * ---------------------------_x000D_ * NormalizedMatrixSeries.java_x000D_ * ---------------------------_x000D_ * (C) Copyright 2003-2020, by Barak Naveh and Contributors._x000D_ *_x000D_ * Original Author: Barak Naveh;_x000D_ * Contributor(s): David Gilbert;_x000D_ *_x000D_ */_x000D_ _x000D_ package org.jfree.data.xy;_x000D_ _x000D_ /**_x000D_ * Represents a dense normalized matrix M[i,j] where each Mij item of the_x000D_ * matrix has a value (default is 0). When a matrix item is observed using_x000D_ * {@code getItem()} method, it is normalized, that is, divided by the_x000D_ * total sum of all items. It can be also be scaled by setting a scale factor._x000D_ */_x000D_ public class NormalizedMatrixSeries extends MatrixSeries {_x000D_ _x000D_ /** The default scale factor. */_x000D_ public static final double DEFAULT_SCALE_FACTOR = 1.0;_x000D_ _x000D_ /**_x000D_ * A factor that multiplies each item in this series when observed using_x000D_ * getItem method._x000D_ */_x000D_ private double m_scaleFactor = DEFAULT_SCALE_FACTOR;_x000D_ _x000D_ /** The sum of all items in this matrix */_x000D_ private double m_totalSum;_x000D_ _x000D_ /**_x000D_ * Constructor for NormalizedMatrixSeries._x000D_ *_x000D_ * @param name the series name._x000D_ * @param rows the number of rows._x000D_ * @param columns the number of columns._x000D_ */_x000D_ public NormalizedMatrixSeries(String name, int rows, int columns) {_x000D_ super(name, rows, columns);_x000D_ _x000D_ /*_x000D_ * we assum super is always initialized to all-zero matrix, so the_x000D_ * total sum should be 0 upon initialization. However, we set it to_x000D_ * Double.MIN_VALUE to get the same effect and yet avoid division by 0_x000D_ * upon initialization._x000D_ */_x000D_ this.m_totalSum = Double.MIN_VALUE;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Returns an item._x000D_ *_x000D_ * @param itemIndex the index._x000D_ *_x000D_ * @return The value._x000D_ *_x000D_ * @see org.jfree.data.xy.MatrixSeries#getItem(int)_x000D_ */_x000D_ @Override_x000D_ public Number getItem(int itemIndex) {_x000D_ int i = getItemRow(itemIndex);_x000D_ int j = getItemColumn(itemIndex);_x000D_ _x000D_ double mij = get(i, j) * this.m_scaleFactor;_x000D_ Number n = mij / this.m_totalSum;_x000D_ _x000D_ return n;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Sets the factor that multiplies each item in this series when observed_x000D_ * using getItem mehtod._x000D_ *_x000D_ * @param factor new factor to set._x000D_ *_x000D_ * @see #DEFAULT_SCALE_FACTOR_x000D_ */_x000D_ public void setScaleFactor(double factor) {_x000D_ this.m_scaleFactor = factor;_x000D_ // FIXME: this should generate a series change event_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Returns the factor that multiplies each item in this series when_x000D_ * observed using getItem mehtod._x000D_ *_x000D_ * @return The factor_x000D_ */_x000D_ public double getScaleFactor() {_x000D_ return this.m_scaleFactor;_x000D_ }_x000D_ _x000D_ _x000D_ /**_x000D_ * Updates the value of the specified item in this matrix series._x000D_ *_x000D_ * @param i the row of the item._x000D_ * @param j the column of the item._x000D_ * @param mij the new value for the item._x000D_ *_x000D_ * @see #get(int, int)_x000D_ */_x000D_ @Override_x000D_ public void update(int i, int j, double mij) {_x000D_ this.m_totalSum -= get(i, j);_x000D_ this.m_totalSum += mij;_x000D_ _x000D_ super.update(i, j, mij);_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see org.jfree.data.xy.MatrixSeries#zeroAll()_x000D_ <SUF>*/_x000D_ @Override_x000D_ public void zeroAll() {_x000D_ this.m_totalSum = 0;_x000D_ super.zeroAll();_x000D_ }_x000D_ }_x000D_
False
1,964
32
2,127
35
2,207
37
2,127
35
2,341
38
false
false
false
false
false
true
2,741
142566_12
/* UnderOverAtom.java * ========================================================================= * This file is originally part of the JMathTeX Library - http://jmathtex.sourceforge.net * * Copyright (C) 2004-2007 Universiteit Gent * Copyright (C) 2009-2018 DENIZET Calixte * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License can be found in the file * LICENSE.txt provided with the source distribution of this program (see * the META-INF directory in the source jar). This license can also be * found on the GNU website at http://www.gnu.org/licenses/gpl.html. * * If you did not receive a copy of the GNU General Public License along * with this program, contact the lead developer, or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * Linking this library statically or dynamically with other modules * is making a combined work based on this library. Thus, the terms * and conditions of the GNU General Public License cover the whole * combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce * an executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under terms * of your choice, provided that you also meet, for each linked independent * module, the terms and conditions of the license of that module. * An independent module is a module which is not derived from or based * on this library. If you modify this library, you may extend this exception * to your version of the library, but you are not obliged to do so. * If you do not wish to do so, delete this exception statement from your * version. * */ package com.himamis.retex.renderer.share; /** * An atom representing another atom with an atom above it (if not null) * seperated by a kern and in a smaller size depending on "overScriptSize" * and/or an atom under it (if not null) seperated by a kern and in a smaller * size depending on "underScriptSize" */ public class UnderOverAtom extends Atom implements HasUnderOver { // base, underscript and overscript private final Atom base; private final Atom under; private final Atom over; // kern between base and under- and overscript private final TeXLength underSpace; private final TeXLength overSpace; // whether the under- and overscript should be drawn in a smaller size private final boolean underScriptSize; private final boolean overScriptSize; public UnderOverAtom(Atom base, Atom underOver, TeXLength underOverSpace, boolean underOverScriptSize, boolean over) { this.base = base; if (over) { this.under = null; this.underSpace = TeXLength.getZero(); this.underScriptSize = false; this.over = underOver; this.overSpace = underOverSpace; this.overScriptSize = underOverScriptSize; } else { this.under = underOver; this.underSpace = underOverSpace; this.underScriptSize = underOverScriptSize; this.overSpace = TeXLength.getZero(); this.over = null; this.overScriptSize = false; } } public UnderOverAtom(Atom base, Atom under, TeXLength underSpace, boolean underScriptSize, Atom over, TeXLength overSpace, boolean overScriptSize) { this.base = base; this.under = under; this.underSpace = underSpace; this.underScriptSize = underScriptSize; this.over = over; this.overSpace = overSpace; this.overScriptSize = overScriptSize; } @Override public Box createBox(TeXEnvironment env) { // create boxes in right style and calculate maximum width Box b = base == null ? StrutBox.getEmpty() : base.createBox(env); Box o = null; Box u = null; double max = b.getWidth(); if (over != null) { o = over.createBox(overScriptSize ? env.supStyle() : env); max = Math.max(max, o.getWidth()); } if (under != null) { u = under.createBox(underScriptSize ? env.subStyle() : env); max = Math.max(max, u.getWidth()); } // create vertical box VerticalBox vBox = new VerticalBox(); // last font used by the base (for Mspace atoms following) env.setLastFont(b.getLastFont()); // overscript + space if (over != null) { vBox.add(changeWidth(o, max)); vBox.add(new StrutBox(0., overSpace.getValue(env), 0., 0.)); } // base Box c = changeWidth(b, max); vBox.add(c); // calculate future height of the vertical box (to make sure that the // base // stays on the baseline!) double h = vBox.getHeight() + vBox.getDepth() - c.getDepth(); // underscript + space if (under != null) { vBox.add(new StrutBox(0., underSpace.getValue(env), 0., 0.)); vBox.add(changeWidth(u, max)); } // set height and depth vBox.setDepth(vBox.getHeight() + vBox.getDepth() - h); vBox.setHeight(h); return vBox.setAtom(this); } private static Box changeWidth(Box b, double maxWidth) { if (b != null) { if (Math.abs(maxWidth - b.getWidth()) > TeXFormula.PREC) { return new HorizontalBox(b, maxWidth, TeXConstants.Align.CENTER); } else { b.setHeight(Math.max(b.getHeight(), 0.)); b.setDepth(Math.max(b.getDepth(), 0.)); } } return b; } @Override public int getLeftType() { return base.getLeftType(); } @Override public int getRightType() { return base.getRightType(); } @Override public int getLimits() { return base.getLimits(); } public Atom getUnderOver() { return over == null ? under : over; } public boolean isUnder() { return over == null; } @Override public Atom getTrueBase() { return base; } }
freeenergylab/geogebra
retex/renderer-base/src/main/java/com/himamis/retex/renderer/share/UnderOverAtom.java
1,846
// set height and depth
line_comment
nl
/* UnderOverAtom.java * ========================================================================= * This file is originally part of the JMathTeX Library - http://jmathtex.sourceforge.net * * Copyright (C) 2004-2007 Universiteit Gent * Copyright (C) 2009-2018 DENIZET Calixte * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License can be found in the file * LICENSE.txt provided with the source distribution of this program (see * the META-INF directory in the source jar). This license can also be * found on the GNU website at http://www.gnu.org/licenses/gpl.html. * * If you did not receive a copy of the GNU General Public License along * with this program, contact the lead developer, or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * Linking this library statically or dynamically with other modules * is making a combined work based on this library. Thus, the terms * and conditions of the GNU General Public License cover the whole * combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce * an executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under terms * of your choice, provided that you also meet, for each linked independent * module, the terms and conditions of the license of that module. * An independent module is a module which is not derived from or based * on this library. If you modify this library, you may extend this exception * to your version of the library, but you are not obliged to do so. * If you do not wish to do so, delete this exception statement from your * version. * */ package com.himamis.retex.renderer.share; /** * An atom representing another atom with an atom above it (if not null) * seperated by a kern and in a smaller size depending on "overScriptSize" * and/or an atom under it (if not null) seperated by a kern and in a smaller * size depending on "underScriptSize" */ public class UnderOverAtom extends Atom implements HasUnderOver { // base, underscript and overscript private final Atom base; private final Atom under; private final Atom over; // kern between base and under- and overscript private final TeXLength underSpace; private final TeXLength overSpace; // whether the under- and overscript should be drawn in a smaller size private final boolean underScriptSize; private final boolean overScriptSize; public UnderOverAtom(Atom base, Atom underOver, TeXLength underOverSpace, boolean underOverScriptSize, boolean over) { this.base = base; if (over) { this.under = null; this.underSpace = TeXLength.getZero(); this.underScriptSize = false; this.over = underOver; this.overSpace = underOverSpace; this.overScriptSize = underOverScriptSize; } else { this.under = underOver; this.underSpace = underOverSpace; this.underScriptSize = underOverScriptSize; this.overSpace = TeXLength.getZero(); this.over = null; this.overScriptSize = false; } } public UnderOverAtom(Atom base, Atom under, TeXLength underSpace, boolean underScriptSize, Atom over, TeXLength overSpace, boolean overScriptSize) { this.base = base; this.under = under; this.underSpace = underSpace; this.underScriptSize = underScriptSize; this.over = over; this.overSpace = overSpace; this.overScriptSize = overScriptSize; } @Override public Box createBox(TeXEnvironment env) { // create boxes in right style and calculate maximum width Box b = base == null ? StrutBox.getEmpty() : base.createBox(env); Box o = null; Box u = null; double max = b.getWidth(); if (over != null) { o = over.createBox(overScriptSize ? env.supStyle() : env); max = Math.max(max, o.getWidth()); } if (under != null) { u = under.createBox(underScriptSize ? env.subStyle() : env); max = Math.max(max, u.getWidth()); } // create vertical box VerticalBox vBox = new VerticalBox(); // last font used by the base (for Mspace atoms following) env.setLastFont(b.getLastFont()); // overscript + space if (over != null) { vBox.add(changeWidth(o, max)); vBox.add(new StrutBox(0., overSpace.getValue(env), 0., 0.)); } // base Box c = changeWidth(b, max); vBox.add(c); // calculate future height of the vertical box (to make sure that the // base // stays on the baseline!) double h = vBox.getHeight() + vBox.getDepth() - c.getDepth(); // underscript + space if (under != null) { vBox.add(new StrutBox(0., underSpace.getValue(env), 0., 0.)); vBox.add(changeWidth(u, max)); } // set height<SUF> vBox.setDepth(vBox.getHeight() + vBox.getDepth() - h); vBox.setHeight(h); return vBox.setAtom(this); } private static Box changeWidth(Box b, double maxWidth) { if (b != null) { if (Math.abs(maxWidth - b.getWidth()) > TeXFormula.PREC) { return new HorizontalBox(b, maxWidth, TeXConstants.Align.CENTER); } else { b.setHeight(Math.max(b.getHeight(), 0.)); b.setDepth(Math.max(b.getDepth(), 0.)); } } return b; } @Override public int getLeftType() { return base.getLeftType(); } @Override public int getRightType() { return base.getRightType(); } @Override public int getLimits() { return base.getLimits(); } public Atom getUnderOver() { return over == null ? under : over; } public boolean isUnder() { return over == null; } @Override public Atom getTrueBase() { return base; } }
False
1,554
5
1,783
5
1,764
5
1,783
5
2,013
5
false
false
false
false
false
true
703
199548_4
package com.jstarcraft.core.cache.proxy;_x000D_ _x000D_ import java.lang.reflect.Method;_x000D_ import java.lang.reflect.Modifier;_x000D_ import java.util.HashSet;_x000D_ _x000D_ import com.jstarcraft.core.cache.CacheInformation;_x000D_ import com.jstarcraft.core.cache.annotation.CacheChange;_x000D_ import com.jstarcraft.core.common.conversion.ConversionUtility;_x000D_ import com.jstarcraft.core.utility.StringUtility;_x000D_ _x000D_ import javassist.CtClass;_x000D_ import javassist.CtMethod;_x000D_ _x000D_ /**_x000D_ * 实体代理_x000D_ * _x000D_ * @author Birdy_x000D_ *_x000D_ */_x000D_ public class JavassistEntityProxy extends JavassistProxy {_x000D_ _x000D_ public JavassistEntityProxy(ProxyManager proxyManager, CacheInformation cacheInformation) {_x000D_ super(proxyManager, cacheInformation);_x000D_ }_x000D_ _x000D_ /**_x000D_ * 代理方法_x000D_ * _x000D_ * <pre>_x000D_ * // TODO 索引变更部分_x000D_ * CacheInformation cacheInformation = _manager.getCacheInformation();_x000D_ * String[] values = _indexChange != null ? _indexChange.values() : new String[] {};_x000D_ * TreeSet<String> indexNames = new TreeSet(Arrays.asList(values));_x000D_ * LinkedList<Lock> locks = new LinkedList<Lock>();_x000D_ * for (String name : indexNames) {_x000D_ * locks.addLast(cacheInformation.getIndexWriteLock(name));_x000D_ * }_x000D_ * Object value = null;_x000D_ * try {_x000D_ * for (Lock lock : locks) {_x000D_ * lock.lock();_x000D_ * }_x000D_ * Map<String, Object> oldIndexValues = cacheInformation.getIndexValues(_object, indexNames);_x000D_ * value = method.invoke(_object);_x000D_ * Map<String, Object> newIndexValues = cacheInformation.getIndexValues(_object, indexNames);_x000D_ * boolean result = true;_x000D_ * for (Entry<String, Object> entry : newIndexValues.entrySet()) {_x000D_ * if (_manager.hasUnique(entry.getKey(), entry.getValue())) {_x000D_ * result = false;_x000D_ * break;_x000D_ * }_x000D_ * }_x000D_ * if (result) {_x000D_ * for (Entry<String, Object> entry : newIndexValues.entrySet()) {_x000D_ * _manager.modifyUnique(_object.getId(), entry.getKey(), entry.getValue());_x000D_ * }_x000D_ * } else {_x000D_ * cacheInformation.setIndexValues(_object, oldIndexValues);_x000D_ * }_x000D_ * } finally {_x000D_ * for (Lock lock : locks) {_x000D_ * lock.unlock();_x000D_ * }_x000D_ * }_x000D_ * // TODO 数据变更部分_x000D_ * if (_dataChange != null) {_x000D_ * if (returnType == void.class) {_x000D_ * _manager.modifyDatas(_object.getId(), _object);_x000D_ * } else {_x000D_ * TreeSet<String> resultValues = new TreeSet(Arrays.asList(_dataChange.values()));_x000D_ * if (resultValues.contains(value.toString())) {_x000D_ * _manager.modifyDatas(_object.getId(), _object);_x000D_ * }_x000D_ * }_x000D_ * }_x000D_ * // TODO 返回值部分_x000D_ * if (returnType != void.class) {_x000D_ * return value;_x000D_ * }_x000D_ * </pre>_x000D_ */_x000D_ final void proxyMethod(Class<?> clazz, CtClass proxyClazz, Method method, CacheChange cacheChange) throws Exception {_x000D_ Class<?> returnType = method.getReturnType();_x000D_ CtMethod proxyMethod = new CtMethod(classPool.get(returnType.getName()), method.getName(), toProxyClasses(method.getParameterTypes()), proxyClazz);_x000D_ proxyMethod.setModifiers(Modifier.PUBLIC);_x000D_ if (method.getExceptionTypes().length != 0) {_x000D_ proxyMethod.setExceptionTypes(toProxyClasses(method.getExceptionTypes()));_x000D_ }_x000D_ StringBuilder methodBuffer = new StringBuilder("{");_x000D_ methodBuffer.append(StringUtility.format("{} methodId = {}.valueOf({});", Integer.class.getName(), Integer.class.getName(), cacheInformation.getMethodId(method)));_x000D_ methodBuffer.append(StringUtility.format("{} changeValues = _information.getMethodChanges(methodId);", HashSet.class.getName()));_x000D_ // TODO 索引变更部分_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format("{} indexNames = ({})_x000D_ // (keyValue.getKey());", TreeSet.class.getName(), TreeSet.class.getName()));_x000D_ // methodBuilder.append(StringUtility.format("{} newIndexValues = new {}();",_x000D_ // HashMap.class.getName(), HashMap.class.getName()));_x000D_ // for (Entry<IndexChange, Integer> entry : indexChanges.entrySet()) {_x000D_ // methodBuilder.append(StringUtility.format("indexNames.add(\"{}\");",_x000D_ // entry.getKey().value()));_x000D_ // methodBuilder.append(StringUtility.format("newIndexValues.put(\"{}\",_x000D_ // {}.primitiveToWrap(${}));", entry.getKey().value(),_x000D_ // ConversionUtility.class.getName(), entry.getValue()));_x000D_ // }_x000D_ // }_x000D_ if (returnType != void.class) {_x000D_ String typeName = returnType.isArray() ? toArrayType(returnType) : returnType.getName();_x000D_ if (returnType.isPrimitive()) {_x000D_ methodBuffer.append(StringUtility.format("{} value;", typeName));_x000D_ } else {_x000D_ methodBuffer.append(StringUtility.format("{} value = null;", typeName));_x000D_ }_x000D_ }_x000D_ methodBuffer.append(StringUtility.format("try {"));_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format("_x000D_ // _information.lockIndexWriteLocks(indexNames);"));_x000D_ // methodBuilder.append(StringUtility.format(" {} checkIterator =_x000D_ // newIndexValues.entrySet().iterator();", Iterator.class.getName()));_x000D_ // methodBuilder.append(StringUtility.format(" while(checkIterator.hasNext())_x000D_ // {"));_x000D_ // methodBuilder.append(StringUtility.format(" {} entry =_x000D_ // checkIterator.next();", Entry.class.getName()));_x000D_ // methodBuilder.append(StringUtility.format(" boolean has =_x000D_ // _manager.hasIndex((String) entry.getKey(), entry.getValue());"));_x000D_ // methodBuilder.append(StringUtility.format(" if (has) {"));_x000D_ // methodBuilder.append(StringUtility.format(" throw new {}();",_x000D_ // JavassistEntityProxy.TYPE_INDEX_EXCEPTION));_x000D_ // methodBuilder.append(StringUtility.format(" }"));_x000D_ // methodBuilder.append(StringUtility.format(" }"));_x000D_ // methodBuilder.append(StringUtility.format(" {} oldIndexValues =_x000D_ // _information.getIndexValues(_instance, indexNames);", Map.class.getName()));_x000D_ // }_x000D_ if (returnType != void.class) {_x000D_ methodBuffer.append(StringUtility.format(" value = super.{}($$);", method.getName()));_x000D_ } else {_x000D_ methodBuffer.append(StringUtility.format(" super.{}($$);", method.getName()));_x000D_ }_x000D_ // TODO 数据变更部分_x000D_ if (cacheChange != null) {_x000D_ if (returnType == void.class) {_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,_x000D_ // newIndexValues, oldIndexValues);"));_x000D_ // }_x000D_ methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));_x000D_ } else {_x000D_ if (cacheChange.values().length > 0) {_x000D_ methodBuffer.append(StringUtility.format(" if (changeValues.contains({}.primitiveToWrap(value))) {", ConversionUtility.class.getName()));_x000D_ }_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,_x000D_ // newIndexValues, oldIndexValues);"));_x000D_ // }_x000D_ methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));_x000D_ if (cacheChange.values().length > 0) {_x000D_ methodBuffer.append(StringUtility.format(" }"));_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,_x000D_ // newIndexValues, oldIndexValues);"));_x000D_ // }_x000D_ }_x000D_ methodBuffer.append(StringUtility.format("} finally {"));_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format("_x000D_ // _information.unlockIndexWriteLocks(indexNames);"));_x000D_ // }_x000D_ methodBuffer.append(StringUtility.format("}"));_x000D_ // TODO 返回值部分_x000D_ if (returnType != void.class) {_x000D_ methodBuffer.append(StringUtility.format("return value;"));_x000D_ }_x000D_ methodBuffer.append(StringUtility.format("}"));_x000D_ proxyMethod.setBody(methodBuffer.toString());_x000D_ proxyClazz.addMethod(proxyMethod);_x000D_ }_x000D_ _x000D_ }_x000D_
HongZhaoHua/jstarcraft-core
jstarcraft-core-cache/src/main/java/com/jstarcraft/core/cache/proxy/JavassistEntityProxy.java
2,391
// (keyValue.getKey());", TreeSet.class.getName(), TreeSet.class.getName()));_x000D_
line_comment
nl
package com.jstarcraft.core.cache.proxy;_x000D_ _x000D_ import java.lang.reflect.Method;_x000D_ import java.lang.reflect.Modifier;_x000D_ import java.util.HashSet;_x000D_ _x000D_ import com.jstarcraft.core.cache.CacheInformation;_x000D_ import com.jstarcraft.core.cache.annotation.CacheChange;_x000D_ import com.jstarcraft.core.common.conversion.ConversionUtility;_x000D_ import com.jstarcraft.core.utility.StringUtility;_x000D_ _x000D_ import javassist.CtClass;_x000D_ import javassist.CtMethod;_x000D_ _x000D_ /**_x000D_ * 实体代理_x000D_ * _x000D_ * @author Birdy_x000D_ *_x000D_ */_x000D_ public class JavassistEntityProxy extends JavassistProxy {_x000D_ _x000D_ public JavassistEntityProxy(ProxyManager proxyManager, CacheInformation cacheInformation) {_x000D_ super(proxyManager, cacheInformation);_x000D_ }_x000D_ _x000D_ /**_x000D_ * 代理方法_x000D_ * _x000D_ * <pre>_x000D_ * // TODO 索引变更部分_x000D_ * CacheInformation cacheInformation = _manager.getCacheInformation();_x000D_ * String[] values = _indexChange != null ? _indexChange.values() : new String[] {};_x000D_ * TreeSet<String> indexNames = new TreeSet(Arrays.asList(values));_x000D_ * LinkedList<Lock> locks = new LinkedList<Lock>();_x000D_ * for (String name : indexNames) {_x000D_ * locks.addLast(cacheInformation.getIndexWriteLock(name));_x000D_ * }_x000D_ * Object value = null;_x000D_ * try {_x000D_ * for (Lock lock : locks) {_x000D_ * lock.lock();_x000D_ * }_x000D_ * Map<String, Object> oldIndexValues = cacheInformation.getIndexValues(_object, indexNames);_x000D_ * value = method.invoke(_object);_x000D_ * Map<String, Object> newIndexValues = cacheInformation.getIndexValues(_object, indexNames);_x000D_ * boolean result = true;_x000D_ * for (Entry<String, Object> entry : newIndexValues.entrySet()) {_x000D_ * if (_manager.hasUnique(entry.getKey(), entry.getValue())) {_x000D_ * result = false;_x000D_ * break;_x000D_ * }_x000D_ * }_x000D_ * if (result) {_x000D_ * for (Entry<String, Object> entry : newIndexValues.entrySet()) {_x000D_ * _manager.modifyUnique(_object.getId(), entry.getKey(), entry.getValue());_x000D_ * }_x000D_ * } else {_x000D_ * cacheInformation.setIndexValues(_object, oldIndexValues);_x000D_ * }_x000D_ * } finally {_x000D_ * for (Lock lock : locks) {_x000D_ * lock.unlock();_x000D_ * }_x000D_ * }_x000D_ * // TODO 数据变更部分_x000D_ * if (_dataChange != null) {_x000D_ * if (returnType == void.class) {_x000D_ * _manager.modifyDatas(_object.getId(), _object);_x000D_ * } else {_x000D_ * TreeSet<String> resultValues = new TreeSet(Arrays.asList(_dataChange.values()));_x000D_ * if (resultValues.contains(value.toString())) {_x000D_ * _manager.modifyDatas(_object.getId(), _object);_x000D_ * }_x000D_ * }_x000D_ * }_x000D_ * // TODO 返回值部分_x000D_ * if (returnType != void.class) {_x000D_ * return value;_x000D_ * }_x000D_ * </pre>_x000D_ */_x000D_ final void proxyMethod(Class<?> clazz, CtClass proxyClazz, Method method, CacheChange cacheChange) throws Exception {_x000D_ Class<?> returnType = method.getReturnType();_x000D_ CtMethod proxyMethod = new CtMethod(classPool.get(returnType.getName()), method.getName(), toProxyClasses(method.getParameterTypes()), proxyClazz);_x000D_ proxyMethod.setModifiers(Modifier.PUBLIC);_x000D_ if (method.getExceptionTypes().length != 0) {_x000D_ proxyMethod.setExceptionTypes(toProxyClasses(method.getExceptionTypes()));_x000D_ }_x000D_ StringBuilder methodBuffer = new StringBuilder("{");_x000D_ methodBuffer.append(StringUtility.format("{} methodId = {}.valueOf({});", Integer.class.getName(), Integer.class.getName(), cacheInformation.getMethodId(method)));_x000D_ methodBuffer.append(StringUtility.format("{} changeValues = _information.getMethodChanges(methodId);", HashSet.class.getName()));_x000D_ // TODO 索引变更部分_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format("{} indexNames = ({})_x000D_ // (keyValue.getKey());", TreeSet.class.getName(),<SUF> // methodBuilder.append(StringUtility.format("{} newIndexValues = new {}();",_x000D_ // HashMap.class.getName(), HashMap.class.getName()));_x000D_ // for (Entry<IndexChange, Integer> entry : indexChanges.entrySet()) {_x000D_ // methodBuilder.append(StringUtility.format("indexNames.add(\"{}\");",_x000D_ // entry.getKey().value()));_x000D_ // methodBuilder.append(StringUtility.format("newIndexValues.put(\"{}\",_x000D_ // {}.primitiveToWrap(${}));", entry.getKey().value(),_x000D_ // ConversionUtility.class.getName(), entry.getValue()));_x000D_ // }_x000D_ // }_x000D_ if (returnType != void.class) {_x000D_ String typeName = returnType.isArray() ? toArrayType(returnType) : returnType.getName();_x000D_ if (returnType.isPrimitive()) {_x000D_ methodBuffer.append(StringUtility.format("{} value;", typeName));_x000D_ } else {_x000D_ methodBuffer.append(StringUtility.format("{} value = null;", typeName));_x000D_ }_x000D_ }_x000D_ methodBuffer.append(StringUtility.format("try {"));_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format("_x000D_ // _information.lockIndexWriteLocks(indexNames);"));_x000D_ // methodBuilder.append(StringUtility.format(" {} checkIterator =_x000D_ // newIndexValues.entrySet().iterator();", Iterator.class.getName()));_x000D_ // methodBuilder.append(StringUtility.format(" while(checkIterator.hasNext())_x000D_ // {"));_x000D_ // methodBuilder.append(StringUtility.format(" {} entry =_x000D_ // checkIterator.next();", Entry.class.getName()));_x000D_ // methodBuilder.append(StringUtility.format(" boolean has =_x000D_ // _manager.hasIndex((String) entry.getKey(), entry.getValue());"));_x000D_ // methodBuilder.append(StringUtility.format(" if (has) {"));_x000D_ // methodBuilder.append(StringUtility.format(" throw new {}();",_x000D_ // JavassistEntityProxy.TYPE_INDEX_EXCEPTION));_x000D_ // methodBuilder.append(StringUtility.format(" }"));_x000D_ // methodBuilder.append(StringUtility.format(" }"));_x000D_ // methodBuilder.append(StringUtility.format(" {} oldIndexValues =_x000D_ // _information.getIndexValues(_instance, indexNames);", Map.class.getName()));_x000D_ // }_x000D_ if (returnType != void.class) {_x000D_ methodBuffer.append(StringUtility.format(" value = super.{}($$);", method.getName()));_x000D_ } else {_x000D_ methodBuffer.append(StringUtility.format(" super.{}($$);", method.getName()));_x000D_ }_x000D_ // TODO 数据变更部分_x000D_ if (cacheChange != null) {_x000D_ if (returnType == void.class) {_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,_x000D_ // newIndexValues, oldIndexValues);"));_x000D_ // }_x000D_ methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));_x000D_ } else {_x000D_ if (cacheChange.values().length > 0) {_x000D_ methodBuffer.append(StringUtility.format(" if (changeValues.contains({}.primitiveToWrap(value))) {", ConversionUtility.class.getName()));_x000D_ }_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,_x000D_ // newIndexValues, oldIndexValues);"));_x000D_ // }_x000D_ methodBuffer.append(StringUtility.format(" _manager.modifyInstance(this);"));_x000D_ if (cacheChange.values().length > 0) {_x000D_ methodBuffer.append(StringUtility.format(" }"));_x000D_ }_x000D_ }_x000D_ } else {_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format(" _manager.modifyIndexes(_instance,_x000D_ // newIndexValues, oldIndexValues);"));_x000D_ // }_x000D_ }_x000D_ methodBuffer.append(StringUtility.format("} finally {"));_x000D_ // if (!indexChanges.isEmpty()) {_x000D_ // methodBuilder.append(StringUtility.format("_x000D_ // _information.unlockIndexWriteLocks(indexNames);"));_x000D_ // }_x000D_ methodBuffer.append(StringUtility.format("}"));_x000D_ // TODO 返回值部分_x000D_ if (returnType != void.class) {_x000D_ methodBuffer.append(StringUtility.format("return value;"));_x000D_ }_x000D_ methodBuffer.append(StringUtility.format("}"));_x000D_ proxyMethod.setBody(methodBuffer.toString());_x000D_ proxyClazz.addMethod(proxyMethod);_x000D_ }_x000D_ _x000D_ }_x000D_
False
2,894
22
3,199
29
3,337
26
3,199
29
3,599
30
false
false
false
false
false
true
301
36429_1
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.util; import org.pepsoft.util.mdc.MDCCapturingRuntimeException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import static org.pepsoft.util.SystemUtils.JAVA_9; import static org.pepsoft.util.SystemUtils.JAVA_VERSION; /** * * @author pepijn */ public class MemoryUtils { /** * Get the memory used by a particular object instance in bytes. To prevent runaway * * @param object The object of which to determine the memory used. * @param stopAt Types of references which should not be followed. * @return The number of bytes of RAM used by the object, or -1 if the size * could not be determined. */ public static long getSize(Object object, Set<Class<?>> stopAt) { if (object == null) { return 0L; } else if (JAVA_VERSION.isAtLeast(JAVA_9)) { // TODO: support Java 9 return -1L; } else { IdentityHashMap<Object, Void> processedObjects = new IdentityHashMap<>(); return getSize(object, processedObjects, stopAt/*, "root"*/); } } private static long getSize(Object object, IdentityHashMap<Object, Void> processedObjects, Set<Class<?>> stopAt/*, String trail*/) { if (processedObjects.containsKey(object)) { // This object has already been counted return 0L; } else { // Record that this object has been counted processedObjects.put(object, null); Class<?> type = object.getClass(); if ((stopAt != null) && (! stopAt.isEmpty())) { for (Class<?> stopClass: stopAt) { if (stopClass.isAssignableFrom(type)) { return 0L; } } } long objectSize = 8L; // Housekeeping if (type.isArray()) { objectSize += 4L; // Array length Class<?> arrayType = type.getComponentType(); if (arrayType.isPrimitive()) { if (arrayType == boolean.class) { objectSize += ((boolean[]) object).length; } else if (arrayType == byte.class) { objectSize += ((byte[]) object).length; } else if (arrayType == char.class) { objectSize += ((char[]) object).length * 2L; } else if (arrayType == short.class) { objectSize += ((short[]) object).length * 2L; } else if (arrayType == int.class) { objectSize += ((int[]) object).length * 4L; } else if (arrayType == float.class) { objectSize += ((float[]) object).length * 4L; } else if (arrayType == long.class) { objectSize += ((long[]) object).length * 8L; } else { objectSize += ((double[]) object).length * 8L; } } else { Object[] array = (Object[]) object; objectSize = array.length * 4L; // References for (Object anArray : array) { if (anArray != null) { objectSize += getSize(anArray, processedObjects, stopAt/*, trail + '[' + i + ']'*/); } } } } else if (type.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(type); } else { Class<?> myType = type; while (myType != null) { Field[] fields = myType.getDeclaredFields(); for (Field field: fields) { if (Modifier.isStatic(field.getModifiers())) { continue; } Class<?> fieldType = field.getType(); if (fieldType.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(fieldType); } else { objectSize += 4L; // Reference field.setAccessible(true); // Will fail if a security manager is installed! try { Object value = field.get(object); if (value != null) { objectSize += getSize(value, processedObjects, stopAt/*, trail + '.' + field.getName()*/); } } catch (IllegalAccessException e) { throw new MDCCapturingRuntimeException("Access denied trying to read field " + field.getName() + " of type " + myType.getName(), e); } } } myType = myType.getSuperclass(); } } if ((objectSize % 8L) != 0L) { objectSize = ((objectSize >> 3) + 1L) << 3; } // System.out.println(trail + " (" + type.getSimpleName() + "): " + objectSize); return objectSize; } } private static final Map<Class<?>, Long> PRIMITIVE_TYPE_SIZES = new HashMap<>(); static { PRIMITIVE_TYPE_SIZES.put(boolean.class, 1L); PRIMITIVE_TYPE_SIZES.put(byte.class, 1L); PRIMITIVE_TYPE_SIZES.put(char.class, 2L); PRIMITIVE_TYPE_SIZES.put(short.class, 2L); PRIMITIVE_TYPE_SIZES.put(int.class, 4L); PRIMITIVE_TYPE_SIZES.put(float.class, 4L); PRIMITIVE_TYPE_SIZES.put(long.class, 8L); PRIMITIVE_TYPE_SIZES.put(double.class, 8L); } }
Captain-Chaos/Utils
src/main/java/org/pepsoft/util/MemoryUtils.java
1,630
/** * * @author pepijn */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pepsoft.util; import org.pepsoft.util.mdc.MDCCapturingRuntimeException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Map; import java.util.Set; import static org.pepsoft.util.SystemUtils.JAVA_9; import static org.pepsoft.util.SystemUtils.JAVA_VERSION; /** * * @author pepijn <SUF>*/ public class MemoryUtils { /** * Get the memory used by a particular object instance in bytes. To prevent runaway * * @param object The object of which to determine the memory used. * @param stopAt Types of references which should not be followed. * @return The number of bytes of RAM used by the object, or -1 if the size * could not be determined. */ public static long getSize(Object object, Set<Class<?>> stopAt) { if (object == null) { return 0L; } else if (JAVA_VERSION.isAtLeast(JAVA_9)) { // TODO: support Java 9 return -1L; } else { IdentityHashMap<Object, Void> processedObjects = new IdentityHashMap<>(); return getSize(object, processedObjects, stopAt/*, "root"*/); } } private static long getSize(Object object, IdentityHashMap<Object, Void> processedObjects, Set<Class<?>> stopAt/*, String trail*/) { if (processedObjects.containsKey(object)) { // This object has already been counted return 0L; } else { // Record that this object has been counted processedObjects.put(object, null); Class<?> type = object.getClass(); if ((stopAt != null) && (! stopAt.isEmpty())) { for (Class<?> stopClass: stopAt) { if (stopClass.isAssignableFrom(type)) { return 0L; } } } long objectSize = 8L; // Housekeeping if (type.isArray()) { objectSize += 4L; // Array length Class<?> arrayType = type.getComponentType(); if (arrayType.isPrimitive()) { if (arrayType == boolean.class) { objectSize += ((boolean[]) object).length; } else if (arrayType == byte.class) { objectSize += ((byte[]) object).length; } else if (arrayType == char.class) { objectSize += ((char[]) object).length * 2L; } else if (arrayType == short.class) { objectSize += ((short[]) object).length * 2L; } else if (arrayType == int.class) { objectSize += ((int[]) object).length * 4L; } else if (arrayType == float.class) { objectSize += ((float[]) object).length * 4L; } else if (arrayType == long.class) { objectSize += ((long[]) object).length * 8L; } else { objectSize += ((double[]) object).length * 8L; } } else { Object[] array = (Object[]) object; objectSize = array.length * 4L; // References for (Object anArray : array) { if (anArray != null) { objectSize += getSize(anArray, processedObjects, stopAt/*, trail + '[' + i + ']'*/); } } } } else if (type.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(type); } else { Class<?> myType = type; while (myType != null) { Field[] fields = myType.getDeclaredFields(); for (Field field: fields) { if (Modifier.isStatic(field.getModifiers())) { continue; } Class<?> fieldType = field.getType(); if (fieldType.isPrimitive()) { objectSize += PRIMITIVE_TYPE_SIZES.get(fieldType); } else { objectSize += 4L; // Reference field.setAccessible(true); // Will fail if a security manager is installed! try { Object value = field.get(object); if (value != null) { objectSize += getSize(value, processedObjects, stopAt/*, trail + '.' + field.getName()*/); } } catch (IllegalAccessException e) { throw new MDCCapturingRuntimeException("Access denied trying to read field " + field.getName() + " of type " + myType.getName(), e); } } } myType = myType.getSuperclass(); } } if ((objectSize % 8L) != 0L) { objectSize = ((objectSize >> 3) + 1L) << 3; } // System.out.println(trail + " (" + type.getSimpleName() + "): " + objectSize); return objectSize; } } private static final Map<Class<?>, Long> PRIMITIVE_TYPE_SIZES = new HashMap<>(); static { PRIMITIVE_TYPE_SIZES.put(boolean.class, 1L); PRIMITIVE_TYPE_SIZES.put(byte.class, 1L); PRIMITIVE_TYPE_SIZES.put(char.class, 2L); PRIMITIVE_TYPE_SIZES.put(short.class, 2L); PRIMITIVE_TYPE_SIZES.put(int.class, 4L); PRIMITIVE_TYPE_SIZES.put(float.class, 4L); PRIMITIVE_TYPE_SIZES.put(long.class, 8L); PRIMITIVE_TYPE_SIZES.put(double.class, 8L); } }
False
1,219
9
1,357
11
1,443
11
1,357
11
1,603
12
false
false
false
false
false
true
1,364
27352_1
import greenfoot.*; /** * * @author R. Springer */ public class Hero extends Mover { private final double gravity; private final double acc; private final double drag; private int width; private boolean isOnGround; private int walkStatus; private int status = 0; private String direction = "right"; public int lives = 2; public Hero() { super(); gravity = 9.8; acc = 0.6; drag = 0.8; setImage("p2_stand.png"); } @Override public void act() { handleInput(); velocityX *= drag; velocityY += acc; if (velocityY > gravity) { velocityY = gravity; } applyVelocity(); for (Actor enemy : getIntersectingObjects(Enemy.class)) { if (enemy != null) { dood(); break; } } } public void dood() { lives--; if (lives > 0) { setLocation(200, 700); } else { getWorld().removeObject(this); } } private double posToNeg(double x) { return (x - (x * 2)); } public void handleInput() { //gekregen van Gijs de Lange en zelf iets veranderd. width = getImage().getWidth() / 2; Tile tile = (Tile) getOneObjectAtOffset(0, getImage().getHeight() / 2 + 1, Tile.class); if (tile == null) { tile = (Tile) getOneObjectAtOffset(this.width - 3, getImage().getHeight() / 2 + 1, Tile.class); } if (tile == null) { tile = (Tile) getOneObjectAtOffset((int) posToNeg(this.width) + 3, getImage().getHeight() / 2 + 1, Tile.class); } if (tile != null && tile.isSolid) { isOnGround = true; } else { isOnGround = false; } if (Greenfoot.isKeyDown("space")) { if (isOnGround) { velocityY = -12; animationJump(getWidth(), getHeight(), 2); } } if (Greenfoot.isKeyDown("a")) { velocityX = -10; direction = "left"; animationWalk(getWidth(), getHeight(), 2); } else if (Greenfoot.isKeyDown("d")) { velocityX = 10; direction = "right"; animationWalk(getWidth(), getHeight(), 2); } else { animationStand(getWidth(), getHeight(), 2); } } public void animationWalk(int width, int heigth, int player) { if (status == 2) { if (walkStatus >= 11) { walkStatus = 1; } if (isOnGround) { setImage("p" + player + "_walk" + walkStatus + ".png"); } else { setImage("p" + player + "_jump.png"); } mirror(); walkStatus++; status = 0; } else { status++; } getImage().scale(width, heigth); } public void animationJump(int width, int heigth, int player) { setImage("p" + player + "_jump.png"); mirror(); getImage().scale(width, heigth); } public void animationStand(int width, int heigth, int player) { if (isOnGround) { setImage("p" + player + "_walk1.png"); getImage().scale(width, heigth); walkStatus = 1; } else { setImage("p" + player + "_jump.png"); } mirror(); getImage().scale(width, heigth); } public void mirror() { if (direction.equals("left")) { getImage().mirrorHorizontally(); } }public int getWidth() { return getImage().getWidth(); } public int getHeight() { return getImage().getHeight(); } }
ROCMondriaanTIN/project-greenfoot-game-302675564
Hero.java
1,160
//gekregen van Gijs de Lange en zelf iets veranderd.
line_comment
nl
import greenfoot.*; /** * * @author R. Springer */ public class Hero extends Mover { private final double gravity; private final double acc; private final double drag; private int width; private boolean isOnGround; private int walkStatus; private int status = 0; private String direction = "right"; public int lives = 2; public Hero() { super(); gravity = 9.8; acc = 0.6; drag = 0.8; setImage("p2_stand.png"); } @Override public void act() { handleInput(); velocityX *= drag; velocityY += acc; if (velocityY > gravity) { velocityY = gravity; } applyVelocity(); for (Actor enemy : getIntersectingObjects(Enemy.class)) { if (enemy != null) { dood(); break; } } } public void dood() { lives--; if (lives > 0) { setLocation(200, 700); } else { getWorld().removeObject(this); } } private double posToNeg(double x) { return (x - (x * 2)); } public void handleInput() { //gekregen van<SUF> width = getImage().getWidth() / 2; Tile tile = (Tile) getOneObjectAtOffset(0, getImage().getHeight() / 2 + 1, Tile.class); if (tile == null) { tile = (Tile) getOneObjectAtOffset(this.width - 3, getImage().getHeight() / 2 + 1, Tile.class); } if (tile == null) { tile = (Tile) getOneObjectAtOffset((int) posToNeg(this.width) + 3, getImage().getHeight() / 2 + 1, Tile.class); } if (tile != null && tile.isSolid) { isOnGround = true; } else { isOnGround = false; } if (Greenfoot.isKeyDown("space")) { if (isOnGround) { velocityY = -12; animationJump(getWidth(), getHeight(), 2); } } if (Greenfoot.isKeyDown("a")) { velocityX = -10; direction = "left"; animationWalk(getWidth(), getHeight(), 2); } else if (Greenfoot.isKeyDown("d")) { velocityX = 10; direction = "right"; animationWalk(getWidth(), getHeight(), 2); } else { animationStand(getWidth(), getHeight(), 2); } } public void animationWalk(int width, int heigth, int player) { if (status == 2) { if (walkStatus >= 11) { walkStatus = 1; } if (isOnGround) { setImage("p" + player + "_walk" + walkStatus + ".png"); } else { setImage("p" + player + "_jump.png"); } mirror(); walkStatus++; status = 0; } else { status++; } getImage().scale(width, heigth); } public void animationJump(int width, int heigth, int player) { setImage("p" + player + "_jump.png"); mirror(); getImage().scale(width, heigth); } public void animationStand(int width, int heigth, int player) { if (isOnGround) { setImage("p" + player + "_walk1.png"); getImage().scale(width, heigth); walkStatus = 1; } else { setImage("p" + player + "_jump.png"); } mirror(); getImage().scale(width, heigth); } public void mirror() { if (direction.equals("left")) { getImage().mirrorHorizontally(); } }public int getWidth() { return getImage().getWidth(); } public int getHeight() { return getImage().getHeight(); } }
False
907
17
961
21
1,052
14
961
21
1,171
20
false
false
false
false
false
true
1,560
100445_7
package com.mobsoft.pxlapp.activities.kalender; import java.io.IOException; import java.util.ArrayList; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.text.Html; import android.text.Spanned; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; import com.mobsoft.pxlapp.R; public class KalenderActivity extends Activity { private Spinner spinner; private Kalender kalenderVolledig; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_kalender); // Show the Up button in the action bar. setupActionBar(); toonKalender(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.kalender, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public void toonKalender() { spinner = (Spinner) findViewById(R.id.soortSpinner); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { String waarde = spinner.getSelectedItem().toString(); updateKalender(waarde); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); try { this.kalenderVolledig = Kalender.kalenderVanBestand(this); tekenKalender(kalenderVolledig); } catch (IOException e) { e.printStackTrace(); } } private void updateKalender(String waarde) { Kalender kalender = kalenderVolledig.filterKalender(waarde); tekenKalender(kalender); } private void tekenKalender(Kalender kalender) { LijnRechts lijnRechts; LijnOnder lijnOnder; TableLayout tabel = (TableLayout) findViewById(R.id.KalenderTable); tabel.removeAllViews(); ArrayList<String> titels = kalender.getTitels(); TableRow tableRow = new TableRow(this); for (int i = 0; i < titels.size(); i++) { KalenderTextView txtTitel = new KalenderTextView(this, titels.get(i)); txtTitel.setTypeface(Typeface.DEFAULT_BOLD); tableRow.addView(txtTitel); if (i < titels.size() - 1) { lijnRechts = new LijnRechts(this); tableRow.addView(lijnRechts); } } tabel.addView(tableRow); lijnOnder = new LijnOnder(this); tabel.addView(lijnOnder); for (int i = 0; i < kalender.getRijen().size(); i++) { KalenderRij rij = kalender.getRij(i); TableRow tr = new TableRow(this); tr.setBackgroundColor(getCelColor(rij.getType())); KalenderTextView txtCel = new KalenderTextView(this, rij.getDatum().toString("dd/MM/yy")); tr.addView(txtCel); lijnRechts = new LijnRechts(this); tr.addView(lijnRechts); for (int j = 0; j < rij.getCellen().size(); j++) { KalenderCel cel = rij.getCel(j); if (cel.getTekst().contains("<br />")) { txtCel = new KalenderTextView(this, Html.fromHtml(cel.getTekst())); } else { txtCel = new KalenderTextView(this, cel.getTekst()); } txtCel.setBackgroundColor(getCelColor(cel.getType())); tr.addView(txtCel); if (j < kalender.getRij(i).getCellen().size() - 1) { lijnRechts = new LijnRechts(this); tr.addView(lijnRechts); } } tabel.addView(tr); lijnOnder = new LijnOnder(this); tabel.addView(lijnOnder); } } private int getCelColor(KalenderType type) { if (type == KalenderType.EXAMEN) { return getResources().getColor(R.color.roze2); } else if (type == KalenderType.VRIJ) { return getResources().getColor(R.color.groen2); } else if (type == KalenderType.DELIBERATIE) { return getResources().getColor(R.color.paars2); } else if (type == KalenderType.VAKANTIE) { return getResources().getColor(R.color.oranje2); } else { return 0x00000000; //Alpha-kanaal is nul, dus is volledig doorzichtig. } } public void toonLegende(View view) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout dialog.setView(inflater.inflate(R.layout.kalender_legende, null)) .setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.show(); } private class KalenderTextView extends TextView { public KalenderTextView(Context context, String text) { super(context); this.setText(text); this.setPadding(5, 3, 5, 3); this.setTextSize(13); } public KalenderTextView(Context context, Spanned text) { super(context); this.setText(text); this.setPadding(5, 3, 5, 3); this.setTextSize(13); } } private class LijnRechts extends View { TableRow.LayoutParams lijnRechts = new TableRow.LayoutParams(1, TableRow.LayoutParams.MATCH_PARENT); int grijs = getResources().getColor(R.color.grijs); public LijnRechts(Context context) { super(context); this.setLayoutParams(lijnRechts); this.setBackgroundColor(grijs); } } private class LijnOnder extends View { TableRow.LayoutParams lijnOnder = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 1); int grijs = getResources().getColor(R.color.grijs); public LijnOnder(Context context) { super(context); this.setLayoutParams(lijnOnder); this.setBackgroundColor(grijs); } } }
Saticmotion/PXLApp
src/com/mobsoft/pxlapp/activities/kalender/KalenderActivity.java
2,523
//Alpha-kanaal is nul, dus is volledig doorzichtig.
line_comment
nl
package com.mobsoft.pxlapp.activities.kalender; import java.io.IOException; import java.util.ArrayList; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.graphics.Typeface; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.text.Html; import android.text.Spanned; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; import com.mobsoft.pxlapp.R; public class KalenderActivity extends Activity { private Spinner spinner; private Kalender kalenderVolledig; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_kalender); // Show the Up button in the action bar. setupActionBar(); toonKalender(); } /** * Set up the {@link android.app.ActionBar}, if the API is available. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) private void setupActionBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.kalender, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public void toonKalender() { spinner = (Spinner) findViewById(R.id.soortSpinner); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { String waarde = spinner.getSelectedItem().toString(); updateKalender(waarde); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); try { this.kalenderVolledig = Kalender.kalenderVanBestand(this); tekenKalender(kalenderVolledig); } catch (IOException e) { e.printStackTrace(); } } private void updateKalender(String waarde) { Kalender kalender = kalenderVolledig.filterKalender(waarde); tekenKalender(kalender); } private void tekenKalender(Kalender kalender) { LijnRechts lijnRechts; LijnOnder lijnOnder; TableLayout tabel = (TableLayout) findViewById(R.id.KalenderTable); tabel.removeAllViews(); ArrayList<String> titels = kalender.getTitels(); TableRow tableRow = new TableRow(this); for (int i = 0; i < titels.size(); i++) { KalenderTextView txtTitel = new KalenderTextView(this, titels.get(i)); txtTitel.setTypeface(Typeface.DEFAULT_BOLD); tableRow.addView(txtTitel); if (i < titels.size() - 1) { lijnRechts = new LijnRechts(this); tableRow.addView(lijnRechts); } } tabel.addView(tableRow); lijnOnder = new LijnOnder(this); tabel.addView(lijnOnder); for (int i = 0; i < kalender.getRijen().size(); i++) { KalenderRij rij = kalender.getRij(i); TableRow tr = new TableRow(this); tr.setBackgroundColor(getCelColor(rij.getType())); KalenderTextView txtCel = new KalenderTextView(this, rij.getDatum().toString("dd/MM/yy")); tr.addView(txtCel); lijnRechts = new LijnRechts(this); tr.addView(lijnRechts); for (int j = 0; j < rij.getCellen().size(); j++) { KalenderCel cel = rij.getCel(j); if (cel.getTekst().contains("<br />")) { txtCel = new KalenderTextView(this, Html.fromHtml(cel.getTekst())); } else { txtCel = new KalenderTextView(this, cel.getTekst()); } txtCel.setBackgroundColor(getCelColor(cel.getType())); tr.addView(txtCel); if (j < kalender.getRij(i).getCellen().size() - 1) { lijnRechts = new LijnRechts(this); tr.addView(lijnRechts); } } tabel.addView(tr); lijnOnder = new LijnOnder(this); tabel.addView(lijnOnder); } } private int getCelColor(KalenderType type) { if (type == KalenderType.EXAMEN) { return getResources().getColor(R.color.roze2); } else if (type == KalenderType.VRIJ) { return getResources().getColor(R.color.groen2); } else if (type == KalenderType.DELIBERATIE) { return getResources().getColor(R.color.paars2); } else if (type == KalenderType.VAKANTIE) { return getResources().getColor(R.color.oranje2); } else { return 0x00000000; //Alpha-kanaal is<SUF> } } public void toonLegende(View view) { AlertDialog.Builder dialog = new AlertDialog.Builder(this); LayoutInflater inflater = getLayoutInflater(); // Inflate and set the layout for the dialog // Pass null as the parent view because its going in the dialog layout dialog.setView(inflater.inflate(R.layout.kalender_legende, null)) .setPositiveButton("OK", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog.show(); } private class KalenderTextView extends TextView { public KalenderTextView(Context context, String text) { super(context); this.setText(text); this.setPadding(5, 3, 5, 3); this.setTextSize(13); } public KalenderTextView(Context context, Spanned text) { super(context); this.setText(text); this.setPadding(5, 3, 5, 3); this.setTextSize(13); } } private class LijnRechts extends View { TableRow.LayoutParams lijnRechts = new TableRow.LayoutParams(1, TableRow.LayoutParams.MATCH_PARENT); int grijs = getResources().getColor(R.color.grijs); public LijnRechts(Context context) { super(context); this.setLayoutParams(lijnRechts); this.setBackgroundColor(grijs); } } private class LijnOnder extends View { TableRow.LayoutParams lijnOnder = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 1); int grijs = getResources().getColor(R.color.grijs); public LijnOnder(Context context) { super(context); this.setLayoutParams(lijnOnder); this.setBackgroundColor(grijs); } } }
True
1,827
18
2,280
21
2,133
15
2,280
21
2,759
20
false
false
false
false
false
true
560
4905_7
/* * This file is subject to the license.txt file in the main folder * of this project. */ package stanhebben.zenscript.parser; import java.util.Arrays; /** * HashSet implementation which is optimized for integer values. * * @author Stan Hebben */ public class HashSetI { private int[] values; private int[] next; private int mask; private int size; /** * Creates a new HashSet for integer values. */ public HashSetI() { values = new int[16]; next = new int[16]; mask = 15; size = 0; for (int i = 0; i < values.length; i++) { values[i] = Integer.MIN_VALUE; } } public HashSetI(HashSetI original) { values = Arrays.copyOf(original.values, original.values.length); next = Arrays.copyOf(original.next, original.next.length); mask = original.mask; size = original.size; } /** * Adds the specified value to this HashSet. If this value is already in * this HashSet, nothing happens. * * @param value value to be added to the HashSet */ public void add(int value) { if (size > (values.length * 3) >> 2) { expand(); } int index = value & mask; if (values[index] == Integer.MIN_VALUE) { values[index] = value; } else { if (values[index] == value) { return; } while (next[index] != 0) { index = next[index] - 1; if (values[index] == value) { return; } } int ref = index; while (values[index] != Integer.MIN_VALUE) { index++; if (index == values.length) index = 0; } next[ref] = index + 1; values[index] = value; } size++; } /** * Checks if this HashSet contains the specified value. * * @param value integer value to add * @return true if this HashSet contains the specified value */ public boolean contains(int value) { int index = value & mask; while (values[index] != value) { if (next[index] == 0) { return false; } index = next[index] - 1; } return true; } /** * Returns an iterator over this HashSet. The elements are returned in no * particular order. * * @return an iterator over this HashSet */ public IteratorI iterator() { return new KeyIterator(); } /** * Converts the contents of this HashSet to an integer array. The order of * the elements is unspecified. * * @return this HashSet as integer array */ public int[] toArray() { int[] result = new int[size]; int ix = 0; for (int i = 0; i < values.length; i++) { if (values[i] != Integer.MIN_VALUE) { result[ix++] = values[i]; } } return result; } // //////////////////////// // Private inner methods // //////////////////////// /** * Expands the capacity of this HashSet. (double it) */ private void expand() { int[] newKeys = new int[values.length * 2]; int[] newNext = new int[next.length * 2]; int newMask = newKeys.length - 1; for (int i = 0; i < newKeys.length; i++) { newKeys[i] = Integer.MIN_VALUE; } for (int i = 0; i < values.length; i++) { if (values[i] == Integer.MIN_VALUE) { continue; } int key = values[i]; int index = key & newMask; if (newKeys[index] == Integer.MIN_VALUE) { newKeys[index] = key; } else { while (newNext[index] != 0) { index = newNext[index] - 1; } int ref = index; while (newKeys[index] != Integer.MIN_VALUE) { index = (index + 1) & newMask; } newNext[ref] = index + 1; newKeys[index] = key; } } values = newKeys; next = newNext; mask = newMask; } // //////////////////////// // Private inner classes // //////////////////////// private class KeyIterator implements IteratorI { private int i; public KeyIterator() { i = 0; skip(); } @Override public boolean hasNext() { return i < values.length; } @Override public int next() { int result = values[i++]; skip(); return result; } private void skip() { while (i < values.length && values[i] == Integer.MIN_VALUE) i++; } } }
GTNewHorizons/NewHorizonsTweaker
ZenScript/src/main/java/stanhebben/zenscript/parser/HashSetI.java
1,399
// Private inner methods
line_comment
nl
/* * This file is subject to the license.txt file in the main folder * of this project. */ package stanhebben.zenscript.parser; import java.util.Arrays; /** * HashSet implementation which is optimized for integer values. * * @author Stan Hebben */ public class HashSetI { private int[] values; private int[] next; private int mask; private int size; /** * Creates a new HashSet for integer values. */ public HashSetI() { values = new int[16]; next = new int[16]; mask = 15; size = 0; for (int i = 0; i < values.length; i++) { values[i] = Integer.MIN_VALUE; } } public HashSetI(HashSetI original) { values = Arrays.copyOf(original.values, original.values.length); next = Arrays.copyOf(original.next, original.next.length); mask = original.mask; size = original.size; } /** * Adds the specified value to this HashSet. If this value is already in * this HashSet, nothing happens. * * @param value value to be added to the HashSet */ public void add(int value) { if (size > (values.length * 3) >> 2) { expand(); } int index = value & mask; if (values[index] == Integer.MIN_VALUE) { values[index] = value; } else { if (values[index] == value) { return; } while (next[index] != 0) { index = next[index] - 1; if (values[index] == value) { return; } } int ref = index; while (values[index] != Integer.MIN_VALUE) { index++; if (index == values.length) index = 0; } next[ref] = index + 1; values[index] = value; } size++; } /** * Checks if this HashSet contains the specified value. * * @param value integer value to add * @return true if this HashSet contains the specified value */ public boolean contains(int value) { int index = value & mask; while (values[index] != value) { if (next[index] == 0) { return false; } index = next[index] - 1; } return true; } /** * Returns an iterator over this HashSet. The elements are returned in no * particular order. * * @return an iterator over this HashSet */ public IteratorI iterator() { return new KeyIterator(); } /** * Converts the contents of this HashSet to an integer array. The order of * the elements is unspecified. * * @return this HashSet as integer array */ public int[] toArray() { int[] result = new int[size]; int ix = 0; for (int i = 0; i < values.length; i++) { if (values[i] != Integer.MIN_VALUE) { result[ix++] = values[i]; } } return result; } // //////////////////////// // Private inner<SUF> // //////////////////////// /** * Expands the capacity of this HashSet. (double it) */ private void expand() { int[] newKeys = new int[values.length * 2]; int[] newNext = new int[next.length * 2]; int newMask = newKeys.length - 1; for (int i = 0; i < newKeys.length; i++) { newKeys[i] = Integer.MIN_VALUE; } for (int i = 0; i < values.length; i++) { if (values[i] == Integer.MIN_VALUE) { continue; } int key = values[i]; int index = key & newMask; if (newKeys[index] == Integer.MIN_VALUE) { newKeys[index] = key; } else { while (newNext[index] != 0) { index = newNext[index] - 1; } int ref = index; while (newKeys[index] != Integer.MIN_VALUE) { index = (index + 1) & newMask; } newNext[ref] = index + 1; newKeys[index] = key; } } values = newKeys; next = newNext; mask = newMask; } // //////////////////////// // Private inner classes // //////////////////////// private class KeyIterator implements IteratorI { private int i; public KeyIterator() { i = 0; skip(); } @Override public boolean hasNext() { return i < values.length; } @Override public int next() { int result = values[i++]; skip(); return result; } private void skip() { while (i < values.length && values[i] == Integer.MIN_VALUE) i++; } } }
False
1,120
4
1,320
4
1,338
4
1,320
4
1,587
4
false
false
false
false
false
true
2,268
195491_7
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package parser; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = false; int bufsize; int available; int tokenBegin; /** Position in buffer. */ public int bufpos = -1; protected int bufline[]; protected int bufcolumn[]; protected int column = 0; protected int line = 1; protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; protected java.io.Reader inputStream; protected char[] buffer; protected int maxNextCharInd = 0; protected int inBuf = 0; protected int tabSize = 8; protected void setTabSize(int i) { tabSize = i; } protected int getTabSize(int i) { return tabSize; } protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ public int getEndLine() { return bufline[bufpos]; } /** Get token beginning column number. */ public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=3f792f16bacbb748005fefbb08a365ec (do not edit this line) */
blakeelias/graphics
ml6-d-svn/trunk/final/Jackie_and_Aleksandr/parser/SimpleCharStream.java
3,819
/** Get token end column number. */
block_comment
nl
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package parser; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = false; int bufsize; int available; int tokenBegin; /** Position in buffer. */ public int bufpos = -1; protected int bufline[]; protected int bufcolumn[]; protected int column = 0; protected int line = 1; protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; protected java.io.Reader inputStream; protected char[] buffer; protected int maxNextCharInd = 0; protected int inBuf = 0; protected int tabSize = 8; protected void setTabSize(int i) { tabSize = i; } protected int getTabSize(int i) { return tabSize; } protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ public int getLine() { return bufline[bufpos]; } /** Get token end<SUF>*/ public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ public int getEndLine() { return bufline[bufpos]; } /** Get token beginning column number. */ public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=3f792f16bacbb748005fefbb08a365ec (do not edit this line) */
False
3,076
8
3,269
8
3,643
8
3,269
8
3,868
8
false
false
false
false
false
true
1,126
114409_0
package nl.overheid.koop.plooi.plooiiamservice.web; import com.nimbusds.jose.JOSEException; import lombok.RequiredArgsConstructor; import lombok.val; import nl.overheid.koop.plooi.plooiiamservice.domain.TokenService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.text.ParseException; @RestController @RequiredArgsConstructor public class TokenIntrospectionEndpoint { private final TokenService tokenService; @GetMapping("/check_token") public ResponseEntity<Void> checkToken(final HttpServletRequest request) { val token = request.getHeader("x-access-token"); if (token == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } try { if (!tokenService.validateToken(token)) return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } catch (ParseException | JOSEException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } return ResponseEntity.ok().build(); } // Tijdelijk niet beschikbaar. Wordt opgepakt wanneer DPC via CA gaat aansluiten. // @GetMapping("/check_ca_token") // public ResponseEntity<Void> checkCaToken() { // return ResponseEntity.ok().build(); // } }
MinBZK/woo-besluit-broncode-PLOOI
aanleveren/security/plooi-iam-service/src/main/java/nl/overheid/koop/plooi/plooiiamservice/web/TokenIntrospectionEndpoint.java
418
// Tijdelijk niet beschikbaar. Wordt opgepakt wanneer DPC via CA gaat aansluiten.
line_comment
nl
package nl.overheid.koop.plooi.plooiiamservice.web; import com.nimbusds.jose.JOSEException; import lombok.RequiredArgsConstructor; import lombok.val; import nl.overheid.koop.plooi.plooiiamservice.domain.TokenService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import java.text.ParseException; @RestController @RequiredArgsConstructor public class TokenIntrospectionEndpoint { private final TokenService tokenService; @GetMapping("/check_token") public ResponseEntity<Void> checkToken(final HttpServletRequest request) { val token = request.getHeader("x-access-token"); if (token == null) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } try { if (!tokenService.validateToken(token)) return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } catch (ParseException | JOSEException e) { return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); } return ResponseEntity.ok().build(); } // Tijdelijk niet<SUF> // @GetMapping("/check_ca_token") // public ResponseEntity<Void> checkCaToken() { // return ResponseEntity.ok().build(); // } }
True
281
29
370
33
360
21
370
33
438
31
false
false
false
false
false
true
1,273
201424_9
package decaf.dataflow; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.HashSet; import decaf.machdesc.Asm; import decaf.machdesc.Register; import decaf.tac.Label; import decaf.tac.Tac; import decaf.tac.Temp; public class BasicBlock { public int bbNum; public enum EndKind { BY_BRANCH, BY_BEQZ, BY_BNEZ, BY_RETURN } public EndKind endKind; public int inDegree; public Tac tacList; public Label label; public Temp var; public Register varReg; public int[] next; public boolean cancelled; public boolean mark; public Set<Temp> def; public Set<Temp> liveUse; public Set<Temp> liveIn; public Set<Temp> liveOut; public Set<Temp> saves; private List<Asm> asms; public BasicBlock() { def = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveUse = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveIn = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveOut = new TreeSet<Temp>(Temp.ID_COMPARATOR); next = new int[2]; asms = new ArrayList<Asm>(); } public void computeDefAndLiveUse() { for (Tac tac = tacList; tac != null; tac = tac.next) { switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op2.lastVisitedBB != bbNum) { liveUse.add (tac.op2); tac.op2.lastVisitedBB = bbNum; } if (tac.op0.lastVisitedBB != bbNum) { def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in INDIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in DIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case STORE: /* use op0 and op1*/ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } break; case PARM: /* use op0 */ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; default: /* BRANCH MEMO MARK PARM*/ break; } } if (var != null && var.lastVisitedBB != bbNum) { liveUse.add (var); var.lastVisitedBB = bbNum; } liveIn.addAll (liveUse); } public void analyzeLiveness() { if (tacList == null) return; Tac tac = tacList; for (; tac.next != null; tac = tac.next); tac.liveOut = new HashSet<Temp> (liveOut); if (var != null) tac.liveOut.add (var); for (; tac != tacList; tac = tac.prev) { tac.prev.liveOut = new HashSet<Temp> (tac.liveOut); switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); tac.prev.liveOut.add (tac.op2); break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def op0 */ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ tac.prev.liveOut.remove (tac.op0); break; case STORE: /* use op0 and op1*/ tac.prev.liveOut.add (tac.op0); tac.prev.liveOut.add (tac.op1); break; case BEQZ: case BNEZ: case PARM: /* use op0 */ tac.prev.liveOut.add (tac.op0); break; default: /* BRANCH MEMO MARK PARM*/ break; } } } public void printTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public void printLivenessTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); pw.println(" Def = " + toString(def)); pw.println(" liveUse = " + toString(liveUse)); pw.println(" liveIn = " + toString(liveIn)); pw.println(" liveOut = " + toString(liveOut)); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t + " " + toString(t.liveOut)); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public String toString(Set<Temp> set) { StringBuilder sb = new StringBuilder("[ "); for (Temp t : set) { sb.append(t.name + " "); } sb.append(']'); return sb.toString(); } public void insertBefore(Tac insert, Tac base) { if (base == tacList) { tacList = insert; } else { base.prev.next = insert; } insert.prev = base.prev; base.prev = insert; insert.next = base; } public void insertAfter(Tac insert, Tac base) { if (tacList == null) { tacList = insert; insert.next = null; return; } if (base.next != null) { base.next.prev = insert; } insert.prev = base; insert.next = base.next; base.next = insert; } public void appendAsm(Asm asm) { asms.add(asm); } public List<Asm> getAsms() { return asms; } }
PKUanonym/REKCARC-TSC-UHT
大三上/编译原理/hw/2016_黄家晖_PA/627604533_5_decaf_PA4/src/decaf/dataflow/BasicBlock.java
2,980
/* use op1, def op0 */
block_comment
nl
package decaf.dataflow; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.HashSet; import decaf.machdesc.Asm; import decaf.machdesc.Register; import decaf.tac.Label; import decaf.tac.Tac; import decaf.tac.Temp; public class BasicBlock { public int bbNum; public enum EndKind { BY_BRANCH, BY_BEQZ, BY_BNEZ, BY_RETURN } public EndKind endKind; public int inDegree; public Tac tacList; public Label label; public Temp var; public Register varReg; public int[] next; public boolean cancelled; public boolean mark; public Set<Temp> def; public Set<Temp> liveUse; public Set<Temp> liveIn; public Set<Temp> liveOut; public Set<Temp> saves; private List<Asm> asms; public BasicBlock() { def = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveUse = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveIn = new TreeSet<Temp>(Temp.ID_COMPARATOR); liveOut = new TreeSet<Temp>(Temp.ID_COMPARATOR); next = new int[2]; asms = new ArrayList<Asm>(); } public void computeDefAndLiveUse() { for (Tac tac = tacList; tac != null; tac = tac.next) { switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op2.lastVisitedBB != bbNum) { liveUse.add (tac.op2); tac.op2.lastVisitedBB = bbNum; } if (tac.op0.lastVisitedBB != bbNum) { def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def op0 */ if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in INDIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ if (tac.op0 != null && tac.op0.lastVisitedBB != bbNum) { // in DIRECT_CALL with return type VOID, // tac.op0 is null def.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; case STORE: /* use op0 and op1*/ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } if (tac.op1.lastVisitedBB != bbNum) { liveUse.add (tac.op1); tac.op1.lastVisitedBB = bbNum; } break; case PARM: /* use op0 */ if (tac.op0.lastVisitedBB != bbNum) { liveUse.add (tac.op0); tac.op0.lastVisitedBB = bbNum; } break; default: /* BRANCH MEMO MARK PARM*/ break; } } if (var != null && var.lastVisitedBB != bbNum) { liveUse.add (var); var.lastVisitedBB = bbNum; } liveIn.addAll (liveUse); } public void analyzeLiveness() { if (tacList == null) return; Tac tac = tacList; for (; tac.next != null; tac = tac.next); tac.liveOut = new HashSet<Temp> (liveOut); if (var != null) tac.liveOut.add (var); for (; tac != tacList; tac = tac.prev) { tac.prev.liveOut = new HashSet<Temp> (tac.liveOut); switch (tac.opc) { case ADD: case SUB: case MUL: case DIV: case MOD: case LAND: case LOR: case GTR: case GEQ: case EQU: case NEQ: case LEQ: case LES: /* use op1 and op2, def op0 */ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); tac.prev.liveOut.add (tac.op2); break; case NEG: case LNOT: case ASSIGN: case INDIRECT_CALL: case LOAD: /* use op1, def<SUF>*/ tac.prev.liveOut.remove (tac.op0); tac.prev.liveOut.add (tac.op1); break; case LOAD_VTBL: case DIRECT_CALL: case RETURN: case LOAD_STR_CONST: case LOAD_IMM4: /* def op0 */ tac.prev.liveOut.remove (tac.op0); break; case STORE: /* use op0 and op1*/ tac.prev.liveOut.add (tac.op0); tac.prev.liveOut.add (tac.op1); break; case BEQZ: case BNEZ: case PARM: /* use op0 */ tac.prev.liveOut.add (tac.op0); break; default: /* BRANCH MEMO MARK PARM*/ break; } } } public void printTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public void printLivenessTo(PrintWriter pw) { pw.println("BASIC BLOCK " + bbNum + " : "); pw.println(" Def = " + toString(def)); pw.println(" liveUse = " + toString(liveUse)); pw.println(" liveIn = " + toString(liveIn)); pw.println(" liveOut = " + toString(liveOut)); for (Tac t = tacList; t != null; t = t.next) { pw.println(" " + t + " " + toString(t.liveOut)); } switch (endKind) { case BY_BRANCH: pw.println("END BY BRANCH, goto " + next[0]); break; case BY_BEQZ: pw.println("END BY BEQZ, if " + var.name + " = "); pw.println(" 0 : goto " + next[0] + "; 1 : goto " + next[1]); break; case BY_BNEZ: pw.println("END BY BGTZ, if " + var.name + " = "); pw.println(" 1 : goto " + next[0] + "; 0 : goto " + next[1]); break; case BY_RETURN: if (var != null) { pw.println("END BY RETURN, result = " + var.name); } else { pw.println("END BY RETURN, void result"); } break; } } public String toString(Set<Temp> set) { StringBuilder sb = new StringBuilder("[ "); for (Temp t : set) { sb.append(t.name + " "); } sb.append(']'); return sb.toString(); } public void insertBefore(Tac insert, Tac base) { if (base == tacList) { tacList = insert; } else { base.prev.next = insert; } insert.prev = base.prev; base.prev = insert; insert.next = base; } public void insertAfter(Tac insert, Tac base) { if (tacList == null) { tacList = insert; insert.next = null; return; } if (base.next != null) { base.next.prev = insert; } insert.prev = base; insert.next = base.next; base.next = insert; } public void appendAsm(Asm asm) { asms.add(asm); } public List<Asm> getAsms() { return asms; } }
False
2,247
9
2,692
9
2,618
9
2,712
9
3,415
9
false
false
false
false
false
true
4,651
122429_2
package nl.vpro.amara; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.Iterator; import org.junit.jupiter.api.Test; import nl.vpro.amara.domain.*; /** * @author Michiel Meeuwissen * @since 0.2 */ //@Ignore("This is integration test requiring actual key in ~/conf/amara.properties") @Slf4j public class VideosClientITest extends AbstractClientsTest { public static String example = "{\"video_url\":\"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\"title\":\"De invloed van de SER // Adviezen en regeringsbeleid\",\"description\":\"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet.\",\"primary_audio_language_code\":\"nl\",\"thumbnail\":\"http://images-test.poms.omroep.nl/image/32071124.jpg\",\"metadata\":{\"location\":\"WO_NTR_425175\",\"speaker-name\":\"De invloed van de SER\"},\"team\":\"netinnederland-staging\",\"project\":\"current\"}"; public static String video = "{\n" + " \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" + " \"title\" : \"De invloed van de SER // Adviezen en regeringsbeleid\",\n" + " \"description\" : \"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet. \",\n" + " \"primary_audio_language_code\" : \"nl\",\n" + //" \"thumbnail\" : \"http://images-test.poms.omroep.nl/image/32071124.jpg\",\n" + " \"metadata\" : {\n" + " \"location\" : \"WO_NTR_425175\",\n" + " \"speaker-name\" : \"De invloed van de SER\"\n" + " },\n" + " \"team\" : \"netinnederland\",\n" + " \"project\" : \"current\"\n" + "}"; public static String anothervideo = "{\n" + " \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/nep/WO_NTR_15925207.mp4?a\",\n" + //" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" + " \"title\" : \"Fragment NOS: Op vakantie naar Syrie\",\n" + " \"description\" : \"Op vakantie naar Syrie\",\n" + " \"primary_audio_language_code\" : \"nl\",\n" + //" \"thumbnail\" : \"http://images.poms.omroep.nl/image/s620/1329508.jpg\",\n" + " \"metadata\" : {\n" + " \"location\" : \"WO_NTR_15925207\",\n" + " \"speaker-name\" : \"Fragment NOS: Op vakantie naar Syrie\"\n" + " },\n" + " \"team\" : \"netinnederland\",\n" + " \"project\" : \"current\"\n" + "}"; @Test public void postSubtitles() throws IOException { Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example); in.setAction("save-draft"); System.out.println(client.videos().post(in, "6dNTmqJsQf1x", "nl")); } /* @Test public void postSubtitles2() throws IOException { Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example); in.setAction("save-draft"); System.out.println(client.videos().post(constructVideo(), "6dNTmqJsQf1x", "nl")); } */ protected Video constructVideo() { String pomsMidBroadcast = "POW_03372509"; String videoTitel = "test"; String speakerName = ""; String thumbnailUrl = "http://images-test.poms.omroep.nl/image/32071124.jpg"; VideoMetadata amaraVideoMetadata = new VideoMetadata(speakerName, pomsMidBroadcast); Video amaraVideo = new Video("http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4", "nl", videoTitel, "descriptoin", client.getTeam(), amaraVideoMetadata); amaraVideo.setThumbnail(thumbnailUrl); amaraVideo.setProject("current"); return amaraVideo; } @Test // GIVES 504. I don't know why. public void postVideo() throws IOException { Video in = AmaraObjectMapper.INSTANCE.readerFor(Video.class).readValue(anothervideo); // System.out.println(anothervideo); System.out.println(client.videos().post(in)); } @Test public void getSubtitles() { Subtitles subtitles = client.videos().getSubtitles("BNkV7s6mKMNb", "ar", "vtt"); log.info("" + subtitles); } @Test public void getVideo() { Video video = client.videos().get("BNkV7s6mKMNb"); log.info("" + video); } @Test public void list() { Iterator<Video> video = client.videos().list(); video.forEachRemaining((v) -> { log.info("" + v); }); } }
vpro/amara-java
src/test/java/nl/vpro/amara/VideosClientITest.java
1,680
//download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\"title\":\"De invloed van de SER // Adviezen en regeringsbeleid\",\"description\":\"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet.\",\"primary_audio_language_code\":\"nl\",\"thumbnail\":\"http://images-test.poms.omroep.nl/image/32071124.jpg\",\"metadata\":{\"location\":\"WO_NTR_425175\",\"speaker-name\":\"De invloed van de SER\"},\"team\":\"netinnederland-staging\",\"project\":\"current\"}";
line_comment
nl
package nl.vpro.amara; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.Iterator; import org.junit.jupiter.api.Test; import nl.vpro.amara.domain.*; /** * @author Michiel Meeuwissen * @since 0.2 */ //@Ignore("This is integration test requiring actual key in ~/conf/amara.properties") @Slf4j public class VideosClientITest extends AbstractClientsTest { public static String example = "{\"video_url\":\"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\"title\":\"De invloed<SUF> public static String video = "{\n" + " \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" + " \"title\" : \"De invloed van de SER // Adviezen en regeringsbeleid\",\n" + " \"description\" : \"De Sociaal Economische Raad (SER) adviseert de regering over belangrijke dingen, zoals de WAO en de ziektekostenwet. \",\n" + " \"primary_audio_language_code\" : \"nl\",\n" + //" \"thumbnail\" : \"http://images-test.poms.omroep.nl/image/32071124.jpg\",\n" + " \"metadata\" : {\n" + " \"location\" : \"WO_NTR_425175\",\n" + " \"speaker-name\" : \"De invloed van de SER\"\n" + " },\n" + " \"team\" : \"netinnederland\",\n" + " \"project\" : \"current\"\n" + "}"; public static String anothervideo = "{\n" + " \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/nep/WO_NTR_15925207.mp4?a\",\n" + //" \"video_url\" : \"http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4\",\n" + " \"title\" : \"Fragment NOS: Op vakantie naar Syrie\",\n" + " \"description\" : \"Op vakantie naar Syrie\",\n" + " \"primary_audio_language_code\" : \"nl\",\n" + //" \"thumbnail\" : \"http://images.poms.omroep.nl/image/s620/1329508.jpg\",\n" + " \"metadata\" : {\n" + " \"location\" : \"WO_NTR_15925207\",\n" + " \"speaker-name\" : \"Fragment NOS: Op vakantie naar Syrie\"\n" + " },\n" + " \"team\" : \"netinnederland\",\n" + " \"project\" : \"current\"\n" + "}"; @Test public void postSubtitles() throws IOException { Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example); in.setAction("save-draft"); System.out.println(client.videos().post(in, "6dNTmqJsQf1x", "nl")); } /* @Test public void postSubtitles2() throws IOException { Subtitles in = AmaraObjectMapper.INSTANCE.readerFor(Subtitles.class).readValue(example); in.setAction("save-draft"); System.out.println(client.videos().post(constructVideo(), "6dNTmqJsQf1x", "nl")); } */ protected Video constructVideo() { String pomsMidBroadcast = "POW_03372509"; String videoTitel = "test"; String speakerName = ""; String thumbnailUrl = "http://images-test.poms.omroep.nl/image/32071124.jpg"; VideoMetadata amaraVideoMetadata = new VideoMetadata(speakerName, pomsMidBroadcast); Video amaraVideo = new Video("http://download.omroep.nl/vpro/netinnederland/hasp/WO_NTR_425175.mp4", "nl", videoTitel, "descriptoin", client.getTeam(), amaraVideoMetadata); amaraVideo.setThumbnail(thumbnailUrl); amaraVideo.setProject("current"); return amaraVideo; } @Test // GIVES 504. I don't know why. public void postVideo() throws IOException { Video in = AmaraObjectMapper.INSTANCE.readerFor(Video.class).readValue(anothervideo); // System.out.println(anothervideo); System.out.println(client.videos().post(in)); } @Test public void getSubtitles() { Subtitles subtitles = client.videos().getSubtitles("BNkV7s6mKMNb", "ar", "vtt"); log.info("" + subtitles); } @Test public void getVideo() { Video video = client.videos().get("BNkV7s6mKMNb"); log.info("" + video); } @Test public void list() { Iterator<Video> video = client.videos().list(); video.forEachRemaining((v) -> { log.info("" + v); }); } }
False
1,367
162
1,540
188
1,516
165
1,538
187
1,735
203
false
false
false
false
false
true
3,111
11142_2
package interdroid.swan.engine; import interdroid.swan.R; import java.text.Format; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.content.LocalBroadcastManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class SensorViewerActivity extends ListActivity { private List<Bundle> mSensors = new ArrayList<Bundle>(); private SensorAdapter mAdapter = new SensorAdapter(); private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // get the data stuff it in the base adapter Parcelable[] sensors = intent.getParcelableArrayExtra("sensors"); mSensors.clear(); for (Parcelable sensor : sensors) { mSensors.add((Bundle) sensor); } mAdapter.notifyDataSetChanged(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(mAdapter); } @Override protected void onResume() { runOnUiThread(new Runnable() { public void run() { Toast.makeText(SensorViewerActivity.this, "updating with service", Toast.LENGTH_SHORT).show(); } }); LocalBroadcastManager.getInstance(this).registerReceiver( mUpdateReceiver, new IntentFilter(EvaluationEngineService.UPDATE_SENSORS)); // let the service know that we want to get updates... startService(new Intent(EvaluationEngineService.UPDATE_SENSORS) .setClass(this, EvaluationEngineService.class)); super.onResume(); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver( mUpdateReceiver); super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.sensorviewer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: startService(new Intent(EvaluationEngineService.UPDATE_SENSORS) .setClass(this, EvaluationEngineService.class)); break; case R.id.expression_viewer: this.finish(); break; default: break; } return super.onOptionsItemSelected(item); } class SensorAdapter extends BaseAdapter { @Override public int getCount() { return mSensors.size(); } @Override public Object getItem(int position) { return mSensors.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // check als je hier komt of niet, met system.out.println if (convertView == null) { convertView = LayoutInflater.from(SensorViewerActivity.this) .inflate(R.layout.sensor_viewer, null); } //Sensor name ((TextView) ((LinearLayout) convertView) .findViewById(R.id.sensorName)).setText(mSensors.get( position).getString("name")); //Number of Registered ID using this sensor ((TextView) ((LinearLayout) convertView) .findViewById(R.id.registeredIds)).setText(" (" + mSensors.get(position).getInt("registeredids") + ")"); //Start time of sensor Date date = new Date(mSensors.get(position).getLong("starttime")); Format format = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy"); ((TextView) ((LinearLayout) convertView) .findViewById(R.id.startTime)).setText("" + format.format(date).toString()); //Sensing rate ((TextView) ((LinearLayout) convertView) .findViewById(R.id.sensingRate)).setText(String.format( "%.2f", mSensors.get(position).getDouble("sensingRate")) + " Hz"); //current milli ampere ((TextView) ((LinearLayout) convertView) .findViewById(R.id.currentMilliAmpere)).setText(mSensors.get(position).getFloat("currentMilliAmpere") + " mA"); //current Watt ((TextView) ((LinearLayout) convertView) .findViewById(R.id.currentWatt)).setText((4 * mSensors.get(position).getFloat("currentMilliAmpere")) + " mW"); //percentage per hour mA int batteryMah = 1780; ((TextView) ((LinearLayout) convertView) .findViewById(R.id.percentageHour)).setText(String.format("%.3f", 100 / (batteryMah / mSensors.get(position).getFloat("currentMilliAmpere"))) + " %/hr"); return convertView; } } }
interdroid/interdroid-swan
src/interdroid/swan/engine/SensorViewerActivity.java
1,593
// check als je hier komt of niet, met system.out.println
line_comment
nl
package interdroid.swan.engine; import interdroid.swan.R; import java.text.Format; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Parcelable; import android.support.v4.content.LocalBroadcastManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class SensorViewerActivity extends ListActivity { private List<Bundle> mSensors = new ArrayList<Bundle>(); private SensorAdapter mAdapter = new SensorAdapter(); private BroadcastReceiver mUpdateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // get the data stuff it in the base adapter Parcelable[] sensors = intent.getParcelableArrayExtra("sensors"); mSensors.clear(); for (Parcelable sensor : sensors) { mSensors.add((Bundle) sensor); } mAdapter.notifyDataSetChanged(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setListAdapter(mAdapter); } @Override protected void onResume() { runOnUiThread(new Runnable() { public void run() { Toast.makeText(SensorViewerActivity.this, "updating with service", Toast.LENGTH_SHORT).show(); } }); LocalBroadcastManager.getInstance(this).registerReceiver( mUpdateReceiver, new IntentFilter(EvaluationEngineService.UPDATE_SENSORS)); // let the service know that we want to get updates... startService(new Intent(EvaluationEngineService.UPDATE_SENSORS) .setClass(this, EvaluationEngineService.class)); super.onResume(); } @Override protected void onPause() { LocalBroadcastManager.getInstance(this).unregisterReceiver( mUpdateReceiver); super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.sensorviewer, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_refresh: startService(new Intent(EvaluationEngineService.UPDATE_SENSORS) .setClass(this, EvaluationEngineService.class)); break; case R.id.expression_viewer: this.finish(); break; default: break; } return super.onOptionsItemSelected(item); } class SensorAdapter extends BaseAdapter { @Override public int getCount() { return mSensors.size(); } @Override public Object getItem(int position) { return mSensors.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // check als<SUF> if (convertView == null) { convertView = LayoutInflater.from(SensorViewerActivity.this) .inflate(R.layout.sensor_viewer, null); } //Sensor name ((TextView) ((LinearLayout) convertView) .findViewById(R.id.sensorName)).setText(mSensors.get( position).getString("name")); //Number of Registered ID using this sensor ((TextView) ((LinearLayout) convertView) .findViewById(R.id.registeredIds)).setText(" (" + mSensors.get(position).getInt("registeredids") + ")"); //Start time of sensor Date date = new Date(mSensors.get(position).getLong("starttime")); Format format = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy"); ((TextView) ((LinearLayout) convertView) .findViewById(R.id.startTime)).setText("" + format.format(date).toString()); //Sensing rate ((TextView) ((LinearLayout) convertView) .findViewById(R.id.sensingRate)).setText(String.format( "%.2f", mSensors.get(position).getDouble("sensingRate")) + " Hz"); //current milli ampere ((TextView) ((LinearLayout) convertView) .findViewById(R.id.currentMilliAmpere)).setText(mSensors.get(position).getFloat("currentMilliAmpere") + " mA"); //current Watt ((TextView) ((LinearLayout) convertView) .findViewById(R.id.currentWatt)).setText((4 * mSensors.get(position).getFloat("currentMilliAmpere")) + " mW"); //percentage per hour mA int batteryMah = 1780; ((TextView) ((LinearLayout) convertView) .findViewById(R.id.percentageHour)).setText(String.format("%.3f", 100 / (batteryMah / mSensors.get(position).getFloat("currentMilliAmpere"))) + " %/hr"); return convertView; } } }
True
1,091
13
1,349
16
1,317
15
1,349
16
1,721
15
false
false
false
false
false
true
901
57428_0
public class Antwoord { private String antwoord; private Vraag huidigeVraag; public Antwoord(Vraag huidigeVraag, String antwoord) { this.huidigeVraag = huidigeVraag; this.antwoord = antwoord; } public String getAntwoord() { return antwoord; } // public Vraag controleerAntwoord() { // if (huidigeVraag.getAntwoord().equals(antwoord)) { // return huidigeVraag; // } // return null; // } }
Kafune/ooad-finch-app
src/Antwoord.java
156
// public Vraag controleerAntwoord() {
line_comment
nl
public class Antwoord { private String antwoord; private Vraag huidigeVraag; public Antwoord(Vraag huidigeVraag, String antwoord) { this.huidigeVraag = huidigeVraag; this.antwoord = antwoord; } public String getAntwoord() { return antwoord; } // public Vraag<SUF> // if (huidigeVraag.getAntwoord().equals(antwoord)) { // return huidigeVraag; // } // return null; // } }
True
137
12
162
13
127
10
162
13
164
13
false
false
false
false
false
true
1,140
202329_0
package nl.Groep13.OrderHandler.model.v2; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.*; @Entity @Getter @Setter @ToString @Table(name = "article_order") public class ArticleOrder { //Eigenaar van het materiaal, oftewel de klant //Ordernummer //Aantal meter restant //Stofnaam, -kleur en -samenstelling @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "articleID", referencedColumnName = "id") private ArticleV2 articleID; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "customerID", referencedColumnName = "id") private CustomerV2 customerID; private boolean finished; public ArticleOrder(Long id, ArticleV2 articleID, CustomerV2 customerID, boolean finished) { this.id = id; this.articleID = articleID; this.customerID = customerID; this.finished = finished; } public ArticleOrder() { } }
Moemen02/IPSEN2-BE
src/main/java/nl/Groep13/OrderHandler/model/v2/ArticleOrder.java
332
//Eigenaar van het materiaal, oftewel de klant
line_comment
nl
package nl.Groep13.OrderHandler.model.v2; import lombok.Getter; import lombok.Setter; import lombok.ToString; import javax.persistence.*; @Entity @Getter @Setter @ToString @Table(name = "article_order") public class ArticleOrder { //Eigenaar van<SUF> //Ordernummer //Aantal meter restant //Stofnaam, -kleur en -samenstelling @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "articleID", referencedColumnName = "id") private ArticleV2 articleID; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "customerID", referencedColumnName = "id") private CustomerV2 customerID; private boolean finished; public ArticleOrder(Long id, ArticleV2 articleID, CustomerV2 customerID, boolean finished) { this.id = id; this.articleID = articleID; this.customerID = customerID; this.finished = finished; } public ArticleOrder() { } }
True
245
14
281
16
286
11
281
16
334
16
false
false
false
false
false
true
1,424
94460_2
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van CollisionEngine private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); // addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
ROCMondriaanTIN/project-greenfoot-game-weikizhou
DemoWorld.java
3,196
// Declareren van CollisionEngine
line_comment
nl
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * * @author R. Springer */ public class DemoWorld extends World { // Declareren van<SUF> private CollisionEngine ce; // Declareren van TileEngine private TileEngine te; /** * Constructor for objects of class MyWorld. * */ public DemoWorld() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(1000, 800, 1, false); this.setBackground("bg.png"); int[][] map = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, -1, -1, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, 7, 8, 9, 5, 5, 5, 5, 5, 5, 5, 5, 7, 8, 8, 8, 8, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 8, 8, 8, 8, -1, -1, -1, -1, -1, 1, 0, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 8, 8, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, 6, 6, 6, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 11, 6, 6, 6, 6, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 6, 8, 8, 9, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 6, 6, 6, 6, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},}; // initialiseren van de TileEngine klasse om de map aan de world toe te voegen te = new TileEngine(this, 60, 60); te.setTileFactory(new DemoTileFactory()); te.setMap(map); // Declarenre en initialiseren van de camera klasse met de TileEngine klasse // zodat de camera weet welke tiles allemaal moeten meebewegen met de camera Camera camera = new Camera(te); // Initialiseren van de CollisionEngine zodat de speler niet door de tile heen kan lopen. // De collision engine kijkt alleen naar de tiles die de variabele solid op true hebben staan. ce = new CollisionEngine(te, camera); // Declareren en initialiseren van een main karakter van het spel mijne heet Hero. Deze klasse // moet de klasse Mover extenden voor de camera om te werken DemoHero hero = new DemoHero(ce, te); // Alle objecten toevoegen aan de wereld: camera, main karakter en mogelijke enemies addObject(camera, 0, 0); addObject(hero, 300, 200); // addObject(new Enemy(), 1170, 410); // Toevoegen van de mover instantie of een extentie hiervan ce.addCollidingMover(hero); // Laat de camera een object volgen. Die moet een Mover instatie zijn of een extentie hiervan. camera.follow(hero); // Force act zodat de camera op de juist plek staat. camera.act(); hero.act(); } @Override public void act() { ce.update(); } }
True
3,420
7
3,460
7
3,456
6
3,460
7
3,543
8
false
false
false
false
false
true
3,979
46818_8
import java.util.concurrent.Semaphore; import java.util.logging.Level; import java.util.logging.Logger; public class Main implements Runnable { private final static Logger LOGGER = Logger.getLogger(Main.class.getName()); private final static Semaphore bridge = new Semaphore(1); private static String farmerNorthLocation = "north"; private static String farmerSouthLocation = "south"; private String farmer; private Main(String farmer) { this.farmer = farmer; } public static void main(String[] args) { Thread farmerNorth = new Thread(new Main("n")); Thread farmerSouth = new Thread(new Main("s")); farmerNorth.start(); // farmerNorth gaat naar de bridge toe farmerSouth.start(); // farmerSouth gaat naar de bridge toe // Thread[] threads = new Thread[100]; // for (int i = 0; i < threads.length ; i++) { // threads[i] = new Thread(new Main(i % 2 == 0 ? "n" : "s")); // threads[i].start(); // } } @Override public void run() { LOGGER.log(Level.WARNING, "Iemand is bij de bridge aangekomen. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); try { Main.bridge.acquire(); // vraag de bridge op if ("n".equals(this.farmer)) { // verander de locatie van farmer == "n" Main.farmerNorthLocation = Main.farmerNorthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerNorthLocation); } if ("s".equals(this.farmer)) { // verander de locatie van farmer == "s" Main.farmerSouthLocation = Main.farmerSouthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerSouthLocation); } Main.bridge.release(); // geef de bridge af LOGGER.log(Level.WARNING, "Iemand is over de bridge gereden. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); } catch (Exception e) { LOGGER.log(Level.INFO, e.getMessage()); } } }
peterschriever/os-concepts
week-3/src/Main.java
667
// geef de bridge af
line_comment
nl
import java.util.concurrent.Semaphore; import java.util.logging.Level; import java.util.logging.Logger; public class Main implements Runnable { private final static Logger LOGGER = Logger.getLogger(Main.class.getName()); private final static Semaphore bridge = new Semaphore(1); private static String farmerNorthLocation = "north"; private static String farmerSouthLocation = "south"; private String farmer; private Main(String farmer) { this.farmer = farmer; } public static void main(String[] args) { Thread farmerNorth = new Thread(new Main("n")); Thread farmerSouth = new Thread(new Main("s")); farmerNorth.start(); // farmerNorth gaat naar de bridge toe farmerSouth.start(); // farmerSouth gaat naar de bridge toe // Thread[] threads = new Thread[100]; // for (int i = 0; i < threads.length ; i++) { // threads[i] = new Thread(new Main(i % 2 == 0 ? "n" : "s")); // threads[i].start(); // } } @Override public void run() { LOGGER.log(Level.WARNING, "Iemand is bij de bridge aangekomen. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); try { Main.bridge.acquire(); // vraag de bridge op if ("n".equals(this.farmer)) { // verander de locatie van farmer == "n" Main.farmerNorthLocation = Main.farmerNorthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerNorthLocation); } if ("s".equals(this.farmer)) { // verander de locatie van farmer == "s" Main.farmerSouthLocation = Main.farmerSouthLocation.equals("north") ? "south" : "north"; LOGGER.log(Level.INFO, "Boer: "+this.farmer+", is de bridge over en in: "+Main.farmerSouthLocation); } Main.bridge.release(); // geef de<SUF> LOGGER.log(Level.WARNING, "Iemand is over de bridge gereden. Aantal wachtende voor de bridge: "+Main.bridge.getQueueLength()); } catch (Exception e) { LOGGER.log(Level.INFO, e.getMessage()); } } }
True
522
6
598
6
595
5
600
6
685
6
false
false
false
false
false
true
3,630
14649_0
package communitycommons; import java.util.Calendar; import java.util.Date; import communitycommons.proxies.DatePartSelector; public class DateTime { /** * @author mwe * Berekent aantal jaar sinds een bepaalde datum. Als einddatum == null, het huidige tijdstip wordt gebruikt * Code is gebaseerd op http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java */ public static long yearsBetween(Date birthdate, Date comparedate) { if (birthdate == null) return -1L; Calendar now = Calendar.getInstance(); if (comparedate != null) now.setTime(comparedate); Calendar dob = Calendar.getInstance(); dob.setTime(birthdate); if (dob.after(now)) return -1L; int year1 = now.get(Calendar.YEAR); int year2 = dob.get(Calendar.YEAR); long age = year1 - year2; int month1 = now.get(Calendar.MONTH); int month2 = dob.get(Calendar.MONTH); if (month2 > month1) { age--; } else if (month1 == month2) { int day1 = now.get(Calendar.DAY_OF_MONTH); int day2 = dob.get(Calendar.DAY_OF_MONTH); if (day2 > day1) { age--; } } return age; } public static long dateTimeToLong(Date date) { return date.getTime(); } public static Date longToDateTime(Long value) { return new Date(value); } public static long dateTimeToInteger(Date date, DatePartSelector selectorObj) { Calendar newDate = Calendar.getInstance(); newDate.setTime(date); int value = -1; switch (selectorObj) { case year : value = newDate.get(Calendar.YEAR); break; case month : value = newDate.get(Calendar.MONTH)+1; break; // Return starts at 0 case day : value = newDate.get(Calendar.DAY_OF_MONTH); break; default : break; } return value; } }
mendix/RestServices
javasource/communitycommons/DateTime.java
648
/** * @author mwe * Berekent aantal jaar sinds een bepaalde datum. Als einddatum == null, het huidige tijdstip wordt gebruikt * Code is gebaseerd op http://stackoverflow.com/questions/1116123/how-do-i-calculate-someones-age-in-java */
block_comment
nl
package communitycommons; import java.util.Calendar; import java.util.Date; import communitycommons.proxies.DatePartSelector; public class DateTime { /** * @author mwe <SUF>*/ public static long yearsBetween(Date birthdate, Date comparedate) { if (birthdate == null) return -1L; Calendar now = Calendar.getInstance(); if (comparedate != null) now.setTime(comparedate); Calendar dob = Calendar.getInstance(); dob.setTime(birthdate); if (dob.after(now)) return -1L; int year1 = now.get(Calendar.YEAR); int year2 = dob.get(Calendar.YEAR); long age = year1 - year2; int month1 = now.get(Calendar.MONTH); int month2 = dob.get(Calendar.MONTH); if (month2 > month1) { age--; } else if (month1 == month2) { int day1 = now.get(Calendar.DAY_OF_MONTH); int day2 = dob.get(Calendar.DAY_OF_MONTH); if (day2 > day1) { age--; } } return age; } public static long dateTimeToLong(Date date) { return date.getTime(); } public static Date longToDateTime(Long value) { return new Date(value); } public static long dateTimeToInteger(Date date, DatePartSelector selectorObj) { Calendar newDate = Calendar.getInstance(); newDate.setTime(date); int value = -1; switch (selectorObj) { case year : value = newDate.get(Calendar.YEAR); break; case month : value = newDate.get(Calendar.MONTH)+1; break; // Return starts at 0 case day : value = newDate.get(Calendar.DAY_OF_MONTH); break; default : break; } return value; } }
True
466
78
574
84
580
78
574
84
668
89
false
false
false
false
false
true
187
205155_2
package be.pbo.jeugdcup.ranking.domain; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @Data @Builder(toBuilder = true, builderClassName = "EventInternalBuilder", builderMethodName = "internalBuilder") @AllArgsConstructor(access = AccessLevel.PUBLIC) @NoArgsConstructor(access = AccessLevel.PUBLIC) @Slf4j public class Event { private static final AgeCategoryDetector ageCategoryDetector = new AgeCategoryDetector(); private static final ReeksDetector reeksDetector = new ReeksDetector(); private Integer id; private String name; private Gender gender; private EventType eventType; private AgeCategory ageCategory = AgeCategory.DEFAULT_AGE_CATEGORY; private Reeks reeks = Reeks.DEFAULT_REEKS; private List<Round> rounds = new ArrayList<>(); private List<EliminationScheme> eliminationSchemes = new ArrayList<>(); public void init() { ageCategory = ageCategoryDetector.resolveFromEventName(this.name); reeks = reeksDetector.resolveFromEventName(this.name); } public static Builder builder() { return new Builder(); } public static class Builder extends EventInternalBuilder { Builder() { super(); } @Override public Event build() { final Event event = super.build(); event.init(); return event; } } // Returns teams sorted by their results for this event // It's possible that not all teams play in the Elimination phase. // For example: 13 inschijvingen, dubbel/gemengd -> vierde & vijfde uit poule spelen geen eindronde // In that case multiple teams end at the same Event-rank and should get equal points public SortedMap<Integer, List<Team>> sortTeamsByEventResult() { final TreeMap<Integer, List<Team>> result = new TreeMap<>(); if (rounds.isEmpty()) { log.info("Event has no rounds:" + this); } else if (eliminationSchemes.isEmpty() && rounds.size() == 1) { //Geen eindrondes, enkel 1 poule final List<Team> teamsSortedByPouleResult = rounds.get(0).getTeamsSortedByPouleResult(); for (int i = 0; i < teamsSortedByPouleResult.size(); i++) { result.put(i + 1, Arrays.asList(teamsSortedByPouleResult.get(i))); } } else if (eliminationSchemes.size() > 0) { //Sort EliminationScheme so winners scheme come in front eliminationSchemes.sort(new EliminationSchemeComparator(this)); final AtomicInteger resultPosition = new AtomicInteger(0); for (final EliminationScheme eliminationScheme : eliminationSchemes) { final SortedMap<Integer, List<Team>> teamsSortedByEliminationResult = eliminationScheme.getTeamsSortedByEliminationResult(); teamsSortedByEliminationResult.keySet().forEach(k -> result.put(resultPosition.addAndGet(1), teamsSortedByEliminationResult.get(k))); } //Add teams that are part of a round but did not make it into the EliminationSchemes final List<Team> teamsPartOfEliminationsSchemes = eliminationSchemes.stream().flatMap(e -> e.getAllTeams().stream()).collect(Collectors.toList()); final TreeMap<Integer, List<Team>> remainingTeams = new TreeMap<>(Comparator.reverseOrder()); this.getRounds().forEach(round -> { final List<Team> teamsSortedByPouleResult = round.getTeamsSortedByPouleResult(); for (int i = 0; i < teamsSortedByPouleResult.size(); i++) { final Team team = teamsSortedByPouleResult.get(i); if (!teamsPartOfEliminationsSchemes.contains(team)) { remainingTeams.compute(i, (k, v) -> { if (v == null) { return new ArrayList<>(Arrays.asList(team)); } else { v.add(team); return v; } }); } } }); remainingTeams.keySet().stream() .sorted() .forEach(k -> { result.put(resultPosition.addAndGet(1), remainingTeams.get(k)); }); return result; } else { throw new IllegalArgumentException("Event has more than one round but no eliminationscheme." + this); } return result; } private Set<Team> getTeams() { if (rounds.isEmpty()) { throw new RuntimeException("No rounds are yet assigned to this Event" + this); } return rounds.stream().flatMap(r -> r.getAllTeams().stream()).collect(Collectors.toSet()); } }
Badminton-PBO/pbo-jeugdcupranking
core/src/main/java/be/pbo/jeugdcup/ranking/domain/Event.java
1,453
// For example: 13 inschijvingen, dubbel/gemengd -> vierde & vijfde uit poule spelen geen eindronde
line_comment
nl
package be.pbo.jeugdcup.ranking.domain; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; @Data @Builder(toBuilder = true, builderClassName = "EventInternalBuilder", builderMethodName = "internalBuilder") @AllArgsConstructor(access = AccessLevel.PUBLIC) @NoArgsConstructor(access = AccessLevel.PUBLIC) @Slf4j public class Event { private static final AgeCategoryDetector ageCategoryDetector = new AgeCategoryDetector(); private static final ReeksDetector reeksDetector = new ReeksDetector(); private Integer id; private String name; private Gender gender; private EventType eventType; private AgeCategory ageCategory = AgeCategory.DEFAULT_AGE_CATEGORY; private Reeks reeks = Reeks.DEFAULT_REEKS; private List<Round> rounds = new ArrayList<>(); private List<EliminationScheme> eliminationSchemes = new ArrayList<>(); public void init() { ageCategory = ageCategoryDetector.resolveFromEventName(this.name); reeks = reeksDetector.resolveFromEventName(this.name); } public static Builder builder() { return new Builder(); } public static class Builder extends EventInternalBuilder { Builder() { super(); } @Override public Event build() { final Event event = super.build(); event.init(); return event; } } // Returns teams sorted by their results for this event // It's possible that not all teams play in the Elimination phase. // For example:<SUF> // In that case multiple teams end at the same Event-rank and should get equal points public SortedMap<Integer, List<Team>> sortTeamsByEventResult() { final TreeMap<Integer, List<Team>> result = new TreeMap<>(); if (rounds.isEmpty()) { log.info("Event has no rounds:" + this); } else if (eliminationSchemes.isEmpty() && rounds.size() == 1) { //Geen eindrondes, enkel 1 poule final List<Team> teamsSortedByPouleResult = rounds.get(0).getTeamsSortedByPouleResult(); for (int i = 0; i < teamsSortedByPouleResult.size(); i++) { result.put(i + 1, Arrays.asList(teamsSortedByPouleResult.get(i))); } } else if (eliminationSchemes.size() > 0) { //Sort EliminationScheme so winners scheme come in front eliminationSchemes.sort(new EliminationSchemeComparator(this)); final AtomicInteger resultPosition = new AtomicInteger(0); for (final EliminationScheme eliminationScheme : eliminationSchemes) { final SortedMap<Integer, List<Team>> teamsSortedByEliminationResult = eliminationScheme.getTeamsSortedByEliminationResult(); teamsSortedByEliminationResult.keySet().forEach(k -> result.put(resultPosition.addAndGet(1), teamsSortedByEliminationResult.get(k))); } //Add teams that are part of a round but did not make it into the EliminationSchemes final List<Team> teamsPartOfEliminationsSchemes = eliminationSchemes.stream().flatMap(e -> e.getAllTeams().stream()).collect(Collectors.toList()); final TreeMap<Integer, List<Team>> remainingTeams = new TreeMap<>(Comparator.reverseOrder()); this.getRounds().forEach(round -> { final List<Team> teamsSortedByPouleResult = round.getTeamsSortedByPouleResult(); for (int i = 0; i < teamsSortedByPouleResult.size(); i++) { final Team team = teamsSortedByPouleResult.get(i); if (!teamsPartOfEliminationsSchemes.contains(team)) { remainingTeams.compute(i, (k, v) -> { if (v == null) { return new ArrayList<>(Arrays.asList(team)); } else { v.add(team); return v; } }); } } }); remainingTeams.keySet().stream() .sorted() .forEach(k -> { result.put(resultPosition.addAndGet(1), remainingTeams.get(k)); }); return result; } else { throw new IllegalArgumentException("Event has more than one round but no eliminationscheme." + this); } return result; } private Set<Team> getTeams() { if (rounds.isEmpty()) { throw new RuntimeException("No rounds are yet assigned to this Event" + this); } return rounds.stream().flatMap(r -> r.getAllTeams().stream()).collect(Collectors.toSet()); } }
True
1,066
37
1,191
39
1,238
31
1,191
39
1,454
35
false
false
false
false
false
true
4,692
131308_13
package hotel.userinterface; import hotel.model.Hotel; import hotel.model.KamerType; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.TextField; import java.time.LocalDate; import javafx.stage.Stage; public class BoekingenController { @FXML private Label errorLabel; @FXML private TextField naamTextField; @FXML private TextField adresTextField; @FXML private DatePicker aankomstDatePicker; @FXML private DatePicker vertrekDatePicker; @FXML private ComboBox<KamerType> kamertypeComboBox; private HotelOverzichtController hotelOverzichtController; private Stage stage; // Add a field to store the reference to the stage // Setter method to set the stage public void setStage(Stage stage) { this.stage = stage; } private Hotel hotel = Hotel.getHotel(); public void setHotelOverzichtController(HotelOverzichtController hotelOverzichtController) { this.hotelOverzichtController = hotelOverzichtController; } @FXML private void initialize() { // Initialize the kamertypeComboBox with available KamerTypes ObservableList<KamerType> kamerTypes = FXCollections.observableArrayList(hotel.getKamerTypen()); kamertypeComboBox.setItems(kamerTypes); System.out.println("BoekingenController initialized!"); } @FXML private void resetForm() { // Reset all fields to their initial state naamTextField.clear(); adresTextField.clear(); aankomstDatePicker.setValue(null); vertrekDatePicker.setValue(null); kamertypeComboBox.getSelectionModel().clearSelection(); if (errorLabel != null) { errorLabel.setText(""); } } @FXML private void handleBoekButtonAction() { System.out.println("Boek button clicked!"); // Ensure that errorLabel is not null before invoking setText if (errorLabel != null) { errorLabel.setText(""); // Clear any previous error messages } try { // Get the selected values from the form String naam = naamTextField.getText(); String adres = adresTextField.getText(); LocalDate aankomstDatum = aankomstDatePicker.getValue(); LocalDate vertrekDatum = vertrekDatePicker.getValue(); KamerType selectedKamerType = kamertypeComboBox.getValue(); // Perform basic validation if (naam.isEmpty() || adres.isEmpty() || aankomstDatum == null || vertrekDatum == null || selectedKamerType == null) { throw new Exception("Vul alle velden in"); } // Perform validation for enddate if (aankomstDatum.isBefore(LocalDate.now())) { throw new Exception("De aankomstdatum moet vandaag of later zijn"); } // Perform validation for end date being later than the arrival date if (aankomstDatum.isAfter(vertrekDatum)) { throw new Exception("De vertrekdatum moet later zijn dan de aankomstdatum"); } // Try to create a new booking hotel.voegBoekingToe(aankomstDatum, vertrekDatum, naam, adres, selectedKamerType); // Reset the form after a successful booking resetForm(); // Call a method on HotelOverzichtController to update UI if (hotelOverzichtController != null) { hotelOverzichtController.updateBoekingen(); } // Close the Boekingen screen if (stage != null) { stage.close(); } } catch (Exception e) { // Handle the exception, display an error message if (errorLabel != null) { errorLabel.setText("Fout bij het maken van de boeking: " + e.getMessage()); System.out.println(e.getMessage()); } } } }
wesselvandenijssel/Oop-les-7
Practicum 10/src/hotel/userinterface/BoekingenController.java
1,131
// Close the Boekingen screen
line_comment
nl
package hotel.userinterface; import hotel.model.Hotel; import hotel.model.KamerType; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.ComboBox; import javafx.scene.control.DatePicker; import javafx.scene.control.Label; import javafx.scene.control.TextField; import java.time.LocalDate; import javafx.stage.Stage; public class BoekingenController { @FXML private Label errorLabel; @FXML private TextField naamTextField; @FXML private TextField adresTextField; @FXML private DatePicker aankomstDatePicker; @FXML private DatePicker vertrekDatePicker; @FXML private ComboBox<KamerType> kamertypeComboBox; private HotelOverzichtController hotelOverzichtController; private Stage stage; // Add a field to store the reference to the stage // Setter method to set the stage public void setStage(Stage stage) { this.stage = stage; } private Hotel hotel = Hotel.getHotel(); public void setHotelOverzichtController(HotelOverzichtController hotelOverzichtController) { this.hotelOverzichtController = hotelOverzichtController; } @FXML private void initialize() { // Initialize the kamertypeComboBox with available KamerTypes ObservableList<KamerType> kamerTypes = FXCollections.observableArrayList(hotel.getKamerTypen()); kamertypeComboBox.setItems(kamerTypes); System.out.println("BoekingenController initialized!"); } @FXML private void resetForm() { // Reset all fields to their initial state naamTextField.clear(); adresTextField.clear(); aankomstDatePicker.setValue(null); vertrekDatePicker.setValue(null); kamertypeComboBox.getSelectionModel().clearSelection(); if (errorLabel != null) { errorLabel.setText(""); } } @FXML private void handleBoekButtonAction() { System.out.println("Boek button clicked!"); // Ensure that errorLabel is not null before invoking setText if (errorLabel != null) { errorLabel.setText(""); // Clear any previous error messages } try { // Get the selected values from the form String naam = naamTextField.getText(); String adres = adresTextField.getText(); LocalDate aankomstDatum = aankomstDatePicker.getValue(); LocalDate vertrekDatum = vertrekDatePicker.getValue(); KamerType selectedKamerType = kamertypeComboBox.getValue(); // Perform basic validation if (naam.isEmpty() || adres.isEmpty() || aankomstDatum == null || vertrekDatum == null || selectedKamerType == null) { throw new Exception("Vul alle velden in"); } // Perform validation for enddate if (aankomstDatum.isBefore(LocalDate.now())) { throw new Exception("De aankomstdatum moet vandaag of later zijn"); } // Perform validation for end date being later than the arrival date if (aankomstDatum.isAfter(vertrekDatum)) { throw new Exception("De vertrekdatum moet later zijn dan de aankomstdatum"); } // Try to create a new booking hotel.voegBoekingToe(aankomstDatum, vertrekDatum, naam, adres, selectedKamerType); // Reset the form after a successful booking resetForm(); // Call a method on HotelOverzichtController to update UI if (hotelOverzichtController != null) { hotelOverzichtController.updateBoekingen(); } // Close the<SUF> if (stage != null) { stage.close(); } } catch (Exception e) { // Handle the exception, display an error message if (errorLabel != null) { errorLabel.setText("Fout bij het maken van de boeking: " + e.getMessage()); System.out.println(e.getMessage()); } } } }
True
838
7
925
7
939
6
925
7
1,078
7
false
false
false
false
false
true
3,668
98768_4
/******************************************************************************* * Copyright 2019 Viridian Software Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.mini2Dx.core; import org.mini2Dx.core.collision.Collisions; import org.mini2Dx.core.serialization.JsonSerializer; import org.mini2Dx.core.serialization.XmlSerializer; import org.mini2Dx.lockprovider.Locks; /** * Mini2Dx environment class<br> * <br> * Note: Everything is public static to allow cross-platform reference setting. These variables should not be modified. */ public class Mdx { /** * {@link Audio} API */ public static Audio audio; /** * Object pool for {@link org.mini2Dx.core.collision.CollisionObject} classes */ public static final Collisions collisions = new Collisions(); /** * {@link DependencyInjection} API */ public static DependencyInjection di; /** * {@link TaskExecutor} API */ public static TaskExecutor executor; /** * {@link Files} API */ public static Files files; /** * {@link Fonts} API */ public static Fonts fonts; /** * This game's unique identifier for app stores */ public static String gameIdentifier; /** * Object pool for {@link Geometry} classes */ public static final Geometry geom = new Geometry(); /** * {@link GraphicsUtils} API */ public static GraphicsUtils graphics; /** * {@link Graphics} API - should not be called */ public static Graphics graphicsContext; /** * {@link Input} API */ public static Input input; /** * {@link Locks} API */ public static Locks locks; /** * JSON Serialization API */ public static JsonSerializer json; /** * {@link Logger} API */ public static Logger log; /** * Returns the current {@link Platform} */ public static Platform platform; /** * API for reading/writing {@link PlayerData} */ public static PlayerData playerData; /** * API for reflection */ public static Reflection reflect; /** * Returns the current {@link ApiRuntime} */ public static ApiRuntime runtime; /** * Returns the {@link TimestepMode} specified at launch */ public static TimestepMode timestepMode = TimestepMode.DEFAULT; /** * XML serialization API */ public static XmlSerializer xml; /** * Platform utilities API */ public static PlatformUtils platformUtils; }
mini2Dx/mini2Dx
core/src/main/java/org/mini2Dx/core/Mdx.java
832
/** * {@link DependencyInjection} API */
block_comment
nl
/******************************************************************************* * Copyright 2019 Viridian Software Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package org.mini2Dx.core; import org.mini2Dx.core.collision.Collisions; import org.mini2Dx.core.serialization.JsonSerializer; import org.mini2Dx.core.serialization.XmlSerializer; import org.mini2Dx.lockprovider.Locks; /** * Mini2Dx environment class<br> * <br> * Note: Everything is public static to allow cross-platform reference setting. These variables should not be modified. */ public class Mdx { /** * {@link Audio} API */ public static Audio audio; /** * Object pool for {@link org.mini2Dx.core.collision.CollisionObject} classes */ public static final Collisions collisions = new Collisions(); /** * {@link DependencyInjection} API<SUF>*/ public static DependencyInjection di; /** * {@link TaskExecutor} API */ public static TaskExecutor executor; /** * {@link Files} API */ public static Files files; /** * {@link Fonts} API */ public static Fonts fonts; /** * This game's unique identifier for app stores */ public static String gameIdentifier; /** * Object pool for {@link Geometry} classes */ public static final Geometry geom = new Geometry(); /** * {@link GraphicsUtils} API */ public static GraphicsUtils graphics; /** * {@link Graphics} API - should not be called */ public static Graphics graphicsContext; /** * {@link Input} API */ public static Input input; /** * {@link Locks} API */ public static Locks locks; /** * JSON Serialization API */ public static JsonSerializer json; /** * {@link Logger} API */ public static Logger log; /** * Returns the current {@link Platform} */ public static Platform platform; /** * API for reading/writing {@link PlayerData} */ public static PlayerData playerData; /** * API for reflection */ public static Reflection reflect; /** * Returns the current {@link ApiRuntime} */ public static ApiRuntime runtime; /** * Returns the {@link TimestepMode} specified at launch */ public static TimestepMode timestepMode = TimestepMode.DEFAULT; /** * XML serialization API */ public static XmlSerializer xml; /** * Platform utilities API */ public static PlatformUtils platformUtils; }
False
677
12
695
11
788
13
695
11
879
15
false
false
false
false
false
true
921
200620_39
package swisseph; /** * Interface for different methods used for transit calculations. */ public abstract class TransitCalculator implements java.io.Serializable { SwissEph sw; // This method changes the offset value for the transit /** * @return Returns true, if one position value is identical to another * position value. E.g., 360 degree is identical to 0 degree in * circular angles. * @see #rolloverVal */ public abstract boolean getRollover(); /** * @return Returns the value, which is identical to zero on the other * end of a linear scale. * @see #rolloverVal */ public double getRolloverVal() { return rolloverVal; } /** * This sets the degree or other value for the position or speed of * the planet to transit. It will be used on the next call to getTransit(). * @param value The desired offset value. * @see #getOffset() */ public abstract void setOffset(double value); /** * This returns the degree or other value of the position or speed of * the planet to transit. * @return The currently set offset value. * @see #setOffset(double) */ public abstract double getOffset(); /** * This returns all the &quot;object identifiers&quot; used in this * TransitCalculator. It may be the planet number or planet numbers, * when calculating planets. * @return An array of identifiers identifying the calculated objects. */ public Object[] getObjectIdentifiers() { return null; } ////////////////////////////////////////////////////////////////////////////// // Rollover from 360 degrees to 0 degrees for planetary longitudinal positions // or similar, or continuous and unlimited values: protected boolean rollover = false; // We need a rollover of 360 degrees being // equal to 0 degrees for longitudinal // position transits only. protected double rolloverVal = 360.; // if rollover, we roll over from 360 to 0 // as default. Other values than 0.0 for the // minimum values are not supported for now. // These methods have to return the maxima of the first derivative of the // function, mathematically spoken... protected abstract double getMaxSpeed(); protected abstract double getMinSpeed(); // This method returns the precision in x-direction in an x-y-coordinate // system for the transit calculation routine. protected abstract double getDegreePrecision(double jdET); // This method returns the precision in y-direction in an x-y-coordinate // system from the x-direction precision. protected abstract double getTimePrecision(double degPrec); // This is the main routine, mathematically speaking: returning f(x): protected abstract double calc(double jdET); // This routine allows for changing jdET before starting calculations. double preprocessDate(double jdET, boolean back) { return jdET; } // These routines check the result if it meets the stop condition protected boolean checkIdenticalResult(double offset, double val) { return val == offset; } protected boolean checkResult(double offset, double lastVal, double val, boolean above, boolean pxway) { return (// transits from higher deg. to lower deg.: ( above && val<=offset && !pxway) || // transits from lower deg. to higher deg.: (!above && val>=offset && pxway)) || (rollover && ( // transits from above the transit degree via rollover over // 0 degrees to a higher degree: (offset<lastVal && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from below the transit degree via rollover over // 360 degrees to a lower degree: (offset>lastVal && val<20. && lastVal>.9*rolloverVal && pxway) || // transits from below the transit degree via rollover over // 0 degrees to a higher degree: (offset>val && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from above the transit degree via rollover over // 360 degrees to a lower degree: (offset<val && val<20. && lastVal>.9*rolloverVal && pxway)) ); } // Find next reasonable point to probe. protected double getNextJD(double jdET, double val, double offset, double min, double max, boolean back) { double jdPlus = 0; double jdMinus = 0; if (rollover) { // In most cases here we cannot find out for sure if the distance // is decreasing or increasing. We take the smaller one of these: jdPlus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(max); jdMinus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(min); if (back) { jdET -= SMath.min(jdPlus,jdMinus); } else { jdET += SMath.min(jdPlus,jdMinus); } } else { // Latitude, distance and speed calculations... //jdPlus = (back?(val-offset):(offset-val))/max; //jdMinus = (back?(val-offset):(offset-val))/min; jdPlus = (offset-val)/max; jdMinus = (offset-val)/min; if (back) { if (jdPlus >= 0 && jdMinus >= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus >= 0) { jdET += jdMinus; } else { // if (jdMinus >= 0) jdET += jdPlus; } } else { if (jdPlus <= 0 && jdMinus <= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus <= 0) { jdET += jdMinus; } else { // if (jdMinus <= 0) jdET += jdPlus; } } } return jdET; } }
Kibo/AstroAPI
src/main/java/swisseph/TransitCalculator.java
1,711
//jdMinus = (back?(val-offset):(offset-val))/min;
line_comment
nl
package swisseph; /** * Interface for different methods used for transit calculations. */ public abstract class TransitCalculator implements java.io.Serializable { SwissEph sw; // This method changes the offset value for the transit /** * @return Returns true, if one position value is identical to another * position value. E.g., 360 degree is identical to 0 degree in * circular angles. * @see #rolloverVal */ public abstract boolean getRollover(); /** * @return Returns the value, which is identical to zero on the other * end of a linear scale. * @see #rolloverVal */ public double getRolloverVal() { return rolloverVal; } /** * This sets the degree or other value for the position or speed of * the planet to transit. It will be used on the next call to getTransit(). * @param value The desired offset value. * @see #getOffset() */ public abstract void setOffset(double value); /** * This returns the degree or other value of the position or speed of * the planet to transit. * @return The currently set offset value. * @see #setOffset(double) */ public abstract double getOffset(); /** * This returns all the &quot;object identifiers&quot; used in this * TransitCalculator. It may be the planet number or planet numbers, * when calculating planets. * @return An array of identifiers identifying the calculated objects. */ public Object[] getObjectIdentifiers() { return null; } ////////////////////////////////////////////////////////////////////////////// // Rollover from 360 degrees to 0 degrees for planetary longitudinal positions // or similar, or continuous and unlimited values: protected boolean rollover = false; // We need a rollover of 360 degrees being // equal to 0 degrees for longitudinal // position transits only. protected double rolloverVal = 360.; // if rollover, we roll over from 360 to 0 // as default. Other values than 0.0 for the // minimum values are not supported for now. // These methods have to return the maxima of the first derivative of the // function, mathematically spoken... protected abstract double getMaxSpeed(); protected abstract double getMinSpeed(); // This method returns the precision in x-direction in an x-y-coordinate // system for the transit calculation routine. protected abstract double getDegreePrecision(double jdET); // This method returns the precision in y-direction in an x-y-coordinate // system from the x-direction precision. protected abstract double getTimePrecision(double degPrec); // This is the main routine, mathematically speaking: returning f(x): protected abstract double calc(double jdET); // This routine allows for changing jdET before starting calculations. double preprocessDate(double jdET, boolean back) { return jdET; } // These routines check the result if it meets the stop condition protected boolean checkIdenticalResult(double offset, double val) { return val == offset; } protected boolean checkResult(double offset, double lastVal, double val, boolean above, boolean pxway) { return (// transits from higher deg. to lower deg.: ( above && val<=offset && !pxway) || // transits from lower deg. to higher deg.: (!above && val>=offset && pxway)) || (rollover && ( // transits from above the transit degree via rollover over // 0 degrees to a higher degree: (offset<lastVal && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from below the transit degree via rollover over // 360 degrees to a lower degree: (offset>lastVal && val<20. && lastVal>.9*rolloverVal && pxway) || // transits from below the transit degree via rollover over // 0 degrees to a higher degree: (offset>val && val>.9*rolloverVal && lastVal<20. && !pxway) || // transits from above the transit degree via rollover over // 360 degrees to a lower degree: (offset<val && val<20. && lastVal>.9*rolloverVal && pxway)) ); } // Find next reasonable point to probe. protected double getNextJD(double jdET, double val, double offset, double min, double max, boolean back) { double jdPlus = 0; double jdMinus = 0; if (rollover) { // In most cases here we cannot find out for sure if the distance // is decreasing or increasing. We take the smaller one of these: jdPlus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(max); jdMinus = SMath.min(val-offset,rolloverVal-val+offset)/SMath.abs(min); if (back) { jdET -= SMath.min(jdPlus,jdMinus); } else { jdET += SMath.min(jdPlus,jdMinus); } } else { // Latitude, distance and speed calculations... //jdPlus = (back?(val-offset):(offset-val))/max; //jdMinus =<SUF> jdPlus = (offset-val)/max; jdMinus = (offset-val)/min; if (back) { if (jdPlus >= 0 && jdMinus >= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus >= 0) { jdET += jdMinus; } else { // if (jdMinus >= 0) jdET += jdPlus; } } else { if (jdPlus <= 0 && jdMinus <= 0) { throw new SwissephException(jdET, SwissephException.OUT_OF_TIME_RANGE, -1, "No transit in ephemeris time range."); // I mean: No transits possible... } else if (jdPlus <= 0) { jdET += jdMinus; } else { // if (jdMinus <= 0) jdET += jdPlus; } } } return jdET; } }
False
1,447
15
1,488
18
1,589
17
1,488
18
1,735
20
false
false
false
false
false
true
4,506
191252_14
/* * @(#)MathConstants.java 2.1.1-1 2016-01-07 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariusz.gromada@mathspace.pl * http://mathspace.pl/ * http://mathparser.org/ * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser/ * http://mxparser.sourceforge.net/ * http://bitbucket.org/mariuszgromada/mxparser/ * http://mxparser.codeplex.com/ * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ package org.mariuszgromada.math.mxparser.mathcollection; /** * MathConstants - class representing the most important math constants. * * @author <b>Mariusz Gromada</b><br/> * <a href="mailto:mariusz.gromada@mathspace.pl">mariusz.gromada@mathspace.pl</a><br> * <a href="http://mathspace.pl/" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org/" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mariuszgromada.github.io/MathParser.org-mXparser/" target="_blank">mXparser on GitHub pages</a><br> * <a href="http://mxparser.sourceforge.net/" target="_blank">mXparser on SourceForge/</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser/" target="_blank">mXparser on Bitbucket/</a><br> * <a href="http://mxparser.codeplex.com/" target="_blank">mXparser on CodePlex/</a><br> * * @version 2.1.1-1 */ public final class MathConstants { /** * Pi, Archimedes' constant or Ludolph's number */ public static final double PI = 3.14159265358979323846264338327950288; /** * Napier's constant, or Euler's number, base of Natural logarithm */ public static final double E = 2.71828182845904523536028747135266249; /** * Euler-Mascheroni constant */ public static final double EULER_MASCHERONI = 0.57721566490153286060651209008240243; /** * Golden ratio */ public static final double GOLDEN_RATIO = 1.61803398874989484820458683436563811; /** * Plastic constant */ public static final double PLASTIC = 1.32471795724474602596090885447809734; /** * Embree-Trefethen constant */ public static final double EMBREE_TREFETHEN = 0.70258; /** * Feigenbaum constant */ public static final double FEIGENBAUM_DELTA = 4.66920160910299067185320382046620161; /** * Feigenbaum constant */ public static final double FEIGENBAUM_ALFA = 2.50290787509589282228390287321821578; /** * Feigenbaum constant */ public static final double TWIN_PRIME = 0.66016181584686957392781211001455577; /** * Meissel-Mertens constant */ public static final double MEISSEL_MERTEENS = 0.26149721284764278375542683860869585; /** * Brun's constant for twin primes */ public static final double BRAUN_TWIN_PRIME = 1.9021605823; /** * Brun's constant for prime quadruplets */ public static final double BRAUN_PRIME_QUADR = 0.8705883800; /** * de Bruijn-Newman constant */ public static final double BRUIJN_NEWMAN = -2.7E-9; /** * Catalan's constant */ public static final double CATALAN = 0.91596559417721901505460351493238411; /** * Landau-Ramanujan constant */ public static final double LANDAU_RAMANUJAN = 0.76422365358922066299069873125009232; /** * Viswanath's constant */ public static final double VISWANATH = 1.13198824; /** * Legendre's constant */ public static final double LEGENDRE = 1.0; /** * Ramanujan-Soldner constant */ public static final double RAMANUJAN_SOLDNER = 1.45136923488338105028396848589202744; /** * Erdos-Borwein constant */ public static final double ERDOS_BORWEIN = 1.60669515241529176378330152319092458; /** * Bernstein's constant */ public static final double BERNSTEIN = 0.28016949902386913303; /** * Gauss-Kuzmin-Wirsing constant */ public static final double GAUSS_KUZMIN_WIRSING = 0.30366300289873265859744812190155623; /** * Hafner-Sarnak-McCurley constant */ public static final double HAFNER_SARNAK_MCCURLEY = 0.35323637185499598454; /** * Golomb-Dickman constant */ public static final double GOLOMB_DICKMAN = 0.62432998854355087099293638310083724; /** * Cahen's constant */ public static final double CAHEN = 0.6434105463; /** * Laplace limit */ public static final double LAPLACE_LIMIT = 0.66274341934918158097474209710925290; /** * Alladi-Grinstead constant */ public static final double ALLADI_GRINSTEAD = 0.8093940205; /** * Lengyel's constant */ public static final double LENGYEL = 1.0986858055; /** * Levy's constant */ public static final double LEVY = 3.27582291872181115978768188245384386; /** * Apery's constant */ public static final double APERY = 1.20205690315959428539973816151144999; /** * Mills' constant */ public static final double MILLS = 1.30637788386308069046861449260260571; /** * Backhouse's constant */ public static final double BACKHOUSE = 1.45607494858268967139959535111654356; /** * Porter's constant */ public static final double PORTER = 1.4670780794; /** * Porter's constant */ public static final double LIEB_QUARE_ICE = 1.5396007178; /** * Niven's constant */ public static final double NIVEN = 1.70521114010536776428855145343450816; /** * Sierpiński's constant */ public static final double SIERPINSKI = 2.58498175957925321706589358738317116; /** * Khinchin's constant */ public static final double KHINCHIN = 2.68545200106530644530971483548179569; /** * Fransén-Robinson constant */ public static final double FRANSEN_ROBINSON = 2.80777024202851936522150118655777293; /** * Landau's constant */ public static final double LANDAU = 0.5; /** * Parabolic constant */ public static final double PARABOLIC = 2.29558714939263807403429804918949039; /** * Omega constant */ public static final double OMEGA = 0.56714329040978387299996866221035555; /** * MRB constant */ public static final double MRB = 0.187859; }
tiagogoncalves/MathParser.org-mXparser
STABLE/2.2.0/java/src/org/mariuszgromada/math/mxparser/mathcollection/MathConstants.java
2,801
/** * de Bruijn-Newman constant */
block_comment
nl
/* * @(#)MathConstants.java 2.1.1-1 2016-01-07 * * You may use this software under the condition of "Simplified BSD License" * * Copyright 2010-2016 MARIUSZ GROMADA. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY <MARIUSZ GROMADA> ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of MARIUSZ GROMADA. * * If you have any questions/bugs feel free to contact: * * Mariusz Gromada * mariusz.gromada@mathspace.pl * http://mathspace.pl/ * http://mathparser.org/ * http://github.com/mariuszgromada/MathParser.org-mXparser * http://mariuszgromada.github.io/MathParser.org-mXparser/ * http://mxparser.sourceforge.net/ * http://bitbucket.org/mariuszgromada/mxparser/ * http://mxparser.codeplex.com/ * * Asked if he believes in one God, a mathematician answered: * "Yes, up to isomorphism." */ package org.mariuszgromada.math.mxparser.mathcollection; /** * MathConstants - class representing the most important math constants. * * @author <b>Mariusz Gromada</b><br/> * <a href="mailto:mariusz.gromada@mathspace.pl">mariusz.gromada@mathspace.pl</a><br> * <a href="http://mathspace.pl/" target="_blank">MathSpace.pl</a><br> * <a href="http://mathparser.org/" target="_blank">MathParser.org - mXparser project page</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * <a href="http://mariuszgromada.github.io/MathParser.org-mXparser/" target="_blank">mXparser on GitHub pages</a><br> * <a href="http://mxparser.sourceforge.net/" target="_blank">mXparser on SourceForge/</a><br> * <a href="http://bitbucket.org/mariuszgromada/mxparser/" target="_blank">mXparser on Bitbucket/</a><br> * <a href="http://mxparser.codeplex.com/" target="_blank">mXparser on CodePlex/</a><br> * * @version 2.1.1-1 */ public final class MathConstants { /** * Pi, Archimedes' constant or Ludolph's number */ public static final double PI = 3.14159265358979323846264338327950288; /** * Napier's constant, or Euler's number, base of Natural logarithm */ public static final double E = 2.71828182845904523536028747135266249; /** * Euler-Mascheroni constant */ public static final double EULER_MASCHERONI = 0.57721566490153286060651209008240243; /** * Golden ratio */ public static final double GOLDEN_RATIO = 1.61803398874989484820458683436563811; /** * Plastic constant */ public static final double PLASTIC = 1.32471795724474602596090885447809734; /** * Embree-Trefethen constant */ public static final double EMBREE_TREFETHEN = 0.70258; /** * Feigenbaum constant */ public static final double FEIGENBAUM_DELTA = 4.66920160910299067185320382046620161; /** * Feigenbaum constant */ public static final double FEIGENBAUM_ALFA = 2.50290787509589282228390287321821578; /** * Feigenbaum constant */ public static final double TWIN_PRIME = 0.66016181584686957392781211001455577; /** * Meissel-Mertens constant */ public static final double MEISSEL_MERTEENS = 0.26149721284764278375542683860869585; /** * Brun's constant for twin primes */ public static final double BRAUN_TWIN_PRIME = 1.9021605823; /** * Brun's constant for prime quadruplets */ public static final double BRAUN_PRIME_QUADR = 0.8705883800; /** * de Bruijn-Newman constant<SUF>*/ public static final double BRUIJN_NEWMAN = -2.7E-9; /** * Catalan's constant */ public static final double CATALAN = 0.91596559417721901505460351493238411; /** * Landau-Ramanujan constant */ public static final double LANDAU_RAMANUJAN = 0.76422365358922066299069873125009232; /** * Viswanath's constant */ public static final double VISWANATH = 1.13198824; /** * Legendre's constant */ public static final double LEGENDRE = 1.0; /** * Ramanujan-Soldner constant */ public static final double RAMANUJAN_SOLDNER = 1.45136923488338105028396848589202744; /** * Erdos-Borwein constant */ public static final double ERDOS_BORWEIN = 1.60669515241529176378330152319092458; /** * Bernstein's constant */ public static final double BERNSTEIN = 0.28016949902386913303; /** * Gauss-Kuzmin-Wirsing constant */ public static final double GAUSS_KUZMIN_WIRSING = 0.30366300289873265859744812190155623; /** * Hafner-Sarnak-McCurley constant */ public static final double HAFNER_SARNAK_MCCURLEY = 0.35323637185499598454; /** * Golomb-Dickman constant */ public static final double GOLOMB_DICKMAN = 0.62432998854355087099293638310083724; /** * Cahen's constant */ public static final double CAHEN = 0.6434105463; /** * Laplace limit */ public static final double LAPLACE_LIMIT = 0.66274341934918158097474209710925290; /** * Alladi-Grinstead constant */ public static final double ALLADI_GRINSTEAD = 0.8093940205; /** * Lengyel's constant */ public static final double LENGYEL = 1.0986858055; /** * Levy's constant */ public static final double LEVY = 3.27582291872181115978768188245384386; /** * Apery's constant */ public static final double APERY = 1.20205690315959428539973816151144999; /** * Mills' constant */ public static final double MILLS = 1.30637788386308069046861449260260571; /** * Backhouse's constant */ public static final double BACKHOUSE = 1.45607494858268967139959535111654356; /** * Porter's constant */ public static final double PORTER = 1.4670780794; /** * Porter's constant */ public static final double LIEB_QUARE_ICE = 1.5396007178; /** * Niven's constant */ public static final double NIVEN = 1.70521114010536776428855145343450816; /** * Sierpiński's constant */ public static final double SIERPINSKI = 2.58498175957925321706589358738317116; /** * Khinchin's constant */ public static final double KHINCHIN = 2.68545200106530644530971483548179569; /** * Fransén-Robinson constant */ public static final double FRANSEN_ROBINSON = 2.80777024202851936522150118655777293; /** * Landau's constant */ public static final double LANDAU = 0.5; /** * Parabolic constant */ public static final double PARABOLIC = 2.29558714939263807403429804918949039; /** * Omega constant */ public static final double OMEGA = 0.56714329040978387299996866221035555; /** * MRB constant */ public static final double MRB = 0.187859; }
False
2,972
13
3,213
13
3,202
13
3,213
13
3,550
14
false
false
false
false
false
true
2,490
88936_2
/*___INFO__MARK_BEGIN__*/ /************************************************************************* * * The Contents of this file are made available subject to the terms of * the Sun Industry Standards Source License Version 1.2 * * Sun Microsystems Inc., March, 2001 * * * Sun Industry Standards Source License Version 1.2 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.2 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2001 by Sun Microsystems, Inc. * * All Rights Reserved. * ************************************************************************/ /*___INFO__MARK_END__*/ package jqmon;_x000D_ _x000D_ import java.lang.*;_x000D_ import jqmon.debug.*;_x000D_ import jqmon.events.*;_x000D_ import codine.*;_x000D_ _x000D_ /**_x000D_ Diese Klasse repraesentiert den JWorkerThread, das Arbeitstier._x000D_ Er schickt DPrint-Meldungen an den angeschlossenen JDPrintThread,_x000D_ falls einer angeschlossen ist._x000D_ _x000D_ @author Michael Roehrl_x000D_ @version 0,01_x000D_ _x000D_ */_x000D_ _x000D_ public class JWorkerThread extends Thread {_x000D_ _x000D_ /** Soll der Thread beendet werden ? */_x000D_ protected boolean end = false;_x000D_ _x000D_ /** Das globale JDebug-Objekt */_x000D_ protected JDebug debug = null;_x000D_ _x000D_ /** Die JAnswerList */_x000D_ protected JAnswerList answerList = null;_x000D_ _x000D_ /** Die Queue-Liste */_x000D_ protected JQueueList queueList = null;_x000D_ _x000D_ /** Die Host-Liste */_x000D_ protected JHostList hostList = null;_x000D_ _x000D_ /** Das UpdateQueueList Model */_x000D_ protected JUpdateQueueList updateQueueList = null;_x000D_ _x000D_ /** Das UpdateHostList Model */_x000D_ protected JUpdateHostList updateHostList = null;_x000D_ _x000D_ _x000D_ /** Default-Konstruktor. Legt einen JWorkerThread ohne JDPrintThread an._x000D_ Im Normalfall sollte ein JDPrintThread mitangegeben werden._x000D_ */_x000D_ public JWorkerThread(JDebug d, JUpdateQueueList q, JUpdateHostList h) {_x000D_ debug = d;_x000D_ updateQueueList = q;_x000D_ updateHostList = h;_x000D_ answerList = new JAnswerList(10,10);_x000D_ queueList = new JQueueList(10,10);_x000D_ hostList = new JHostList(10,10);_x000D_ }_x000D_ _x000D_ _x000D_ /** Haelt den Thread am Laufen. Er befindet sich in einer Endlosschleife_x000D_ und kann nur doch "stop" angehalten werden._x000D_ */_x000D_ public void run() {_x000D_ contact();_x000D_ try {_x000D_ while( !end ) {_x000D_ work();_x000D_ sleep(1000);_x000D_ }_x000D_ } _x000D_ catch (InterruptedException e) {_x000D_ }_x000D_ catch (ThreadDeath td) {_x000D_ cleanup();_x000D_ throw td; // Muss unbedingt nochmal geworfen werden!!_x000D_ }_x000D_ _x000D_ cleanup();_x000D_ }_x000D_ _x000D_ _x000D_ /** Macht die ganze Arbeit. Wird von run() aufgerufen, weil_x000D_ sich nur so synchronisiert arbeiten laesst. _x000D_ */_x000D_ protected synchronized void work() {_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ /** Setzen des JDPrintThread. Sollte dieser Null sein, so werden keine JDPrintStrings_x000D_ verarbeitet._x000D_ */_x000D_ _x000D_ public synchronized void endThread() {_x000D_ end = true;_x000D_ }_x000D_ _x000D_ protected void cleanup() {_x000D_ }_x000D_ _x000D_ protected synchronized void contact() {_x000D_ debug.DENTER("JWorderThread.contact");_x000D_ contactC();_x000D_ updateQueueList.newJQueueList(answerList, queueList);_x000D_ updateHostList.newJHostList(answerList, hostList);_x000D_ debug.DEXIT();_x000D_ }_x000D_ _x000D_ private native void contactC();_x000D_ private native void getQueue();_x000D_ }_x000D_
daimh/sge
source/experimental/jqmon/jqmon/JWorkerThread.java
1,229
/** Soll der Thread beendet werden ? */
block_comment
nl
/*___INFO__MARK_BEGIN__*/ /************************************************************************* * * The Contents of this file are made available subject to the terms of * the Sun Industry Standards Source License Version 1.2 * * Sun Microsystems Inc., March, 2001 * * * Sun Industry Standards Source License Version 1.2 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.2 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://gridengine.sunsource.net/Gridengine_SISSL_license.html * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2001 by Sun Microsystems, Inc. * * All Rights Reserved. * ************************************************************************/ /*___INFO__MARK_END__*/ package jqmon;_x000D_ _x000D_ import java.lang.*;_x000D_ import jqmon.debug.*;_x000D_ import jqmon.events.*;_x000D_ import codine.*;_x000D_ _x000D_ /**_x000D_ Diese Klasse repraesentiert den JWorkerThread, das Arbeitstier._x000D_ Er schickt DPrint-Meldungen an den angeschlossenen JDPrintThread,_x000D_ falls einer angeschlossen ist._x000D_ _x000D_ @author Michael Roehrl_x000D_ @version 0,01_x000D_ _x000D_ */_x000D_ _x000D_ public class JWorkerThread extends Thread {_x000D_ _x000D_ /** Soll der Thread<SUF>*/_x000D_ protected boolean end = false;_x000D_ _x000D_ /** Das globale JDebug-Objekt */_x000D_ protected JDebug debug = null;_x000D_ _x000D_ /** Die JAnswerList */_x000D_ protected JAnswerList answerList = null;_x000D_ _x000D_ /** Die Queue-Liste */_x000D_ protected JQueueList queueList = null;_x000D_ _x000D_ /** Die Host-Liste */_x000D_ protected JHostList hostList = null;_x000D_ _x000D_ /** Das UpdateQueueList Model */_x000D_ protected JUpdateQueueList updateQueueList = null;_x000D_ _x000D_ /** Das UpdateHostList Model */_x000D_ protected JUpdateHostList updateHostList = null;_x000D_ _x000D_ _x000D_ /** Default-Konstruktor. Legt einen JWorkerThread ohne JDPrintThread an._x000D_ Im Normalfall sollte ein JDPrintThread mitangegeben werden._x000D_ */_x000D_ public JWorkerThread(JDebug d, JUpdateQueueList q, JUpdateHostList h) {_x000D_ debug = d;_x000D_ updateQueueList = q;_x000D_ updateHostList = h;_x000D_ answerList = new JAnswerList(10,10);_x000D_ queueList = new JQueueList(10,10);_x000D_ hostList = new JHostList(10,10);_x000D_ }_x000D_ _x000D_ _x000D_ /** Haelt den Thread am Laufen. Er befindet sich in einer Endlosschleife_x000D_ und kann nur doch "stop" angehalten werden._x000D_ */_x000D_ public void run() {_x000D_ contact();_x000D_ try {_x000D_ while( !end ) {_x000D_ work();_x000D_ sleep(1000);_x000D_ }_x000D_ } _x000D_ catch (InterruptedException e) {_x000D_ }_x000D_ catch (ThreadDeath td) {_x000D_ cleanup();_x000D_ throw td; // Muss unbedingt nochmal geworfen werden!!_x000D_ }_x000D_ _x000D_ cleanup();_x000D_ }_x000D_ _x000D_ _x000D_ /** Macht die ganze Arbeit. Wird von run() aufgerufen, weil_x000D_ sich nur so synchronisiert arbeiten laesst. _x000D_ */_x000D_ protected synchronized void work() {_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ /** Setzen des JDPrintThread. Sollte dieser Null sein, so werden keine JDPrintStrings_x000D_ verarbeitet._x000D_ */_x000D_ _x000D_ public synchronized void endThread() {_x000D_ end = true;_x000D_ }_x000D_ _x000D_ protected void cleanup() {_x000D_ }_x000D_ _x000D_ protected synchronized void contact() {_x000D_ debug.DENTER("JWorderThread.contact");_x000D_ contactC();_x000D_ updateQueueList.newJQueueList(answerList, queueList);_x000D_ updateHostList.newJHostList(answerList, hostList);_x000D_ debug.DEXIT();_x000D_ }_x000D_ _x000D_ private native void contactC();_x000D_ private native void getQueue();_x000D_ }_x000D_
False
1,617
10
1,788
10
1,792
8
1,789
10
1,952
10
false
false
false
false
false
true
1,016
119267_19
package com.molvenolakeresort.hotel.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.molvenolakeresort.hotel.model.Guest; import com.molvenolakeresort.hotel.repository.GuestRepository; import org.jboss.jandex.JandexAntTask; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.jupiter.api.BeforeEach; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(MockitoJUnitRunner.class) @SpringBootTest @FixMethodOrder(MethodSorters.NAME_ASCENDING) @AutoConfigureMockMvc public class GuestControllerTest { @InjectMocks private GuestController guestController; @Mock private GuestRepository guestRepository; private MockMvc mockMvc; private Guest guest; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(guestController).build(); } @Test public void testGetGuestList() throws Exception { List<Guest> guests = new ArrayList<>(); guests.add(new Guest("Piet")); guests.add(new Guest("Klaas")); when(guestRepository.findAll()).thenReturn(guests); this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(2))) .andExpect(MockMvcResultMatchers.jsonPath("$.[0].name").value(guests.get(0).getName())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void testGetGuestById() throws Exception { // List<Guest> guests = new ArrayList<>(); Guest guest = new Guest("Piet"); guest.setId(1); when(guestRepository.findById((long)1)).thenReturn(Optional.of(guest)); this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests/1")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value(guest.getName())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void addGuestTest() throws Exception { Guest newGuest = new Guest("Piet"); when(guestRepository.save(ArgumentMatchers.any(Guest.class))).thenReturn(newGuest); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(newGuest); this.mockMvc.perform(MockMvcRequestBuilders.post("/api/guests") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value(newGuest.getName())) .andExpect(MockMvcResultMatchers.status().isOk()); } // GuestController guestController; // Iterable<Guest> guestList = guestController.findAll(); // // @BeforeEach // void init() { // guestController = new GuestController(); // //// TEST GUEST LIST : // guestController.postGuest(new Guest("Jan Janssen")); // guestController.postGuest(new Guest("Alice")); // guestController.postGuest(new Guest("Bob")); // } // // @Test // void findById() throws EntityNotFoundException { // // Gastinformatie ophalen: // System.out.println("Informatie wordt opgehaald van guest met ID number 1...\n"); // Guest guest; // guest = guestController.findById(1).getBody(); // System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().toArray().length); // // assertEquals("Jane Doe", guestController.findById(3).getBody().getName()); // } // // @Test // void getGuestList() { // System.out.println("Gastenlijst wordt opgehaald..."); // for (Guest guest : guestList) { // System.out.println(guest.getId() + ". " + guest.getName() + ", " + guest.getCity() + ", " + guest.getBookings().toArray().length + " boekingen."); // } // List<Guest> newList = ((List<Guest>)guestList); // assertEquals(); // } // // @Test // void postGuest() { // try { // System.out.println("Registreer nieuwe gast: Jane Appleseed, geboren in 2002, afkomstig uit New York. \n"); // guestController.postGuest(new Guest("Jane Appleseed", "January 24th, 2002", "Jane@email.com", "0316 - 23454321", "AB1234DE", "Chicago Street", "New York")); // // System.out.print("Nieuwe gast geregistreerd. "); //// Guest guest = guestController.getGuest(4); //// System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().length); //// System.out.println(guestController.getGuest(4).toString()); // // System.out.println("\nNieuwe gastenlijst:"); //// for (Guest guestIterator : guestController.getGuestList()) { //// System.out.println(guestIterator.getId() + ". " + guestIterator.getName() + ", " + guestIterator.getCity() + ", " + guestIterator.getBookings().length + " boekingen."); //// } //// assertEquals("Jane Appleseed", guestController.getGuestList().get(3).getName()); //// } catch (EntityNotFoundException e) { //// assertEquals(e.toString(),""); //// } //// } // // @Test // void putGuest() { // try { // System.out.println("Current guest (ID no. 2):"); // System.out.println(guestController.getGuest(2).toString()); // System.out.println("\nUpdating guest and requesting new information...\n"); // // guestController.putGuest(2,"Alice Smith", "February 20th, 1990", "asmith@email.com", "031-12345678", "", "Veemarkt 1, 5678 CD", ""); // System.out.println("\n" + guestController.getGuest(2).toString()); // // assertEquals(guestController.getGuest(2).getName(), "Alice Smith"); // // } catch (EntityNotFoundException e) { // assertEquals(e.toString(), ""); // } // } // // @Test // void deleteGuest() { // try { // System.out.println("Guest to be deleted (ID no. 3):"); // System.out.println(guestController.getGuest(3).toString()); // // System.out.println("\nDeleting guest... Requesting guest information again: "); // guestController.deleteGuest(3); // System.out.println(guestController.getGuest(3).toString()); // // } catch (EntityNotFoundException e) { // System.out.println(e); // assertEquals("com.molvenolakeresort.hotel.controller.EntityNotFoundException: Guest was not found for ID: 3",e.toString()); // } // // } }
MNalbant1/Molveno-Lake-Resort
src/test/java/com/molvenolakeresort/hotel/controller/GuestControllerTest.java
2,498
// System.out.print("Nieuwe gast geregistreerd. ");
line_comment
nl
package com.molvenolakeresort.hotel.controller; import com.fasterxml.jackson.databind.ObjectMapper; import com.molvenolakeresort.hotel.model.Guest; import com.molvenolakeresort.hotel.repository.GuestRepository; import org.jboss.jandex.JandexAntTask; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.jupiter.api.BeforeEach; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.hamcrest.Matchers.any; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(MockitoJUnitRunner.class) @SpringBootTest @FixMethodOrder(MethodSorters.NAME_ASCENDING) @AutoConfigureMockMvc public class GuestControllerTest { @InjectMocks private GuestController guestController; @Mock private GuestRepository guestRepository; private MockMvc mockMvc; private Guest guest; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(guestController).build(); } @Test public void testGetGuestList() throws Exception { List<Guest> guests = new ArrayList<>(); guests.add(new Guest("Piet")); guests.add(new Guest("Klaas")); when(guestRepository.findAll()).thenReturn(guests); this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$", hasSize(2))) .andExpect(MockMvcResultMatchers.jsonPath("$.[0].name").value(guests.get(0).getName())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void testGetGuestById() throws Exception { // List<Guest> guests = new ArrayList<>(); Guest guest = new Guest("Piet"); guest.setId(1); when(guestRepository.findById((long)1)).thenReturn(Optional.of(guest)); this.mockMvc.perform(MockMvcRequestBuilders.get("/api/guests/1")) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value(guest.getName())) .andExpect(MockMvcResultMatchers.status().isOk()); } @Test public void addGuestTest() throws Exception { Guest newGuest = new Guest("Piet"); when(guestRepository.save(ArgumentMatchers.any(Guest.class))).thenReturn(newGuest); ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(newGuest); this.mockMvc.perform(MockMvcRequestBuilders.post("/api/guests") .contentType(MediaType.APPLICATION_JSON) .content(json)) .andDo(MockMvcResultHandlers.print()) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value(newGuest.getName())) .andExpect(MockMvcResultMatchers.status().isOk()); } // GuestController guestController; // Iterable<Guest> guestList = guestController.findAll(); // // @BeforeEach // void init() { // guestController = new GuestController(); // //// TEST GUEST LIST : // guestController.postGuest(new Guest("Jan Janssen")); // guestController.postGuest(new Guest("Alice")); // guestController.postGuest(new Guest("Bob")); // } // // @Test // void findById() throws EntityNotFoundException { // // Gastinformatie ophalen: // System.out.println("Informatie wordt opgehaald van guest met ID number 1...\n"); // Guest guest; // guest = guestController.findById(1).getBody(); // System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().toArray().length); // // assertEquals("Jane Doe", guestController.findById(3).getBody().getName()); // } // // @Test // void getGuestList() { // System.out.println("Gastenlijst wordt opgehaald..."); // for (Guest guest : guestList) { // System.out.println(guest.getId() + ". " + guest.getName() + ", " + guest.getCity() + ", " + guest.getBookings().toArray().length + " boekingen."); // } // List<Guest> newList = ((List<Guest>)guestList); // assertEquals(); // } // // @Test // void postGuest() { // try { // System.out.println("Registreer nieuwe gast: Jane Appleseed, geboren in 2002, afkomstig uit New York. \n"); // guestController.postGuest(new Guest("Jane Appleseed", "January 24th, 2002", "Jane@email.com", "0316 - 23454321", "AB1234DE", "Chicago Street", "New York")); // // System.out.print("Nieuwe gast<SUF> //// Guest guest = guestController.getGuest(4); //// System.out.println("Gastinformatie: \nNaam: " + guest.getName() + "\nGeboortedatum: " + guest.getBirthDate() + "\nStad: " + guest.getCity() + "\nBoekingen: " + guest.getBookings().length); //// System.out.println(guestController.getGuest(4).toString()); // // System.out.println("\nNieuwe gastenlijst:"); //// for (Guest guestIterator : guestController.getGuestList()) { //// System.out.println(guestIterator.getId() + ". " + guestIterator.getName() + ", " + guestIterator.getCity() + ", " + guestIterator.getBookings().length + " boekingen."); //// } //// assertEquals("Jane Appleseed", guestController.getGuestList().get(3).getName()); //// } catch (EntityNotFoundException e) { //// assertEquals(e.toString(),""); //// } //// } // // @Test // void putGuest() { // try { // System.out.println("Current guest (ID no. 2):"); // System.out.println(guestController.getGuest(2).toString()); // System.out.println("\nUpdating guest and requesting new information...\n"); // // guestController.putGuest(2,"Alice Smith", "February 20th, 1990", "asmith@email.com", "031-12345678", "", "Veemarkt 1, 5678 CD", ""); // System.out.println("\n" + guestController.getGuest(2).toString()); // // assertEquals(guestController.getGuest(2).getName(), "Alice Smith"); // // } catch (EntityNotFoundException e) { // assertEquals(e.toString(), ""); // } // } // // @Test // void deleteGuest() { // try { // System.out.println("Guest to be deleted (ID no. 3):"); // System.out.println(guestController.getGuest(3).toString()); // // System.out.println("\nDeleting guest... Requesting guest information again: "); // guestController.deleteGuest(3); // System.out.println(guestController.getGuest(3).toString()); // // } catch (EntityNotFoundException e) { // System.out.println(e); // assertEquals("com.molvenolakeresort.hotel.controller.EntityNotFoundException: Guest was not found for ID: 3",e.toString()); // } // // } }
False
1,798
17
2,277
20
2,133
16
2,275
20
2,632
21
false
false
false
false
false
true
1,906
104704_1
package inlezen; import data.Datalaag; import java.io.File; import java.io.FileNotFoundException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JOptionPane; import logica.Cijfers; import logica.Datum; import logica.Land; /** * * @author louisdhont */ public class InlezenCovidGevallen { private static final String BESTAND = "src/main/java/gegevens/daily-cases-covid-19.csv"; private static final ArrayList<String> LANDDATUM = new ArrayList<>(); private static final ArrayList<String> LANDCODES = new ArrayList<>(); private static final ArrayList<Integer> LANDAANTAL = new ArrayList<>(); Datalaag dataLaag; Cijfers cijfers; Datum datum; Land land; public void covidGevallenInlezen() throws SQLException, FileNotFoundException { dataLaag = new Datalaag("dhontlouis"); Scanner scanCode = null; Scanner scanDatum = null; Scanner scanAantal = null; try { scanDatum = new Scanner(new File(BESTAND)); scanCode = new Scanner(new File(BESTAND)); scanAantal = new Scanner(new File(BESTAND)); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "Bestand: " + BESTAND + " kon niet worden gevonden", "CSV error", JOptionPane.ERROR_MESSAGE); throw new FileNotFoundException("Kon het opgegeven bestand niet vinden"); } // Opslaan van eerste lijn met kolomnaam String lijstLandCode = scanCode.nextLine().split("\"")[0]; String lijstLandDaum = scanDatum.nextLine().split(",")[0]; String lijstIndexAantal = scanAantal.nextLine().split(",")[0]; while (scanDatum.hasNextLine()) { LANDDATUM.add(scanDatum.nextLine().split("\"")[1]); LANDCODES.add(scanCode.nextLine().split(",")[1]); LANDAANTAL.add(Integer.parseInt(scanAantal.nextLine().split(",")[4])); } for (int i = 0; i < LANDDATUM.size(); i++) { if (i + 1 != LANDDATUM.size()) { cijfers = new Cijfers(LANDAANTAL.get(i)); datum = new Datum(LANDDATUM.get(i)); land = new Land(LANDCODES.get(i)); dataLaag.invoegenCovidGevallen(land.getLandCode(), datum.omzettenDatum(datum.getDatum()), cijfers.getAantal()); } else { break; } } } }
Xevro/2019-java-corona-application
src/main/java/inlezen/InlezenCovidGevallen.java
790
// Opslaan van eerste lijn met kolomnaam
line_comment
nl
package inlezen; import data.Datalaag; import java.io.File; import java.io.FileNotFoundException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Scanner; import javax.swing.JOptionPane; import logica.Cijfers; import logica.Datum; import logica.Land; /** * * @author louisdhont */ public class InlezenCovidGevallen { private static final String BESTAND = "src/main/java/gegevens/daily-cases-covid-19.csv"; private static final ArrayList<String> LANDDATUM = new ArrayList<>(); private static final ArrayList<String> LANDCODES = new ArrayList<>(); private static final ArrayList<Integer> LANDAANTAL = new ArrayList<>(); Datalaag dataLaag; Cijfers cijfers; Datum datum; Land land; public void covidGevallenInlezen() throws SQLException, FileNotFoundException { dataLaag = new Datalaag("dhontlouis"); Scanner scanCode = null; Scanner scanDatum = null; Scanner scanAantal = null; try { scanDatum = new Scanner(new File(BESTAND)); scanCode = new Scanner(new File(BESTAND)); scanAantal = new Scanner(new File(BESTAND)); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(null, "Bestand: " + BESTAND + " kon niet worden gevonden", "CSV error", JOptionPane.ERROR_MESSAGE); throw new FileNotFoundException("Kon het opgegeven bestand niet vinden"); } // Opslaan van<SUF> String lijstLandCode = scanCode.nextLine().split("\"")[0]; String lijstLandDaum = scanDatum.nextLine().split(",")[0]; String lijstIndexAantal = scanAantal.nextLine().split(",")[0]; while (scanDatum.hasNextLine()) { LANDDATUM.add(scanDatum.nextLine().split("\"")[1]); LANDCODES.add(scanCode.nextLine().split(",")[1]); LANDAANTAL.add(Integer.parseInt(scanAantal.nextLine().split(",")[4])); } for (int i = 0; i < LANDDATUM.size(); i++) { if (i + 1 != LANDDATUM.size()) { cijfers = new Cijfers(LANDAANTAL.get(i)); datum = new Datum(LANDDATUM.get(i)); land = new Land(LANDCODES.get(i)); dataLaag.invoegenCovidGevallen(land.getLandCode(), datum.omzettenDatum(datum.getDatum()), cijfers.getAantal()); } else { break; } } } }
True
572
13
662
15
647
9
662
15
772
14
false
false
false
false
false
true
1,621
25170_3
package com.schriek.snuffelneus; import java.text.SimpleDateFormat; import java.util.List; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; /** * This shows how to create a simple activity with a map and a marker on the * map. * <p> * Notice how we deal with the possibility that the Google Play services APK is * not installed/enabled/updated on a user's device. */ public class MapActivity extends Fragment { /** * Note that this may be null if the Google Play services APK is not * available. */ private GoogleMap mMap; double lowLimit = 100.0; double highLimit = 600.0; private final String template = "hh:mm:ss dd-MM-yyyy"; //runs without a timer by reposting this handler at the end of the runnable Handler timerHandler = new Handler(); Runnable timerRunnable = new Runnable() { @Override public void run() { clearMap(); addAllMarkers(); //Log.i("MAP", "markers gezet"); timerHandler.postDelayed(this, 60000); } }; class MyInfoWindowAdapter implements InfoWindowAdapter{ private final View myContentsView; MyInfoWindowAdapter(LayoutInflater inflater){ myContentsView = inflater.inflate(R.layout.custom_info_contents, null); } @Override public View getInfoContents(Marker marker) { String[] list = marker.getSnippet().split(","); // Hieronder kunnen de verschillende snippets worden ingevuld. Denk aan een beschrijving van de waardes. String snippet = "Hier is de luchtkwaliteit best redelijk"; if( Double.parseDouble(list[0]) > highLimit) snippet = "De luchtkwaliteit is slecht!"; else if(Double.parseDouble(list[0]) < lowLimit) snippet = "De luchtkwaliteit is hier uitstekend!"; TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title)); tvTitle.setText("Meting van Snuffelneus:"); TextView datetime = ((TextView)myContentsView.findViewById(R.id.datetime)); datetime.setText("Gemeten op: "+new SimpleDateFormat(template).format(Double.parseDouble(list[3])* 1000.0)); TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet)); tvSnippet.setText(snippet); TextView sensor1 = ((TextView)myContentsView.findViewById(R.id.sensor1)); sensor1.setText("Fijnstof: " + list[0] + " ppb"); TextView sensor2 = ((TextView)myContentsView.findViewById(R.id.sensor2)); sensor2.setText("Temperatuur: " + list[1] + " \u00b0C"); TextView sensor3 = ((TextView)myContentsView.findViewById(R.id.sensor3)); sensor3.setText("Luchtvochtigheid: " + list[2] + " %"); return myContentsView; } @Override public View getInfoWindow(Marker marker) { // TODO Auto-generated method stub return null; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragment = inflater.inflate(R.layout.map_activity, container, false); mMap = ((SupportMapFragment) getFragmentManager().findFragmentById( R.id.map)).getMap(); setUpMap(); mMap.setInfoWindowAdapter(new MyInfoWindowAdapter(inflater)); addAllMarkers(); //deleteAllMarkers(); timerHandler.postDelayed(timerRunnable, 0); focusOnRotterdam(); return fragment; } /** * Het toevoegen van een marker op de kaart. De marker is klikbaar. Manier * om een marker toe te voegen: * * addMarker(new LatLng(11.84031,14.640971),"Schrieks crib", * "Stinkt hier! Niet te harden!" * ,BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED) * ); * * @param lPos * LatLng van de positie * @param sTitle * De titel, wanneer op de marker wordt geklikt * @param sSnippet * De beschrijving, wanneer op de marker wordt geklikt * @param iIcon * De Icon, dit moet een BitmapDescriptor zijn: * BitmapDescriptorFactory * .defaultMarker(BitmapDescriptorFactory.KLEUR) */ public void addMarker(LatLng lPos, String sTitle, String sSnippet, BitmapDescriptor iIcon) { mMap.addMarker(new MarkerOptions().title(sTitle) .snippet(sSnippet).position(lPos).icon(iIcon)); } public void addAllMarkers() { DataSource datasource = new DataSource(); datasource.open(); List<Record> values = datasource.getAllRecords(); int aantal = values.size(); //Log.i("Aantal markers:", aantal + " markers"); for (int i = 0; i < aantal; i++) { float bmf = BitmapDescriptorFactory.HUE_ORANGE; if( (values.get(i).getSensor1()) > highLimit) bmf = BitmapDescriptorFactory.HUE_RED; else if((values.get(i).getSensor1()) < lowLimit) bmf = BitmapDescriptorFactory.HUE_GREEN; addMarker(new LatLng(values.get(i).getLatitude(), values.get(i) .getLongitude()), "", values.get(i).getSensor1() + "," + values.get(i).getSensor2() + "," + values.get(i).getSensor3() + "," + values.get(i).getTimestamp(), BitmapDescriptorFactory .defaultMarker(bmf)); } } void deleteAllMarkers(){ DataSource datasource = new DataSource(); datasource.open(); List<Record> values = datasource.getAllRecords(); int aantal = values.size(); //Log.i("DELETE MAP", "DELETE ALL MARKERS " + aantal); for (int i = 0; i < aantal; i++) { datasource.deleteRecord(values.get(i)); } } public void clearMap(){ mMap.clear(); } /** * Inzoomen op Rotterdam */ public void focusOnRotterdam() { LatLng ROTTERDAM = new LatLng(51.924216, 4.481776); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ROTTERDAM, 12)); } /** * Inzoomen op de latitude en longitude * * @param lati * double van de latitude * @param longi * double van de longitude * @param zoom * integer van de zoomfactor */ public void focus(double lati, double longi, int zoom) { LatLng CENTER = new LatLng(lati, longi); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CENTER, zoom)); } private void setUpMap() { if (mMap != null) mMap.setMyLocationEnabled(true); } @Override public void onDestroyView() { super.onDestroyView(); clearMap(); timerHandler.removeCallbacks(timerRunnable); try { Fragment fragment = (getFragmentManager() .findFragmentById(R.id.map)); FragmentTransaction ft = getActivity().getSupportFragmentManager() .beginTransaction(); ft.remove(fragment); ft.commit(); } catch (Exception e) { e.printStackTrace(); } } // this method performs the task public void run() { clearMap(); addAllMarkers(); } }
Snuffelneus/Android-App
src/com/schriek/snuffelneus/MapActivity.java
2,491
//Log.i("MAP", "markers gezet");
line_comment
nl
package com.schriek.snuffelneus; import java.text.SimpleDateFormat; import java.util.List; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptor; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; /** * This shows how to create a simple activity with a map and a marker on the * map. * <p> * Notice how we deal with the possibility that the Google Play services APK is * not installed/enabled/updated on a user's device. */ public class MapActivity extends Fragment { /** * Note that this may be null if the Google Play services APK is not * available. */ private GoogleMap mMap; double lowLimit = 100.0; double highLimit = 600.0; private final String template = "hh:mm:ss dd-MM-yyyy"; //runs without a timer by reposting this handler at the end of the runnable Handler timerHandler = new Handler(); Runnable timerRunnable = new Runnable() { @Override public void run() { clearMap(); addAllMarkers(); //Log.i("MAP", "markers<SUF> timerHandler.postDelayed(this, 60000); } }; class MyInfoWindowAdapter implements InfoWindowAdapter{ private final View myContentsView; MyInfoWindowAdapter(LayoutInflater inflater){ myContentsView = inflater.inflate(R.layout.custom_info_contents, null); } @Override public View getInfoContents(Marker marker) { String[] list = marker.getSnippet().split(","); // Hieronder kunnen de verschillende snippets worden ingevuld. Denk aan een beschrijving van de waardes. String snippet = "Hier is de luchtkwaliteit best redelijk"; if( Double.parseDouble(list[0]) > highLimit) snippet = "De luchtkwaliteit is slecht!"; else if(Double.parseDouble(list[0]) < lowLimit) snippet = "De luchtkwaliteit is hier uitstekend!"; TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title)); tvTitle.setText("Meting van Snuffelneus:"); TextView datetime = ((TextView)myContentsView.findViewById(R.id.datetime)); datetime.setText("Gemeten op: "+new SimpleDateFormat(template).format(Double.parseDouble(list[3])* 1000.0)); TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet)); tvSnippet.setText(snippet); TextView sensor1 = ((TextView)myContentsView.findViewById(R.id.sensor1)); sensor1.setText("Fijnstof: " + list[0] + " ppb"); TextView sensor2 = ((TextView)myContentsView.findViewById(R.id.sensor2)); sensor2.setText("Temperatuur: " + list[1] + " \u00b0C"); TextView sensor3 = ((TextView)myContentsView.findViewById(R.id.sensor3)); sensor3.setText("Luchtvochtigheid: " + list[2] + " %"); return myContentsView; } @Override public View getInfoWindow(Marker marker) { // TODO Auto-generated method stub return null; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View fragment = inflater.inflate(R.layout.map_activity, container, false); mMap = ((SupportMapFragment) getFragmentManager().findFragmentById( R.id.map)).getMap(); setUpMap(); mMap.setInfoWindowAdapter(new MyInfoWindowAdapter(inflater)); addAllMarkers(); //deleteAllMarkers(); timerHandler.postDelayed(timerRunnable, 0); focusOnRotterdam(); return fragment; } /** * Het toevoegen van een marker op de kaart. De marker is klikbaar. Manier * om een marker toe te voegen: * * addMarker(new LatLng(11.84031,14.640971),"Schrieks crib", * "Stinkt hier! Niet te harden!" * ,BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED) * ); * * @param lPos * LatLng van de positie * @param sTitle * De titel, wanneer op de marker wordt geklikt * @param sSnippet * De beschrijving, wanneer op de marker wordt geklikt * @param iIcon * De Icon, dit moet een BitmapDescriptor zijn: * BitmapDescriptorFactory * .defaultMarker(BitmapDescriptorFactory.KLEUR) */ public void addMarker(LatLng lPos, String sTitle, String sSnippet, BitmapDescriptor iIcon) { mMap.addMarker(new MarkerOptions().title(sTitle) .snippet(sSnippet).position(lPos).icon(iIcon)); } public void addAllMarkers() { DataSource datasource = new DataSource(); datasource.open(); List<Record> values = datasource.getAllRecords(); int aantal = values.size(); //Log.i("Aantal markers:", aantal + " markers"); for (int i = 0; i < aantal; i++) { float bmf = BitmapDescriptorFactory.HUE_ORANGE; if( (values.get(i).getSensor1()) > highLimit) bmf = BitmapDescriptorFactory.HUE_RED; else if((values.get(i).getSensor1()) < lowLimit) bmf = BitmapDescriptorFactory.HUE_GREEN; addMarker(new LatLng(values.get(i).getLatitude(), values.get(i) .getLongitude()), "", values.get(i).getSensor1() + "," + values.get(i).getSensor2() + "," + values.get(i).getSensor3() + "," + values.get(i).getTimestamp(), BitmapDescriptorFactory .defaultMarker(bmf)); } } void deleteAllMarkers(){ DataSource datasource = new DataSource(); datasource.open(); List<Record> values = datasource.getAllRecords(); int aantal = values.size(); //Log.i("DELETE MAP", "DELETE ALL MARKERS " + aantal); for (int i = 0; i < aantal; i++) { datasource.deleteRecord(values.get(i)); } } public void clearMap(){ mMap.clear(); } /** * Inzoomen op Rotterdam */ public void focusOnRotterdam() { LatLng ROTTERDAM = new LatLng(51.924216, 4.481776); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ROTTERDAM, 12)); } /** * Inzoomen op de latitude en longitude * * @param lati * double van de latitude * @param longi * double van de longitude * @param zoom * integer van de zoomfactor */ public void focus(double lati, double longi, int zoom) { LatLng CENTER = new LatLng(lati, longi); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(CENTER, zoom)); } private void setUpMap() { if (mMap != null) mMap.setMyLocationEnabled(true); } @Override public void onDestroyView() { super.onDestroyView(); clearMap(); timerHandler.removeCallbacks(timerRunnable); try { Fragment fragment = (getFragmentManager() .findFragmentById(R.id.map)); FragmentTransaction ft = getActivity().getSupportFragmentManager() .beginTransaction(); ft.remove(fragment); ft.commit(); } catch (Exception e) { e.printStackTrace(); } } // this method performs the task public void run() { clearMap(); addAllMarkers(); } }
False
1,851
11
2,193
12
2,183
11
2,193
12
2,588
13
false
false
false
false
false
true
4,281
172864_1
package hpi.rcstream; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by magnus on 19.04.16. */ @JsonIgnoreProperties(ignoreUnknown = true) public class RCFeedEntry { public String comment; // "[[:File:Nl-geheugenplaatsjes.ogg]] added to category" public String wiki; // "commonswiki" public String server_name; // "commons.wikimedia.org" public String title; // "Category:Male Dutch pronunciation" public long timestamp; // 1461069130 public String server_script_path; // "/w" public int namespace; // 14 public String server_url; // "https://commons.wikimedia.org" public String user; // "RileyBot" public Boolean bot; // true public String type; // "categorize" public long id; // 215733984 public Object length; @Override public String toString() { return type.toUpperCase() + " " + id + ": " + title + " " + user + (bot?"(bot) ":" "); } }
semmul2016group4/RCStream
src/main/java/hpi/rcstream/RCFeedEntry.java
301
// "[[:File:Nl-geheugenplaatsjes.ogg]] added to category"
line_comment
nl
package hpi.rcstream; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * Created by magnus on 19.04.16. */ @JsonIgnoreProperties(ignoreUnknown = true) public class RCFeedEntry { public String comment; // "[[:File:Nl-geheugenplaatsjes.ogg]] added<SUF> public String wiki; // "commonswiki" public String server_name; // "commons.wikimedia.org" public String title; // "Category:Male Dutch pronunciation" public long timestamp; // 1461069130 public String server_script_path; // "/w" public int namespace; // 14 public String server_url; // "https://commons.wikimedia.org" public String user; // "RileyBot" public Boolean bot; // true public String type; // "categorize" public long id; // 215733984 public Object length; @Override public String toString() { return type.toUpperCase() + " " + id + ": " + title + " " + user + (bot?"(bot) ":" "); } }
False
255
19
282
22
284
18
282
22
312
22
false
false
false
false
false
true
3,210
43948_2
package be.kuleuven.dbproject.controller; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class BeheerAttachesController { @FXML private TableView tblTips; public void initialize() { initTable(); tblTips.setOnMouseClicked(e -> { if(e.getClickCount() == 2 && tblTips.getSelectionModel().getSelectedItem() != null) { var selectedRow = (List<String>) tblTips.getSelectionModel().getSelectedItem(); runResource(selectedRow.get(2)); } }); } private boolean isWindows() { return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0; } private boolean isMac() { return System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0; } private void runResource(String resource) { try { // TODO dit moet niet van de resource list komen maar van een DB. var data = this.getClass().getClassLoader().getResourceAsStream(resource).readAllBytes(); var path = Paths.get("out-" + resource); Files.write(path, data); Thread.sleep(1000); var process = new ProcessBuilder(); if(isWindows()) { process.command("cmd.exe", "/c", "start " + path.toRealPath().toString()); } else if(isMac()) { process.command("open", path.toRealPath().toString()); } else { throw new RuntimeException("Ik ken uw OS niet jong"); } process.start(); } catch (Exception e) { throw new RuntimeException("resource " + resource + " kan niet ingelezen worden", e); } } private void initTable() { tblTips.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); tblTips.getColumns().clear(); // TODO zijn dit de juiste kolommen? int colIndex = 0; for(var colName : new String[]{"Attach beschrijving", "Grootte in KB", "Handle"}) { TableColumn<ObservableList<String>, String> col = new TableColumn<>(colName); final int finalColIndex = colIndex; col.setCellValueFactory(f -> new ReadOnlyObjectWrapper<>(f.getValue().get(finalColIndex))); tblTips.getColumns().add(col); colIndex++; } // TODO verwijderen en "echte data" toevoegen! tblTips.getItems().add(FXCollections.observableArrayList("Mooie muziek om bij te gamen", "240", "attach-dubbelklik-op-mij.mp3")); } }
jeroenconinx/databases-course
src/main/java/be/kuleuven/dbproject/controller/BeheerAttachesController.java
813
// TODO verwijderen en "echte data" toevoegen!
line_comment
nl
package be.kuleuven.dbproject.controller; import javafx.beans.property.ReadOnlyObjectWrapper; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXML; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class BeheerAttachesController { @FXML private TableView tblTips; public void initialize() { initTable(); tblTips.setOnMouseClicked(e -> { if(e.getClickCount() == 2 && tblTips.getSelectionModel().getSelectedItem() != null) { var selectedRow = (List<String>) tblTips.getSelectionModel().getSelectedItem(); runResource(selectedRow.get(2)); } }); } private boolean isWindows() { return System.getProperty("os.name").toLowerCase().indexOf("win") >= 0; } private boolean isMac() { return System.getProperty("os.name").toLowerCase().indexOf("mac") >= 0; } private void runResource(String resource) { try { // TODO dit moet niet van de resource list komen maar van een DB. var data = this.getClass().getClassLoader().getResourceAsStream(resource).readAllBytes(); var path = Paths.get("out-" + resource); Files.write(path, data); Thread.sleep(1000); var process = new ProcessBuilder(); if(isWindows()) { process.command("cmd.exe", "/c", "start " + path.toRealPath().toString()); } else if(isMac()) { process.command("open", path.toRealPath().toString()); } else { throw new RuntimeException("Ik ken uw OS niet jong"); } process.start(); } catch (Exception e) { throw new RuntimeException("resource " + resource + " kan niet ingelezen worden", e); } } private void initTable() { tblTips.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); tblTips.getColumns().clear(); // TODO zijn dit de juiste kolommen? int colIndex = 0; for(var colName : new String[]{"Attach beschrijving", "Grootte in KB", "Handle"}) { TableColumn<ObservableList<String>, String> col = new TableColumn<>(colName); final int finalColIndex = colIndex; col.setCellValueFactory(f -> new ReadOnlyObjectWrapper<>(f.getValue().get(finalColIndex))); tblTips.getColumns().add(col); colIndex++; } // TODO verwijderen<SUF> tblTips.getItems().add(FXCollections.observableArrayList("Mooie muziek om bij te gamen", "240", "attach-dubbelklik-op-mij.mp3")); } }
True
597
16
695
17
717
12
695
17
806
16
false
false
false
false
false
true
2,270
10269_0
package com.aquima.plugin.dossier.util; import com.aquima.interactions.foundation.logging.LogFactory; import com.aquima.interactions.foundation.logging.Logger; /** * Deze class biedt een aantal methoden aan die binnen de applicatie gebruikt kunnen worden om Throwables en Exceptions * expliciet te negeren. Door deze class te gebruiken, kan op een later tijdstip extra functionaliteit ingebouwd worden * om inzicht te verkrijgen in het 'onderwater' gedrag van de applicatie. Een reden om dit te willen is bijvoorbeeld * performanceverbetering. Het throwen van excepties kost namelijk relatief veel tijd. Als er in een gedeelte van de * code excessief gebruik gemaakt wordt van het exceptiemechanisme, dan zal dit slechter performen dan wanneer er voor * gezorgd wordt dat deze excepties niet optreden. * * @author <a href="mailto:c.de.meijer@everest.nl">C. de Meijer</a> */ public final class ExceptionHandler { private static final Logger LOG = LogFactory.getLogger(ExceptionHandler.class); public static final boolean LOGGING_ENABLED = false; private ExceptionHandler() {} /** * Negeer de gespecificeerde Exception. Indien de LOGGING_ENABLED setting ge-activeerd is, dan zal een melding van het * feit dat deze Exception genegeerd is, gemeld worden in de log van de applicatie. * * @param e Een instantie van een Exception die genegeerd moet worden. */ public static void ignore(final Exception e) { if (!LOGGING_ENABLED) { return; } if (LOG.isDebugEnabled()) { LOG.debug("An exception has been ignored by the application.", e); } } /** * Negeer de gespecificeerde Exception. Indien de LOGGING_ENABLED setting ge-activeerd is, dan zal een melding van het * feit dat deze Exception genegeerd is, gemeld worden in de log van de applicatie. * * @param e Een instantie van een Exception die genegeerd moet worden. * @param warn Boolean om aan te geven dat dit serieus is en er hoe dan ook een warning gelogd moet worden. * Bijvoorbeeld als er in commentaar staat dat 'dit nooit voor kan komen'. */ public static void ignore(final Exception e, final boolean warn) { if (!warn && !LOGGING_ENABLED) { return; } if (warn) { LOG.warning("An exception has been ignored by the application.", e); } else { LOG.debug("An exception has been ignored by the application.", e); } } }
blueriq/blueriq-plugin-dossier-sql-store
src/main/java/com/aquima/plugin/dossier/util/ExceptionHandler.java
713
/** * Deze class biedt een aantal methoden aan die binnen de applicatie gebruikt kunnen worden om Throwables en Exceptions * expliciet te negeren. Door deze class te gebruiken, kan op een later tijdstip extra functionaliteit ingebouwd worden * om inzicht te verkrijgen in het 'onderwater' gedrag van de applicatie. Een reden om dit te willen is bijvoorbeeld * performanceverbetering. Het throwen van excepties kost namelijk relatief veel tijd. Als er in een gedeelte van de * code excessief gebruik gemaakt wordt van het exceptiemechanisme, dan zal dit slechter performen dan wanneer er voor * gezorgd wordt dat deze excepties niet optreden. * * @author <a href="mailto:c.de.meijer@everest.nl">C. de Meijer</a> */
block_comment
nl
package com.aquima.plugin.dossier.util; import com.aquima.interactions.foundation.logging.LogFactory; import com.aquima.interactions.foundation.logging.Logger; /** * Deze class biedt<SUF>*/ public final class ExceptionHandler { private static final Logger LOG = LogFactory.getLogger(ExceptionHandler.class); public static final boolean LOGGING_ENABLED = false; private ExceptionHandler() {} /** * Negeer de gespecificeerde Exception. Indien de LOGGING_ENABLED setting ge-activeerd is, dan zal een melding van het * feit dat deze Exception genegeerd is, gemeld worden in de log van de applicatie. * * @param e Een instantie van een Exception die genegeerd moet worden. */ public static void ignore(final Exception e) { if (!LOGGING_ENABLED) { return; } if (LOG.isDebugEnabled()) { LOG.debug("An exception has been ignored by the application.", e); } } /** * Negeer de gespecificeerde Exception. Indien de LOGGING_ENABLED setting ge-activeerd is, dan zal een melding van het * feit dat deze Exception genegeerd is, gemeld worden in de log van de applicatie. * * @param e Een instantie van een Exception die genegeerd moet worden. * @param warn Boolean om aan te geven dat dit serieus is en er hoe dan ook een warning gelogd moet worden. * Bijvoorbeeld als er in commentaar staat dat 'dit nooit voor kan komen'. */ public static void ignore(final Exception e, final boolean warn) { if (!warn && !LOGGING_ENABLED) { return; } if (warn) { LOG.warning("An exception has been ignored by the application.", e); } else { LOG.debug("An exception has been ignored by the application.", e); } } }
True
598
194
679
227
635
182
679
227
714
210
false
true
false
true
false
false
344
42137_0
package com.jie.befamiliewijzer.config; /* CORS (Cross Origin Resource Sharing is een instelling die zorgt dat de frontend en de backend met elkaar kunnen communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080). De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten. In deze applictie staat alsnog wel boven elke klasse ter demonstratie. Vergeet niet om in de security config ook de ".cors()" optie aan te zetten. */ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class GlobalCorsConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"); } }; } }
ConradJie/be-familie-wijzer
src/main/java/com/jie/befamiliewijzer/config/GlobalCorsConfiguration.java
335
/* CORS (Cross Origin Resource Sharing is een instelling die zorgt dat de frontend en de backend met elkaar kunnen communiceren ondanks dat ze op verschillende poorten opereren (b.v. localhost:3000 en localhost:8080). De globale cors configuratie zorgt dat je niet boven elke klasse @CrossOrigin hoeft te zetten. In deze applictie staat alsnog wel boven elke klasse ter demonstratie. Vergeet niet om in de security config ook de ".cors()" optie aan te zetten. */
block_comment
nl
package com.jie.befamiliewijzer.config; /* CORS (Cross Origin<SUF>*/ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class GlobalCorsConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"); } }; } }
False
262
125
314
146
287
113
314
146
334
139
false
false
false
false
false
true
1,914
10425_5
/*_x000D_ * To change this license header, choose License Headers in Project Properties._x000D_ * To change this template file, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ package dominion;_x000D_ _x000D_ import dominion.Database.DatabaseService;_x000D_ import dominion.Models.*;_x000D_ _x000D_ public class Speler {_x000D_ private String name;_x000D_ private int playerID;_x000D_ private Deck drawDeck;_x000D_ private Deck handDeck;_x000D_ private Deck discardDeck;_x000D_ private int actions;_x000D_ private int buys;_x000D_ private int coins;_x000D_ private int victoryPoints;_x000D_ private boolean effected;_x000D_ _x000D_ //constructor_x000D_ public Speler(String name, int ID, DatabaseService dbs){_x000D_ this.name = name;_x000D_ this.playerID = ID;_x000D_ newDecks(dbs);_x000D_ // initRound();_x000D_ }_x000D_ _x000D_ private void newDecks(DatabaseService dbs){_x000D_ drawDeck = new Deck(true, dbs);_x000D_ handDeck = new Deck(false, dbs);_x000D_ discardDeck = new Deck(false, dbs);_x000D_ }_x000D_ _x000D_ public void initRound(){_x000D_ actions = 1;_x000D_ buys = 1;_x000D_ coins = 0;_x000D_ }_x000D_ _x000D_ public void setEffected(boolean b){_x000D_ effected = b;_x000D_ }_x000D_ _x000D_ //actie verminderen per actiekaart gespeeld_x000D_ public void actionDecrement(int actionDecrease){_x000D_ this.actions -= actionDecrease;_x000D_ }_x000D_ _x000D_ //naargelang de kaart actie terug vermeerderen_x000D_ public void actionIncrement(int actionIncrease){_x000D_ this.actions += actionIncrease;_x000D_ }_x000D_ _x000D_ //na aankoop kaart buy verminderen_x000D_ public void buysDecrement(int buysDecrease){_x000D_ this.buys -= buysDecrease;_x000D_ }_x000D_ _x000D_ public void buysIncrement(int buysIncrease){_x000D_ this.buys += buysIncrease;_x000D_ }_x000D_ _x000D_ //na aankoop muntkaarten coins verhogen_x000D_ public void coinsIncrement(int coinsIncrease){_x000D_ this.coins += coinsIncrease;_x000D_ }_x000D_ _x000D_ //na aankoop muntkaarten coins verlagen_x000D_ public void coinsDecrement(int coinsDecrease){_x000D_ this.coins -= coinsDecrease;_x000D_ }_x000D_ _x000D_ public void setVictoryPoints(int amount){_x000D_ this.victoryPoints = amount;_x000D_ }_x000D_ _x000D_ public boolean isEffected() {_x000D_ return effected;_x000D_ }_x000D_ public String getPlayerName() {_x000D_ return name;_x000D_ }_x000D_ public int getPlayerID() {_x000D_ return playerID;_x000D_ }_x000D_ public int getActions() {_x000D_ return actions;_x000D_ }_x000D_ public int getBuys() {_x000D_ return buys;_x000D_ }_x000D_ public int getCoins() {_x000D_ return coins;_x000D_ }_x000D_ public int getVictoryPoints(){_x000D_ return victoryPoints;_x000D_ }_x000D_ public Deck getHandDeck(){_x000D_ return handDeck;_x000D_ }_x000D_ public Deck getDiscardDeck(){_x000D_ return discardDeck;_x000D_ }_x000D_ public Deck getDrawDeck(){_x000D_ return drawDeck;_x000D_ }_x000D_ _x000D_ }
YanniD/Dominion
Dominion/src/dominion/Speler.java
825
//na aankoop muntkaarten coins verlagen_x000D_
line_comment
nl
/*_x000D_ * To change this license header, choose License Headers in Project Properties._x000D_ * To change this template file, choose Tools | Templates_x000D_ * and open the template in the editor._x000D_ */_x000D_ package dominion;_x000D_ _x000D_ import dominion.Database.DatabaseService;_x000D_ import dominion.Models.*;_x000D_ _x000D_ public class Speler {_x000D_ private String name;_x000D_ private int playerID;_x000D_ private Deck drawDeck;_x000D_ private Deck handDeck;_x000D_ private Deck discardDeck;_x000D_ private int actions;_x000D_ private int buys;_x000D_ private int coins;_x000D_ private int victoryPoints;_x000D_ private boolean effected;_x000D_ _x000D_ //constructor_x000D_ public Speler(String name, int ID, DatabaseService dbs){_x000D_ this.name = name;_x000D_ this.playerID = ID;_x000D_ newDecks(dbs);_x000D_ // initRound();_x000D_ }_x000D_ _x000D_ private void newDecks(DatabaseService dbs){_x000D_ drawDeck = new Deck(true, dbs);_x000D_ handDeck = new Deck(false, dbs);_x000D_ discardDeck = new Deck(false, dbs);_x000D_ }_x000D_ _x000D_ public void initRound(){_x000D_ actions = 1;_x000D_ buys = 1;_x000D_ coins = 0;_x000D_ }_x000D_ _x000D_ public void setEffected(boolean b){_x000D_ effected = b;_x000D_ }_x000D_ _x000D_ //actie verminderen per actiekaart gespeeld_x000D_ public void actionDecrement(int actionDecrease){_x000D_ this.actions -= actionDecrease;_x000D_ }_x000D_ _x000D_ //naargelang de kaart actie terug vermeerderen_x000D_ public void actionIncrement(int actionIncrease){_x000D_ this.actions += actionIncrease;_x000D_ }_x000D_ _x000D_ //na aankoop kaart buy verminderen_x000D_ public void buysDecrement(int buysDecrease){_x000D_ this.buys -= buysDecrease;_x000D_ }_x000D_ _x000D_ public void buysIncrement(int buysIncrease){_x000D_ this.buys += buysIncrease;_x000D_ }_x000D_ _x000D_ //na aankoop muntkaarten coins verhogen_x000D_ public void coinsIncrement(int coinsIncrease){_x000D_ this.coins += coinsIncrease;_x000D_ }_x000D_ _x000D_ //na aankoop<SUF> public void coinsDecrement(int coinsDecrease){_x000D_ this.coins -= coinsDecrease;_x000D_ }_x000D_ _x000D_ public void setVictoryPoints(int amount){_x000D_ this.victoryPoints = amount;_x000D_ }_x000D_ _x000D_ public boolean isEffected() {_x000D_ return effected;_x000D_ }_x000D_ public String getPlayerName() {_x000D_ return name;_x000D_ }_x000D_ public int getPlayerID() {_x000D_ return playerID;_x000D_ }_x000D_ public int getActions() {_x000D_ return actions;_x000D_ }_x000D_ public int getBuys() {_x000D_ return buys;_x000D_ }_x000D_ public int getCoins() {_x000D_ return coins;_x000D_ }_x000D_ public int getVictoryPoints(){_x000D_ return victoryPoints;_x000D_ }_x000D_ public Deck getHandDeck(){_x000D_ return handDeck;_x000D_ }_x000D_ public Deck getDiscardDeck(){_x000D_ return discardDeck;_x000D_ }_x000D_ public Deck getDrawDeck(){_x000D_ return drawDeck;_x000D_ }_x000D_ _x000D_ }
True
1,357
18
1,387
20
1,445
17
1,387
20
1,594
20
false
false
false
false
false
true
4,823
93771_7
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package sun.security.provider; import java.io.IOException; import java.security.AccessController; import java.security.DrbgParameters; import java.security.PrivilegedAction; import java.security.SecureRandomParameters; import java.security.SecureRandomSpi; import java.security.Security; import java.util.Locale; import static java.security.DrbgParameters.Capability.*; /** * Implement the "SecureRandom.DRBG" algorithm. * * About the default "securerandom.drbg.config" value: * * The default value in java.security is set to "". This is because * the default values of different aspects are dependent (For example, * strength depends on algorithm) and if we write a full string there * it will be difficult to modify one and keep all others legal. * * When changing default values, touch all places including: * * 1. comments of the security property in java.security * 2. Default mech, cap, usedf set in this class * 3. Default algorithm set in final implementation of each mech * 4. Default strength set in AbstractDrbg, but the effective * value can be smaller if an algorithm does not support it. * * The default value is also mentioned in the @implNote part of * {@link DrbgParameters} class. */ public final class DRBG extends SecureRandomSpi { private static final String PROP_NAME = "securerandom.drbg.config"; private static final long serialVersionUID = 9L; private transient AbstractDrbg impl; /** * @serial */ private final MoreDrbgParameters mdp; public DRBG(SecureRandomParameters params) { // All parameters at unset status (null or -1). // Configurable with the "securerandom.drbg.config" security property String mech = null; Boolean usedf = null; String algorithm = null; // Default instantiate parameters also configurable with // "securerandom.drbg.config", and can be changed with params // in getInstance("drbg", params) int strength = -1; DrbgParameters.Capability cap = null; byte[] ps = null; // Not configurable with public interfaces, but is a part of // MoreDrbgParameters EntropySource es = null; byte[] nonce = null; // Can be configured with a security property String config = AccessController.doPrivileged((PrivilegedAction<String>) () -> Security.getProperty(PROP_NAME)); if (config != null && !config.isEmpty()) { for (String part : config.split(",")) { part = part.trim(); switch (part.toLowerCase(Locale.ROOT)) { case "": throw new IllegalArgumentException( "aspect in " + PROP_NAME + " cannot be empty"); case "pr_and_reseed": checkTwice(cap != null, "capability"); cap = PR_AND_RESEED; break; case "reseed_only": checkTwice(cap != null, "capability"); cap = RESEED_ONLY; break; case "none": checkTwice(cap != null, "capability"); cap = NONE; break; case "hash_drbg": case "hmac_drbg": case "ctr_drbg": checkTwice(mech != null, "mechanism name"); mech = part; break; case "no_df": checkTwice(usedf != null, "usedf flag"); usedf = false; break; case "use_df": checkTwice(usedf != null, "usedf flag"); usedf = true; break; default: // For all other parts of the property, it is // either an algorithm name or a strength try { int tmp = Integer.parseInt(part); if (tmp < 0) { throw new IllegalArgumentException( "strength in " + PROP_NAME + " cannot be negative: " + part); } checkTwice(strength >= 0, "strength"); strength = tmp; } catch (NumberFormatException e) { checkTwice(algorithm != null, "algorithm name"); algorithm = part; } } } } // Can be updated by params if (params != null) { // MoreDrbgParameters is used for testing. if (params instanceof MoreDrbgParameters) { MoreDrbgParameters m = (MoreDrbgParameters) params; params = DrbgParameters.instantiation(m.strength, m.capability, m.personalizationString); // No need to check null for es and nonce, they are still null es = m.es; nonce = m.nonce; if (m.mech != null) { mech = m.mech; } if (m.algorithm != null) { algorithm = m.algorithm; } usedf = m.usedf; } if (params instanceof DrbgParameters.Instantiation) { DrbgParameters.Instantiation dp = (DrbgParameters.Instantiation) params; // ps is still null by now ps = dp.getPersonalizationString(); int tmp = dp.getStrength(); if (tmp != -1) { strength = tmp; } cap = dp.getCapability(); } else { throw new IllegalArgumentException("Unsupported params: " + params.getClass()); } } // Hardcoded defaults. // Remember to sync with "securerandom.drbg.config" in java.security. if (cap == null) { cap = NONE; } if (mech == null) { mech = "Hash_DRBG"; } if (usedf == null) { usedf = true; } mdp = new MoreDrbgParameters( es, mech, algorithm, nonce, usedf, DrbgParameters.instantiation(strength, cap, ps)); createImpl(); } private void createImpl() { switch (mdp.mech.toLowerCase(Locale.ROOT)) { case "hash_drbg": impl = new HashDrbg(mdp); break; case "hmac_drbg": impl = new HmacDrbg(mdp); break; case "ctr_drbg": impl = new CtrDrbg(mdp); break; default: throw new IllegalArgumentException("Unsupported mech: " + mdp.mech); } } @Override protected void engineSetSeed(byte[] seed) { impl.engineSetSeed(seed); } @Override protected void engineNextBytes(byte[] bytes) { impl.engineNextBytes(bytes); } @Override protected byte[] engineGenerateSeed(int numBytes) { return impl.engineGenerateSeed(numBytes); } @Override protected void engineNextBytes( byte[] bytes, SecureRandomParameters params) { impl.engineNextBytes(bytes, params); } @Override protected void engineReseed(SecureRandomParameters params) { impl.engineReseed(params); } @Override protected SecureRandomParameters engineGetParameters() { return impl.engineGetParameters(); } @Override public String toString() { return impl.toString(); } /** * Ensures an aspect is not set more than once. * * @param flag true if set more than once * @param name the name of aspect shown in IAE * @throws IllegalArgumentException if it happens */ private static void checkTwice(boolean flag, String name) { if (flag) { throw new IllegalArgumentException(name + " cannot be provided more than once in " + PROP_NAME); } } private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if (mdp.mech == null) { throw new IllegalArgumentException("Input data is corrupted"); } createImpl(); } }
zxiaofan/JDK
jdk-11.0.2/src/java.base/sun/security/provider/DRBG.java
2,314
// in getInstance("drbg", params)
line_comment
nl
/* * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package sun.security.provider; import java.io.IOException; import java.security.AccessController; import java.security.DrbgParameters; import java.security.PrivilegedAction; import java.security.SecureRandomParameters; import java.security.SecureRandomSpi; import java.security.Security; import java.util.Locale; import static java.security.DrbgParameters.Capability.*; /** * Implement the "SecureRandom.DRBG" algorithm. * * About the default "securerandom.drbg.config" value: * * The default value in java.security is set to "". This is because * the default values of different aspects are dependent (For example, * strength depends on algorithm) and if we write a full string there * it will be difficult to modify one and keep all others legal. * * When changing default values, touch all places including: * * 1. comments of the security property in java.security * 2. Default mech, cap, usedf set in this class * 3. Default algorithm set in final implementation of each mech * 4. Default strength set in AbstractDrbg, but the effective * value can be smaller if an algorithm does not support it. * * The default value is also mentioned in the @implNote part of * {@link DrbgParameters} class. */ public final class DRBG extends SecureRandomSpi { private static final String PROP_NAME = "securerandom.drbg.config"; private static final long serialVersionUID = 9L; private transient AbstractDrbg impl; /** * @serial */ private final MoreDrbgParameters mdp; public DRBG(SecureRandomParameters params) { // All parameters at unset status (null or -1). // Configurable with the "securerandom.drbg.config" security property String mech = null; Boolean usedf = null; String algorithm = null; // Default instantiate parameters also configurable with // "securerandom.drbg.config", and can be changed with params // in getInstance("drbg",<SUF> int strength = -1; DrbgParameters.Capability cap = null; byte[] ps = null; // Not configurable with public interfaces, but is a part of // MoreDrbgParameters EntropySource es = null; byte[] nonce = null; // Can be configured with a security property String config = AccessController.doPrivileged((PrivilegedAction<String>) () -> Security.getProperty(PROP_NAME)); if (config != null && !config.isEmpty()) { for (String part : config.split(",")) { part = part.trim(); switch (part.toLowerCase(Locale.ROOT)) { case "": throw new IllegalArgumentException( "aspect in " + PROP_NAME + " cannot be empty"); case "pr_and_reseed": checkTwice(cap != null, "capability"); cap = PR_AND_RESEED; break; case "reseed_only": checkTwice(cap != null, "capability"); cap = RESEED_ONLY; break; case "none": checkTwice(cap != null, "capability"); cap = NONE; break; case "hash_drbg": case "hmac_drbg": case "ctr_drbg": checkTwice(mech != null, "mechanism name"); mech = part; break; case "no_df": checkTwice(usedf != null, "usedf flag"); usedf = false; break; case "use_df": checkTwice(usedf != null, "usedf flag"); usedf = true; break; default: // For all other parts of the property, it is // either an algorithm name or a strength try { int tmp = Integer.parseInt(part); if (tmp < 0) { throw new IllegalArgumentException( "strength in " + PROP_NAME + " cannot be negative: " + part); } checkTwice(strength >= 0, "strength"); strength = tmp; } catch (NumberFormatException e) { checkTwice(algorithm != null, "algorithm name"); algorithm = part; } } } } // Can be updated by params if (params != null) { // MoreDrbgParameters is used for testing. if (params instanceof MoreDrbgParameters) { MoreDrbgParameters m = (MoreDrbgParameters) params; params = DrbgParameters.instantiation(m.strength, m.capability, m.personalizationString); // No need to check null for es and nonce, they are still null es = m.es; nonce = m.nonce; if (m.mech != null) { mech = m.mech; } if (m.algorithm != null) { algorithm = m.algorithm; } usedf = m.usedf; } if (params instanceof DrbgParameters.Instantiation) { DrbgParameters.Instantiation dp = (DrbgParameters.Instantiation) params; // ps is still null by now ps = dp.getPersonalizationString(); int tmp = dp.getStrength(); if (tmp != -1) { strength = tmp; } cap = dp.getCapability(); } else { throw new IllegalArgumentException("Unsupported params: " + params.getClass()); } } // Hardcoded defaults. // Remember to sync with "securerandom.drbg.config" in java.security. if (cap == null) { cap = NONE; } if (mech == null) { mech = "Hash_DRBG"; } if (usedf == null) { usedf = true; } mdp = new MoreDrbgParameters( es, mech, algorithm, nonce, usedf, DrbgParameters.instantiation(strength, cap, ps)); createImpl(); } private void createImpl() { switch (mdp.mech.toLowerCase(Locale.ROOT)) { case "hash_drbg": impl = new HashDrbg(mdp); break; case "hmac_drbg": impl = new HmacDrbg(mdp); break; case "ctr_drbg": impl = new CtrDrbg(mdp); break; default: throw new IllegalArgumentException("Unsupported mech: " + mdp.mech); } } @Override protected void engineSetSeed(byte[] seed) { impl.engineSetSeed(seed); } @Override protected void engineNextBytes(byte[] bytes) { impl.engineNextBytes(bytes); } @Override protected byte[] engineGenerateSeed(int numBytes) { return impl.engineGenerateSeed(numBytes); } @Override protected void engineNextBytes( byte[] bytes, SecureRandomParameters params) { impl.engineNextBytes(bytes, params); } @Override protected void engineReseed(SecureRandomParameters params) { impl.engineReseed(params); } @Override protected SecureRandomParameters engineGetParameters() { return impl.engineGetParameters(); } @Override public String toString() { return impl.toString(); } /** * Ensures an aspect is not set more than once. * * @param flag true if set more than once * @param name the name of aspect shown in IAE * @throws IllegalArgumentException if it happens */ private static void checkTwice(boolean flag, String name) { if (flag) { throw new IllegalArgumentException(name + " cannot be provided more than once in " + PROP_NAME); } } private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); if (mdp.mech == null) { throw new IllegalArgumentException("Input data is corrupted"); } createImpl(); } }
False
1,774
9
1,928
9
2,069
9
1,928
9
2,338
11
false
false
false
false
false
true
3,306
172176_19
package org.tools.hqlbuilder.client; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections4.CollectionUtils; import org.jhaws.common.lang.StringUtils; import org.jhaws.common.web.resteasy.RestResource; import org.slf4j.LoggerFactory; import org.swingeasy.ObjectWrapper; import org.tools.hqlbuilder.common.CommonUtilsAdd; import org.tools.hqlbuilder.common.DelegatingHqlService; import org.tools.hqlbuilder.common.HqlService; /** * @author Jurgen */ public class HqlServiceClientImpl extends DelegatingHqlService implements HqlServiceClient { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(HqlServiceClientImpl.class); public static final String NEWLINE = "\n"; private HqlService hqlService; private String serviceUrl; private String[] keywordGroups = { "cross join", "right outer join", "left outer join", "inner join", "from", "where", "having", "and", "or", "group by", "order by", "select", "," }; /** when cleaning up HQL: replace key by value */ private Map<String, String> hqlReplacers = new HashMap<>(); public HqlService getHqlService() { return hqlService; } public void setHqlService(HqlService hqlService) { this.hqlService = hqlService; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#getServiceUrl() */ @Override public String getServiceUrl() { return this.serviceUrl; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#setServiceUrl(java.lang.String) */ @Override public void setServiceUrl(String serviceUrl) { this.serviceUrl = serviceUrl; } /** * @see org.tools.hqlbuilder.common.DelegatingHqlService#getDelegate() */ @Override public HqlService getDelegate() { return hqlService; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#cleanupSql(java.lang.String, java.lang.String[], java.lang.String[][], boolean, boolean, * boolean) */ @Override public String cleanupSql(String sqlString, String[] queryReturnAliases, String[][] scalarColumnNames, boolean replaceProperties, boolean formatLines, boolean removeReplacers) { if (sqlString == null) { return ""; } // kolom alias (kan enkel maar wanneer de query al is omgezet, dus de tweede maal dat deze methode wordt opgeroepen- if (queryReturnAliases != null) { for (int i = 0; i < queryReturnAliases.length; i++) { String queryReturnAlias = queryReturnAliases[i]; if (queryReturnAlias != null) { try { String scalarColumnName = scalarColumnNames[i][0]; if (queryReturnAlias != null) { try { // nummers worden vervangen door 'kolom${nummer}' want nummer alleen wordt niet aanvaard Long.parseLong(queryReturnAlias); String newAlias = queryReturnAlias.replace('.', ' ').replace('(', ' ').replace(')', ' ').trim().replace(' ', '_'); logger.trace(": " + scalarColumnName + " >> " + queryReturnAlias + " >> " + newAlias); sqlString = sqlString.replace(scalarColumnName, newAlias); } catch (NumberFormatException ex) { logger.trace(": " + scalarColumnName + " >> " + queryReturnAlias); sqlString = sqlString.replace(scalarColumnName, queryReturnAlias); } } } catch (ArrayIndexOutOfBoundsException ex) { // } } } } // maakt replacers aan HashMap<String, String> replacers = new HashMap<>(); // vervang tabel_?_?_ door tabelnamen in "from ..." en "... join ..." // vervang replacers { String prefix = "((from)|(join)|(,))"; String joinfromgroup = "( ([a-zA-Z0-9_]+) ([a-zA-Z0-9_]+))"; Matcher matcher = Pattern.compile(prefix + joinfromgroup, Pattern.CASE_INSENSITIVE).matcher(sqlString); int startpos = 0; while (matcher.find(startpos)) { String replacing = matcher.group(7); if ("when".equals(replacing)) { startpos++; continue; } String replaceBy = matcher.group(6); for (Map.Entry<String, String> hqlReplacer : hqlReplacers.entrySet()) { if (replaceBy.contains(hqlReplacer.getKey())) { logger.trace("-> " + replaceBy + " >> " + replaceBy.replace(hqlReplacer.getKey(), hqlReplacer.getValue())); replaceBy = replaceBy.replace(hqlReplacer.getKey(), hqlReplacer.getValue()); } } @SuppressWarnings("deprecation") int existing = CollectionUtils.cardinality(replaceBy, replacers.values()); if (existing > 0) { logger.trace("-> " + replaceBy + " >> " + replaceBy + (existing + 1)); replaceBy = replaceBy + (existing + 1); } logger.trace("- " + replacing + " >> " + replaceBy); replacers.put(replacing, replaceBy); startpos = matcher.end(); } } // vervang (1) door (2) om geen dubbels te hebben // (1) tabel_?_?_=tabelnaamY EN tabel_?_=tabelnaamX // (2) tabel_?_?_=tabelnaamX_tabelnaamY EN tabel_?_=tabelnaamX List<String> hqlReplacerMap = new ArrayList<>(); for (Map.Entry<String, String> replacer : replacers.entrySet()) { for (Map.Entry<String, String> replacerOther : replacers.entrySet()) { if (!replacer.getKey().equals(replacerOther.getKey()) && replacer.getKey().startsWith(replacerOther.getKey())) { String newvalue = replacerOther.getValue() + "_" + replacer.getValue(); // oracle heeft 30 len limiet if (newvalue.length() > 30) { newvalue = newvalue.substring(0, 30); } logger.trace("* " + replacer + " EN " + replacerOther + " >> " + replacer.getValue() + "=" + newvalue); replacer.setValue(newvalue); hqlReplacerMap.add(newvalue); } } } // sorteer replacers op langste eerst List<String> keys = new ArrayList<>(replacers.keySet()); Collections.sort(keys, (o1, o2) -> { if (o1.length() < o2.length()) { return 1; } else if (o1.length() > o2.length()) { return -1; } else { return 0; } }); // vervang nu replacers for (String key : keys) { String value = replacers.get(key); logger.trace("+ " + key + " > " + value); sqlString = sqlString.replace(key, value); } // vervang kolomnamen if (replaceProperties) { Matcher matcher = Pattern.compile("(( )([^ ]+)( as )([a-zA-Z0-9_]+))", Pattern.CASE_INSENSITIVE).matcher(sqlString); while (matcher.find()) { String newvalue = matcher.group(3).replace('.', ' ').replace('(', ' ').replace(')', ' ').trim().replace(' ', '_'); // oracle heeft 30 len limiet if (newvalue.length() > 30) { newvalue = newvalue.substring(0, 30); } newvalue = " " + matcher.group(3) + " as " + newvalue; String group = matcher.group(); try { logger.trace("/ " + group + " > " + newvalue); sqlString = sqlString.replaceAll("\\Q" + group + "\\E", newvalue); } catch (Exception ex) { logger.warn("ERROR: " + ex); } } } logger.debug(sqlString); if (formatLines) { sqlString = makeMultiline(sqlString); } sqlString = removeBlanks(sqlString); @SuppressWarnings("unused") String[] sqlStringParts = sqlString.split(getNewline()); String[] lines = sqlString.split(getNewline()); if (removeReplacers) { for (int i = 0; i < lines.length; i++) { String line = lines[i]; boolean keep = true; for (String hqlReplacer : hqlReplacers.values()) { if (line.contains(hqlReplacer)) { keep &= keep(hqlReplacer, hqlReplacerMap, lines, i, line); } } // zal verwijderd worden if (!keep) { lines[i] = null; } } } StringBuilder anew = new StringBuilder(); for (String line : lines) { if (line != null) { anew.append(line).append(getNewline()); } } sqlString = anew.toString(); // logger.debug(sqlString); try { sqlString = CommonUtilsAdd.call( Class.forName("org.hibernate.jdbc.util.BasicFormatterImpl").getDeclaredConstructor().newInstance(), "format", String.class, sqlString); } catch (Throwable ex) { if (!warn1) { warn1 = true; logger.warn("{}", String.valueOf(ex)); } } try { Object formatter = Class.forName("org.hibernate.engine.jdbc.internal.BasicFormatterImpl") .getDeclaredConstructor().newInstance(); try { @SuppressWarnings("unchecked") Set<String> BEGIN_CLAUSES = (Set<String>) new ObjectWrapper(formatter).get("BEGIN_CLAUSES"); if (!BEGIN_CLAUSES.contains("cross")) { BEGIN_CLAUSES.add("cross"); } } catch (Exception ex) { // } sqlString = CommonUtilsAdd.call(formatter, "format", String.class, sqlString); } catch (Throwable ex) { if (!warn2) { warn2 = true; logger.warn("{}", String.valueOf(ex)); } } logger.info(sqlString); return sqlString; } private boolean warn1 = false; private boolean warn2 = false; /** * @see org.tools.hqlbuilder.client.HqlServiceClient#getNewline() */ @Override public String getNewline() { return NEWLINE; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#makeMultiline(java.lang.String) */ @Override public String makeMultiline(String string) { for (String kw : keywordGroups) { string = lineformat1replace(string, kw); } // (?i) : case insensitive // *+ : zero or more, possessive // $1 : replace with value of first group string = string.replaceAll("(?i) (ASC)[ ]*+,[ ]*+", " $1," + getNewline()); string = string.replaceAll("(?i) (DESC)[ ]*+,[ ]*+", " $1," + getNewline()); return string; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#removeBlanks(java.lang.String) */ @Override public String removeBlanks(String string) { return StringUtils.removeUnnecessaryWhiteSpaces(string); } private String lineformat1replace(String string, String splitter) { Matcher matcher = Pattern.compile(" " + splitter + " ", Pattern.CASE_INSENSITIVE).matcher(string); String CTE = "AAAAAAAAAAA"; String replaceAll = matcher.replaceAll(" " + getNewline() + CTE + " ").replaceAll(CTE, splitter); return replaceAll; } private boolean keep(String hqlReplacerValue, List<String> hqlReplacerValueX, String[] lines, int i, String line) { if (!line.contains(hqlReplacerValue)) { return true; } for (String hqlReplacerValueXEl : hqlReplacerValueX) { if (line.contains(hqlReplacerValueXEl)) { for (int j = 0; j < lines.length; j++) { if (i != j) { if (lines[j] != null && lines[j].contains(hqlReplacerValueXEl)) { // deze mag niet vervangen worden return true; } } } } } return false; } public Map<String, String> getHqlReplacers() { return this.hqlReplacers; } public void setHqlReplacers(Map<String, String> hqlReplacers) { this.hqlReplacers = hqlReplacers; } @Override public String getHibernateHelpURL() { return this.hqlService.getHibernateHelpURL().replace(RestResource.INTERNET_SHORTCUT_URL, ""); } @Override public String getHqlHelpURL() { return this.hqlService.getHqlHelpURL().replace(RestResource.INTERNET_SHORTCUT_URL, ""); } @Override public String getLuceneHelpURL() { return this.hqlService.getLuceneHelpURL().replace(RestResource.INTERNET_SHORTCUT_URL, ""); } }
jurgendl/hql-builder
hql-builder/hql-builder-client/src/main/java/org/tools/hqlbuilder/client/HqlServiceClientImpl.java
3,990
/** * @see org.tools.hqlbuilder.client.HqlServiceClient#makeMultiline(java.lang.String) */
block_comment
nl
package org.tools.hqlbuilder.client; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.collections4.CollectionUtils; import org.jhaws.common.lang.StringUtils; import org.jhaws.common.web.resteasy.RestResource; import org.slf4j.LoggerFactory; import org.swingeasy.ObjectWrapper; import org.tools.hqlbuilder.common.CommonUtilsAdd; import org.tools.hqlbuilder.common.DelegatingHqlService; import org.tools.hqlbuilder.common.HqlService; /** * @author Jurgen */ public class HqlServiceClientImpl extends DelegatingHqlService implements HqlServiceClient { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(HqlServiceClientImpl.class); public static final String NEWLINE = "\n"; private HqlService hqlService; private String serviceUrl; private String[] keywordGroups = { "cross join", "right outer join", "left outer join", "inner join", "from", "where", "having", "and", "or", "group by", "order by", "select", "," }; /** when cleaning up HQL: replace key by value */ private Map<String, String> hqlReplacers = new HashMap<>(); public HqlService getHqlService() { return hqlService; } public void setHqlService(HqlService hqlService) { this.hqlService = hqlService; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#getServiceUrl() */ @Override public String getServiceUrl() { return this.serviceUrl; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#setServiceUrl(java.lang.String) */ @Override public void setServiceUrl(String serviceUrl) { this.serviceUrl = serviceUrl; } /** * @see org.tools.hqlbuilder.common.DelegatingHqlService#getDelegate() */ @Override public HqlService getDelegate() { return hqlService; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#cleanupSql(java.lang.String, java.lang.String[], java.lang.String[][], boolean, boolean, * boolean) */ @Override public String cleanupSql(String sqlString, String[] queryReturnAliases, String[][] scalarColumnNames, boolean replaceProperties, boolean formatLines, boolean removeReplacers) { if (sqlString == null) { return ""; } // kolom alias (kan enkel maar wanneer de query al is omgezet, dus de tweede maal dat deze methode wordt opgeroepen- if (queryReturnAliases != null) { for (int i = 0; i < queryReturnAliases.length; i++) { String queryReturnAlias = queryReturnAliases[i]; if (queryReturnAlias != null) { try { String scalarColumnName = scalarColumnNames[i][0]; if (queryReturnAlias != null) { try { // nummers worden vervangen door 'kolom${nummer}' want nummer alleen wordt niet aanvaard Long.parseLong(queryReturnAlias); String newAlias = queryReturnAlias.replace('.', ' ').replace('(', ' ').replace(')', ' ').trim().replace(' ', '_'); logger.trace(": " + scalarColumnName + " >> " + queryReturnAlias + " >> " + newAlias); sqlString = sqlString.replace(scalarColumnName, newAlias); } catch (NumberFormatException ex) { logger.trace(": " + scalarColumnName + " >> " + queryReturnAlias); sqlString = sqlString.replace(scalarColumnName, queryReturnAlias); } } } catch (ArrayIndexOutOfBoundsException ex) { // } } } } // maakt replacers aan HashMap<String, String> replacers = new HashMap<>(); // vervang tabel_?_?_ door tabelnamen in "from ..." en "... join ..." // vervang replacers { String prefix = "((from)|(join)|(,))"; String joinfromgroup = "( ([a-zA-Z0-9_]+) ([a-zA-Z0-9_]+))"; Matcher matcher = Pattern.compile(prefix + joinfromgroup, Pattern.CASE_INSENSITIVE).matcher(sqlString); int startpos = 0; while (matcher.find(startpos)) { String replacing = matcher.group(7); if ("when".equals(replacing)) { startpos++; continue; } String replaceBy = matcher.group(6); for (Map.Entry<String, String> hqlReplacer : hqlReplacers.entrySet()) { if (replaceBy.contains(hqlReplacer.getKey())) { logger.trace("-> " + replaceBy + " >> " + replaceBy.replace(hqlReplacer.getKey(), hqlReplacer.getValue())); replaceBy = replaceBy.replace(hqlReplacer.getKey(), hqlReplacer.getValue()); } } @SuppressWarnings("deprecation") int existing = CollectionUtils.cardinality(replaceBy, replacers.values()); if (existing > 0) { logger.trace("-> " + replaceBy + " >> " + replaceBy + (existing + 1)); replaceBy = replaceBy + (existing + 1); } logger.trace("- " + replacing + " >> " + replaceBy); replacers.put(replacing, replaceBy); startpos = matcher.end(); } } // vervang (1) door (2) om geen dubbels te hebben // (1) tabel_?_?_=tabelnaamY EN tabel_?_=tabelnaamX // (2) tabel_?_?_=tabelnaamX_tabelnaamY EN tabel_?_=tabelnaamX List<String> hqlReplacerMap = new ArrayList<>(); for (Map.Entry<String, String> replacer : replacers.entrySet()) { for (Map.Entry<String, String> replacerOther : replacers.entrySet()) { if (!replacer.getKey().equals(replacerOther.getKey()) && replacer.getKey().startsWith(replacerOther.getKey())) { String newvalue = replacerOther.getValue() + "_" + replacer.getValue(); // oracle heeft 30 len limiet if (newvalue.length() > 30) { newvalue = newvalue.substring(0, 30); } logger.trace("* " + replacer + " EN " + replacerOther + " >> " + replacer.getValue() + "=" + newvalue); replacer.setValue(newvalue); hqlReplacerMap.add(newvalue); } } } // sorteer replacers op langste eerst List<String> keys = new ArrayList<>(replacers.keySet()); Collections.sort(keys, (o1, o2) -> { if (o1.length() < o2.length()) { return 1; } else if (o1.length() > o2.length()) { return -1; } else { return 0; } }); // vervang nu replacers for (String key : keys) { String value = replacers.get(key); logger.trace("+ " + key + " > " + value); sqlString = sqlString.replace(key, value); } // vervang kolomnamen if (replaceProperties) { Matcher matcher = Pattern.compile("(( )([^ ]+)( as )([a-zA-Z0-9_]+))", Pattern.CASE_INSENSITIVE).matcher(sqlString); while (matcher.find()) { String newvalue = matcher.group(3).replace('.', ' ').replace('(', ' ').replace(')', ' ').trim().replace(' ', '_'); // oracle heeft 30 len limiet if (newvalue.length() > 30) { newvalue = newvalue.substring(0, 30); } newvalue = " " + matcher.group(3) + " as " + newvalue; String group = matcher.group(); try { logger.trace("/ " + group + " > " + newvalue); sqlString = sqlString.replaceAll("\\Q" + group + "\\E", newvalue); } catch (Exception ex) { logger.warn("ERROR: " + ex); } } } logger.debug(sqlString); if (formatLines) { sqlString = makeMultiline(sqlString); } sqlString = removeBlanks(sqlString); @SuppressWarnings("unused") String[] sqlStringParts = sqlString.split(getNewline()); String[] lines = sqlString.split(getNewline()); if (removeReplacers) { for (int i = 0; i < lines.length; i++) { String line = lines[i]; boolean keep = true; for (String hqlReplacer : hqlReplacers.values()) { if (line.contains(hqlReplacer)) { keep &= keep(hqlReplacer, hqlReplacerMap, lines, i, line); } } // zal verwijderd worden if (!keep) { lines[i] = null; } } } StringBuilder anew = new StringBuilder(); for (String line : lines) { if (line != null) { anew.append(line).append(getNewline()); } } sqlString = anew.toString(); // logger.debug(sqlString); try { sqlString = CommonUtilsAdd.call( Class.forName("org.hibernate.jdbc.util.BasicFormatterImpl").getDeclaredConstructor().newInstance(), "format", String.class, sqlString); } catch (Throwable ex) { if (!warn1) { warn1 = true; logger.warn("{}", String.valueOf(ex)); } } try { Object formatter = Class.forName("org.hibernate.engine.jdbc.internal.BasicFormatterImpl") .getDeclaredConstructor().newInstance(); try { @SuppressWarnings("unchecked") Set<String> BEGIN_CLAUSES = (Set<String>) new ObjectWrapper(formatter).get("BEGIN_CLAUSES"); if (!BEGIN_CLAUSES.contains("cross")) { BEGIN_CLAUSES.add("cross"); } } catch (Exception ex) { // } sqlString = CommonUtilsAdd.call(formatter, "format", String.class, sqlString); } catch (Throwable ex) { if (!warn2) { warn2 = true; logger.warn("{}", String.valueOf(ex)); } } logger.info(sqlString); return sqlString; } private boolean warn1 = false; private boolean warn2 = false; /** * @see org.tools.hqlbuilder.client.HqlServiceClient#getNewline() */ @Override public String getNewline() { return NEWLINE; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#makeMultiline(java.lang.String) <SUF>*/ @Override public String makeMultiline(String string) { for (String kw : keywordGroups) { string = lineformat1replace(string, kw); } // (?i) : case insensitive // *+ : zero or more, possessive // $1 : replace with value of first group string = string.replaceAll("(?i) (ASC)[ ]*+,[ ]*+", " $1," + getNewline()); string = string.replaceAll("(?i) (DESC)[ ]*+,[ ]*+", " $1," + getNewline()); return string; } /** * @see org.tools.hqlbuilder.client.HqlServiceClient#removeBlanks(java.lang.String) */ @Override public String removeBlanks(String string) { return StringUtils.removeUnnecessaryWhiteSpaces(string); } private String lineformat1replace(String string, String splitter) { Matcher matcher = Pattern.compile(" " + splitter + " ", Pattern.CASE_INSENSITIVE).matcher(string); String CTE = "AAAAAAAAAAA"; String replaceAll = matcher.replaceAll(" " + getNewline() + CTE + " ").replaceAll(CTE, splitter); return replaceAll; } private boolean keep(String hqlReplacerValue, List<String> hqlReplacerValueX, String[] lines, int i, String line) { if (!line.contains(hqlReplacerValue)) { return true; } for (String hqlReplacerValueXEl : hqlReplacerValueX) { if (line.contains(hqlReplacerValueXEl)) { for (int j = 0; j < lines.length; j++) { if (i != j) { if (lines[j] != null && lines[j].contains(hqlReplacerValueXEl)) { // deze mag niet vervangen worden return true; } } } } } return false; } public Map<String, String> getHqlReplacers() { return this.hqlReplacers; } public void setHqlReplacers(Map<String, String> hqlReplacers) { this.hqlReplacers = hqlReplacers; } @Override public String getHibernateHelpURL() { return this.hqlService.getHibernateHelpURL().replace(RestResource.INTERNET_SHORTCUT_URL, ""); } @Override public String getHqlHelpURL() { return this.hqlService.getHqlHelpURL().replace(RestResource.INTERNET_SHORTCUT_URL, ""); } @Override public String getLuceneHelpURL() { return this.hqlService.getLuceneHelpURL().replace(RestResource.INTERNET_SHORTCUT_URL, ""); } }
False
3,014
25
3,331
31
3,510
31
3,331
31
3,980
35
false
false
false
false
false
true
4,238
23517_0
package org.example.h12; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) // tot waar moet de annotatie behouden blijven? public @interface Bram { String[] value() default ""; int age() default 0; }
sajanssens/bd2020-live-code
javase/src/main/java/org/example/h12/Bram.java
119
// tot waar moet de annotatie behouden blijven?
line_comment
nl
package org.example.h12; import java.lang.annotation.Retention; import java.lang.annotation.Target; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME) // tot waar<SUF> public @interface Bram { String[] value() default ""; int age() default 0; }
True
86
12
111
14
106
11
111
14
129
15
false
false
false
false
false
true
236
87803_1
package domein; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import persistentie.PersistentieController; public class Zoo {//DUMMY public final String PERSISTENCE_UNIT_NAME = "JPA_details"; private List<Verzorger> verzorgers; private List<Dier> dieren; private List<Gebouw> gebouwen; public Zoo() { this.dieren = new PersistentieController().geefDieren(); this.verzorgers = new PersistentieController().geefVerzorgers(); this.gebouwen = new PersistentieController().geefGebouwen(); } /* * Geeft alle dieren terug die behoren tot de diersoort met de opgegeven naam. De lijst van * dieren moet gesorteerd zijn op gewicht (laag naar hoog). */ public List<Dier> geefDierenVanSoortMetNaam(String soortNaam) { Comparator<Dier> opGewicht = Comparator.comparing(Dier::getGewicht); return dieren.stream() .filter(d -> d.getSoort().getNaam().equals(soortNaam)) .sorted(opGewicht) .collect(Collectors.toList()); } /* * Geeft het gemiddelde gewicht terug van alle dieren die verblijven in het gebouw met de * opgegeven naam. Geeft 0 terug indien er geen gebouw is met deze naam. */ public double geefGemiddeldeGewichtVanDierenInGebouwMetNaam(String gebouwNaam) { Gebouw gebouw = gebouwen.stream() .filter(g -> g.getNaam().equals(gebouwNaam)) .findFirst() .orElse(null); if(gebouw == null) { return 0; } return gebouw.getDieren().stream() .mapToDouble(Dier::getGewicht) .average() .getAsDouble(); } /* * Geeft de namen van de dieren terug die verzorgd worden door de verzorger met het opgegeven * nummer. Geeft een lege lijst terug indien er geen verzorger is met dit nummer. */ //-- public List<String> geefNamenVanDierenVanVerzorgerMetNummer(int verzorgerNummer) { Verzorger optVerzorger = verzorgers.stream() .filter(v -> v.getNummer() == verzorgerNummer) .findFirst() .orElse(null); if(optVerzorger != null) { return optVerzorger.getDieren().stream() .map(Dier::getNaam) .collect(Collectors.toList()); } return new ArrayList<String>(); } // /* // * Geeft een lijst terug van verzorgers die een of meerdere dieren verzorgen die verblijven in // * het gebouw met de opgegeven naam. Geeft een lege lijst terug indien er geen gebouw is met // * deze naam. // * NU DUMMY UITWERKING voor test gebruik in deze toepassing // * NIET VERDER UITWERKEN // */ public List<Verzorger> verzorgersInGebouwMetNaam(String gebouwNaam) { if (gebouwNaam.equalsIgnoreCase("Reptielen")) { return verzorgers; } else { return new ArrayList<>(); } } /** * De methode maakOverzichtVolgensSoort geeft een overzicht (Map) terug van * alle dieren per Soort. */ //TODO // TODO METHODE ....maakOverzichtVolgensSoort() ... hier uitschrijven // public Map<Soort, List<Dier>> maakOverzichtVolgensSoort(){ return dieren.stream() .collect(Collectors.groupingBy(Dier::getSoort)); } }
Bramke/OOPIII_Oplossingen
Ex_OOP3_1516_herex_start_vraag3_4/src/domein/Zoo.java
1,191
/* * Geeft het gemiddelde gewicht terug van alle dieren die verblijven in het gebouw met de * opgegeven naam. Geeft 0 terug indien er geen gebouw is met deze naam. */
block_comment
nl
package domein; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import persistentie.PersistentieController; public class Zoo {//DUMMY public final String PERSISTENCE_UNIT_NAME = "JPA_details"; private List<Verzorger> verzorgers; private List<Dier> dieren; private List<Gebouw> gebouwen; public Zoo() { this.dieren = new PersistentieController().geefDieren(); this.verzorgers = new PersistentieController().geefVerzorgers(); this.gebouwen = new PersistentieController().geefGebouwen(); } /* * Geeft alle dieren terug die behoren tot de diersoort met de opgegeven naam. De lijst van * dieren moet gesorteerd zijn op gewicht (laag naar hoog). */ public List<Dier> geefDierenVanSoortMetNaam(String soortNaam) { Comparator<Dier> opGewicht = Comparator.comparing(Dier::getGewicht); return dieren.stream() .filter(d -> d.getSoort().getNaam().equals(soortNaam)) .sorted(opGewicht) .collect(Collectors.toList()); } /* * Geeft het gemiddelde<SUF>*/ public double geefGemiddeldeGewichtVanDierenInGebouwMetNaam(String gebouwNaam) { Gebouw gebouw = gebouwen.stream() .filter(g -> g.getNaam().equals(gebouwNaam)) .findFirst() .orElse(null); if(gebouw == null) { return 0; } return gebouw.getDieren().stream() .mapToDouble(Dier::getGewicht) .average() .getAsDouble(); } /* * Geeft de namen van de dieren terug die verzorgd worden door de verzorger met het opgegeven * nummer. Geeft een lege lijst terug indien er geen verzorger is met dit nummer. */ //-- public List<String> geefNamenVanDierenVanVerzorgerMetNummer(int verzorgerNummer) { Verzorger optVerzorger = verzorgers.stream() .filter(v -> v.getNummer() == verzorgerNummer) .findFirst() .orElse(null); if(optVerzorger != null) { return optVerzorger.getDieren().stream() .map(Dier::getNaam) .collect(Collectors.toList()); } return new ArrayList<String>(); } // /* // * Geeft een lijst terug van verzorgers die een of meerdere dieren verzorgen die verblijven in // * het gebouw met de opgegeven naam. Geeft een lege lijst terug indien er geen gebouw is met // * deze naam. // * NU DUMMY UITWERKING voor test gebruik in deze toepassing // * NIET VERDER UITWERKEN // */ public List<Verzorger> verzorgersInGebouwMetNaam(String gebouwNaam) { if (gebouwNaam.equalsIgnoreCase("Reptielen")) { return verzorgers; } else { return new ArrayList<>(); } } /** * De methode maakOverzichtVolgensSoort geeft een overzicht (Map) terug van * alle dieren per Soort. */ //TODO // TODO METHODE ....maakOverzichtVolgensSoort() ... hier uitschrijven // public Map<Soort, List<Dier>> maakOverzichtVolgensSoort(){ return dieren.stream() .collect(Collectors.groupingBy(Dier::getSoort)); } }
True
958
56
1,078
64
993
48
1,089
64
1,181
54
false
false
false
false
false
true
1,179
200193_11
/* * @author Holger Vogelsang */ package de.hska.iwii.gui.drawing; import java.util.EventListener; import javafx.scene.Node; /** * Ein konkreter Beobachter der Zeichenereignisse muss diese * Schnittstelle implementieren. * @author H. Vogelsang */ public interface DrawingListener extends EventListener { /** * Reaktion auf einen Mausklick in die Zeichenflaeche. Dabei wird eine neue * Figur erzeugt. * @param figureType Zu erzeugende Figur: * <ul> * <li><code>"circle"</code> Es soll ein neuer Kreis erzeugt werden. * <li><code>"rect"</code> Es soll ein neues Rechteck erzeugt werden. * <li><code>"line"</code> Es soll eine neue Linie erzeugt werden. * </ul> * @param xPos X-Position des Mauszeigers waehrend des Klicks. * @param yPos y-Position des Mauszeigers waehrend des Klicks. */ void startCreateFigure(String figureType, double xPos, double yPos); /** * Die Figur an der mit <code>pos</code> gekennzeichneten Stelle * soll verschoben werden. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers waehrend des Klicks. * @param yPos y-Position des Mauszeigers waehrend des Klicks. */ void startMoveFigure(Node node, double xPos, double yPos); /** * Der Mauszeiger wird mit gedrueckter Maustaste ueber die * Zeichenflaeche bewegt. Dabei wird die neu mit * <code>startCreateFigure</code> erzeugte Figur in der Groesse * veraendert. * @param xPos X-Position des Mauszeigers waehrend des Verschiebens. * @param yPos y-Position des Mauszeigers waehrend des Verschiebens. */ void workCreateFigure(double xPos, double yPos); /** * Der Mauszeiger wird mit gedrueckter Maustaste ueber die * Zeichenflaeche bewegt. Dabei wird eine mit * <code>startMoveFigure</code> gewaehlte Figur verschoben. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers waehrend des Verschiebens. * @param yPos y-Position des Mauszeigers waehrend des Verschiebens. */ void workMoveFigure(Node node, double xPos, double yPos); /** * Der Mauszeiger wird wieder losgelassen. Das Erzeugen * der Figur ist somit beendet. * @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste. * @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste. */ void endCreateFigure(double xPos, double yPos); /** * Der Mauszeiger wird wieder losgelassen. Das Verschieben * der Figur ist somit beendet. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste. * @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste. */ void endMoveFigure(Node node, double xPos, double yPos); /** * Selektionsereignis: Die Maustaste wurde auf einer Figur * gedrueckt und wieder losgelassen. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers waehrend des Klicks. * @param yPos y-Position des Mauszeigers waehrend des Klicks. * @param shiftPressed <code>true</code>: Die Shift-Taste wurde waehrend des * Mausklicks gedrueckt. */ void selectFigure(Node node, double xPos, double yPos, boolean shiftPressed); /** * Gestenereignis: Figur soll gedreht werden. * @param node Zu drehende Figure. * @param angle Winkel, um den die Figur weitergedreht werden soll. */ void rotate(Node node, double angle); /** * Gestenereignis: Figur soll verschoben werden. * @param node Zu verschiebende Figure. * @param deltaX Abstand in x-Richtung, um den die Figur weitergeschoben werden soll. * @param deltaY Abstand in y-Richtung, um den die Figur weitergeschoben werden soll. */ void translate(Node node, double deltaX, double deltaY); /** * Gestenereignis: Groesse der Figur soll veraendert werden. * @param node Zu verandernde Figure. * @param zoomFactor Faktor, um den die Figur vergroessert oder verkleinert werden soll. */ void zoom(Node node, double zoomFactor); /** * Aufforderung zum Loeschen der selektierten Figur. */ void deleteFigures(); /** * Aufforderung zum Kopieren der selektierten Figuren. */ void copyFigures(); /** * Aufforderung zum Einfuegen einer kopierten Figuren. */ void pasteFigures(); /** * Selektierte Figuren in die oberste Ebene verschieben. */ void moveSelectedFiguresToTop(); /** * Selektierte Figuren in die unterste Ebene verschieben. */ void moveSelectedFiguresToBottom(); /** * Selektierte Figuren eine Ebene nach unten verschieben. */ void moveSelectedFiguresDown(); /** * Selektierte Figuren um eine Ebene nach oben verschieben. */ void moveSelectedFiguresUp(); /** * Alle selektierten Figuren zu einer Gruppe zusammenfassen. */ void groupFigures(); /** * Alle selektierten Gruppen aufloesen. */ void ungroupFigures(); /** * Anzahl selektierter Figuren ermitteln. * @return Anzahl selektierter Figuren. */ int getSelectedFiguresCount(); /** * Anzahl Figuren im Clipboard ermitteln. * @return Anzahl Figuren im Clipboard. */ int getFiguresInClipboardCount(); /** * Ist eine Gruppe momentan selektiert? * @return <code>true</code> Ja, es ist mindestens eine Gruppe selektiert. */ boolean isGroupSelected(); }
Nad707/Zeichenprogramm
src/de/hska/iwii/gui/drawing/DrawingListener.java
1,812
/** * Gestenereignis: Groesse der Figur soll veraendert werden. * @param node Zu verandernde Figure. * @param zoomFactor Faktor, um den die Figur vergroessert oder verkleinert werden soll. */
block_comment
nl
/* * @author Holger Vogelsang */ package de.hska.iwii.gui.drawing; import java.util.EventListener; import javafx.scene.Node; /** * Ein konkreter Beobachter der Zeichenereignisse muss diese * Schnittstelle implementieren. * @author H. Vogelsang */ public interface DrawingListener extends EventListener { /** * Reaktion auf einen Mausklick in die Zeichenflaeche. Dabei wird eine neue * Figur erzeugt. * @param figureType Zu erzeugende Figur: * <ul> * <li><code>"circle"</code> Es soll ein neuer Kreis erzeugt werden. * <li><code>"rect"</code> Es soll ein neues Rechteck erzeugt werden. * <li><code>"line"</code> Es soll eine neue Linie erzeugt werden. * </ul> * @param xPos X-Position des Mauszeigers waehrend des Klicks. * @param yPos y-Position des Mauszeigers waehrend des Klicks. */ void startCreateFigure(String figureType, double xPos, double yPos); /** * Die Figur an der mit <code>pos</code> gekennzeichneten Stelle * soll verschoben werden. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers waehrend des Klicks. * @param yPos y-Position des Mauszeigers waehrend des Klicks. */ void startMoveFigure(Node node, double xPos, double yPos); /** * Der Mauszeiger wird mit gedrueckter Maustaste ueber die * Zeichenflaeche bewegt. Dabei wird die neu mit * <code>startCreateFigure</code> erzeugte Figur in der Groesse * veraendert. * @param xPos X-Position des Mauszeigers waehrend des Verschiebens. * @param yPos y-Position des Mauszeigers waehrend des Verschiebens. */ void workCreateFigure(double xPos, double yPos); /** * Der Mauszeiger wird mit gedrueckter Maustaste ueber die * Zeichenflaeche bewegt. Dabei wird eine mit * <code>startMoveFigure</code> gewaehlte Figur verschoben. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers waehrend des Verschiebens. * @param yPos y-Position des Mauszeigers waehrend des Verschiebens. */ void workMoveFigure(Node node, double xPos, double yPos); /** * Der Mauszeiger wird wieder losgelassen. Das Erzeugen * der Figur ist somit beendet. * @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste. * @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste. */ void endCreateFigure(double xPos, double yPos); /** * Der Mauszeiger wird wieder losgelassen. Das Verschieben * der Figur ist somit beendet. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers nach Loslassen der Maustaste. * @param yPos y-Position des Mauszeigers nach Loslassen der Maustaste. */ void endMoveFigure(Node node, double xPos, double yPos); /** * Selektionsereignis: Die Maustaste wurde auf einer Figur * gedrueckt und wieder losgelassen. * @param node Zu verschiebende Figure. * @param xPos X-Position des Mauszeigers waehrend des Klicks. * @param yPos y-Position des Mauszeigers waehrend des Klicks. * @param shiftPressed <code>true</code>: Die Shift-Taste wurde waehrend des * Mausklicks gedrueckt. */ void selectFigure(Node node, double xPos, double yPos, boolean shiftPressed); /** * Gestenereignis: Figur soll gedreht werden. * @param node Zu drehende Figure. * @param angle Winkel, um den die Figur weitergedreht werden soll. */ void rotate(Node node, double angle); /** * Gestenereignis: Figur soll verschoben werden. * @param node Zu verschiebende Figure. * @param deltaX Abstand in x-Richtung, um den die Figur weitergeschoben werden soll. * @param deltaY Abstand in y-Richtung, um den die Figur weitergeschoben werden soll. */ void translate(Node node, double deltaX, double deltaY); /** * Gestenereignis: Groesse der<SUF>*/ void zoom(Node node, double zoomFactor); /** * Aufforderung zum Loeschen der selektierten Figur. */ void deleteFigures(); /** * Aufforderung zum Kopieren der selektierten Figuren. */ void copyFigures(); /** * Aufforderung zum Einfuegen einer kopierten Figuren. */ void pasteFigures(); /** * Selektierte Figuren in die oberste Ebene verschieben. */ void moveSelectedFiguresToTop(); /** * Selektierte Figuren in die unterste Ebene verschieben. */ void moveSelectedFiguresToBottom(); /** * Selektierte Figuren eine Ebene nach unten verschieben. */ void moveSelectedFiguresDown(); /** * Selektierte Figuren um eine Ebene nach oben verschieben. */ void moveSelectedFiguresUp(); /** * Alle selektierten Figuren zu einer Gruppe zusammenfassen. */ void groupFigures(); /** * Alle selektierten Gruppen aufloesen. */ void ungroupFigures(); /** * Anzahl selektierter Figuren ermitteln. * @return Anzahl selektierter Figuren. */ int getSelectedFiguresCount(); /** * Anzahl Figuren im Clipboard ermitteln. * @return Anzahl Figuren im Clipboard. */ int getFiguresInClipboardCount(); /** * Ist eine Gruppe momentan selektiert? * @return <code>true</code> Ja, es ist mindestens eine Gruppe selektiert. */ boolean isGroupSelected(); }
False
1,569
60
1,713
64
1,566
58
1,712
64
1,832
65
false
false
false
false
false
true
927
175943_3
/* * Knowage, Open Source Business Intelligence suite * Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A. * * Knowage is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Knowage is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.eng.knowage.document.cockpit.template.widget; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import it.eng.spagobi.utilities.assertion.Assert; /** * @author Dragan Pirkovic * */ public abstract class AbstactWidgetReader implements ICockpitWidget { protected JSONObject jsonWidget; /** * */ protected AbstactWidgetReader() { } @Override public JSONArray getColumnSelectedOfDataSet() { Assert.assertNotNull(getContent(), "content cannot be null"); return getContent().optJSONArray("columnSelectedOfDataset"); } @Override public Integer getDsId() { Assert.assertNotNull(getDataset(), "dataset cannot be null"); return getDataset().optInt("dsId"); } @Override public String getDsLabel() { Assert.assertNotNull(getDataset(), "dataset cannot be null"); return getDataset().optString("dsLabel"); } /* * (non-Javadoc) * * @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getId() */ @Override public Integer getId() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return this.jsonWidget.optInt("id"); } /* * (non-Javadoc) * * @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getJsonWidget() */ @Override public JSONObject getJsonWidget() { return jsonWidget; } /** * */ protected JSONObject getContent() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return this.jsonWidget.optJSONObject("content"); } /** * @return */ protected String getContentName() { Assert.assertNotNull(getContent(), "content cannot be null"); return getContent().optString("name"); } /** * @return * @throws JSONException */ protected JSONObject getDataset() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return jsonWidget.optJSONObject("dataset"); } /** * @return */ protected String getWidgetTitleLabel() { Assert.assertNotNull(getTitle(), "title cannot be null"); return getTitle().optString("label"); } /** * @return * @throws JSONException */ protected boolean isTilteDefined() { return styleContainsProperties() && isWidgetTitleLabelDefined(); } /** * @return * @throws JSONException */ private JSONObject getStyle() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return jsonWidget.optJSONObject("style"); } /** * @return * @throws JSONException */ private JSONObject getTitle() { Assert.assertNotNull(getStyle(), "style cannot be null"); return getStyle().optJSONObject("title"); } private boolean isWidgetTitleLabelDefined() { return getTitle() != null && getWidgetTitleLabel() != null && !getWidgetTitleLabel().equals(""); } /** * @return * @throws JSONException */ private boolean styleContainsProperties() { return getStyle() != null && getStyle().length() != 0; } }
KnowageLabs/Knowage-Server
knowage-core/src/main/java/it/eng/knowage/document/cockpit/template/widget/AbstactWidgetReader.java
1,117
/* * (non-Javadoc) * * @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getJsonWidget() */
block_comment
nl
/* * Knowage, Open Source Business Intelligence suite * Copyright (C) 2016 Engineering Ingegneria Informatica S.p.A. * * Knowage is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Knowage is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package it.eng.knowage.document.cockpit.template.widget; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import it.eng.spagobi.utilities.assertion.Assert; /** * @author Dragan Pirkovic * */ public abstract class AbstactWidgetReader implements ICockpitWidget { protected JSONObject jsonWidget; /** * */ protected AbstactWidgetReader() { } @Override public JSONArray getColumnSelectedOfDataSet() { Assert.assertNotNull(getContent(), "content cannot be null"); return getContent().optJSONArray("columnSelectedOfDataset"); } @Override public Integer getDsId() { Assert.assertNotNull(getDataset(), "dataset cannot be null"); return getDataset().optInt("dsId"); } @Override public String getDsLabel() { Assert.assertNotNull(getDataset(), "dataset cannot be null"); return getDataset().optString("dsLabel"); } /* * (non-Javadoc) * * @see it.eng.knowage.document.cockpit.template.widget.ICockpitWidget#getId() */ @Override public Integer getId() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return this.jsonWidget.optInt("id"); } /* * (non-Javadoc) <SUF>*/ @Override public JSONObject getJsonWidget() { return jsonWidget; } /** * */ protected JSONObject getContent() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return this.jsonWidget.optJSONObject("content"); } /** * @return */ protected String getContentName() { Assert.assertNotNull(getContent(), "content cannot be null"); return getContent().optString("name"); } /** * @return * @throws JSONException */ protected JSONObject getDataset() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return jsonWidget.optJSONObject("dataset"); } /** * @return */ protected String getWidgetTitleLabel() { Assert.assertNotNull(getTitle(), "title cannot be null"); return getTitle().optString("label"); } /** * @return * @throws JSONException */ protected boolean isTilteDefined() { return styleContainsProperties() && isWidgetTitleLabelDefined(); } /** * @return * @throws JSONException */ private JSONObject getStyle() { Assert.assertNotNull(jsonWidget, "jsonWidget cannot be null"); return jsonWidget.optJSONObject("style"); } /** * @return * @throws JSONException */ private JSONObject getTitle() { Assert.assertNotNull(getStyle(), "style cannot be null"); return getStyle().optJSONObject("title"); } private boolean isWidgetTitleLabelDefined() { return getTitle() != null && getWidgetTitleLabel() != null && !getWidgetTitleLabel().equals(""); } /** * @return * @throws JSONException */ private boolean styleContainsProperties() { return getStyle() != null && getStyle().length() != 0; } }
False
853
34
1,019
41
1,031
45
1,019
41
1,207
48
false
false
false
false
false
true
448
17436_4
package ehb.group5.app.UI.views; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H1; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.VaadinSession; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import ehb.group5.app.UI.layouts.CommonLayout; import ehb.group5.app.backend.data.DatabaseService; import ehb.group5.app.backend.data.table.CompanyEntity; @Route("support") @PageTitle("Support services") @CssImport("./styles/support.css") public class SupportView extends CommonLayout { /* Author: LAMSAKAM Zakaria email: zakaria.lamsakam@student.ehb.be */ /* Ik heb het Vaadin documentatie gebruikt voor de textfield,de emailfield en de passwordfield. https://vaadin.com/docs/v14/ */ public SupportView(){ Div Supportdiv = new Div(); Supportdiv.setId("supportid"); //Titel aanmaken. Supportdiv.add(new H1("Support services")); //Knop aanmaken voor de eerste probleem. Button button = new Button("Ik heb een probleem met de facturatie"); //Notificatie tonen wanneer er op een button wordt geklikt. Dialog dialog = new Dialog(); dialog.add(new Text("Uw factuur bereikt zijn bestemming niet door onjuiste gegevens. Vraag vooraf alle gegevens op, begin met het e-mailadres van de verantwoordelijke voor de betaling van de facturen.\"" + ""+" Andere problemen bel dan deze telefoonnummer voor support: 0124592598"), //Event toevoegen om de button de sluiten new Button("Close", e -> dialog.close())); //De breedte en lengte van de notificatie initialiseren. dialog.setWidth("600px"); dialog.setHeight("250px"); //Event toevoegen om de notificatie open te doen. button.addClickListener(event -> dialog.open()); //Knop aanmaken voor de tweede probleem. Button button2 = new Button("Ik heb een probleem met de betaling"); Dialog dialog2 = new Dialog(); //Hier wordt de text die in de noficatie zitten geïnstalleerd. dialog2.add(new Text("U kan dit oplossen door één of meerdere minder dringende overschrijvingen uit te vinken.\n" + " Vervolgens tekent u enkel de aangevinkte verrichtingen. "+" " + "Andere problemen bel dan deze telefoonnummer voor support: 0124392594"), new Button("Close", e -> dialog2.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button2.addClickListener(event -> dialog2.open()); //Knop aanmaken voor de derde probleem. Button button3 = new Button("Ik heb een probleem met het bewerken van de informatie "); Dialog dialog3 = new Dialog(); dialog3.add(new Text("BIC code (Bank Identification Code) is een unieke code die één welbepaalde bank identificeert en bestaat meestal uit 8 of 11 tekens." +" Andere problemen bel dan deze telefoonnummer voor support: 0184592599"), new Button("Close", e -> dialog3.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button3.addClickListener(event -> dialog3.open()); //Knop aanmaken voor de vierde probleem. Button button4 = new Button("Ik heb een probleem met de agenda"); Dialog dialog4 = new Dialog(); dialog4.add(new Text("Zorg ervoor dat je verbinding met internet hebt, controleer of de agenda zichtbaar is, zorg dat nieuwe afspraken worden toegevoegd aan je Google Agenda." +" Andere problemen bel dan deze telefoonnummer voor support: 0124692298"), new Button("Close", e -> dialog4.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button4.addClickListener(event -> dialog4.open()); //Laatste knop aanmaken voor de vijfde probleem. Button button5 = new Button("Andere probleem"); //Wanneer er geklikt wordt op de button gaan we gestuurd worden naar de pagina van de klasse die geplaats word. button5.addClickListener(buttonClickEvent ->{ UI.getCurrent().navigate(TicketView.class); }); //Alle buttons toevoegen aan de supportdiv. Supportdiv.add(button, button2,button3,button4,button5); Supportdiv.addClassName("centered-content"); getContainer().add(Supportdiv); } }
EHB-TI/Groep5-Reservingstool_voor_winkeliers
src/main/java/ehb/group5/app/UI/views/SupportView.java
1,425
//Event toevoegen om de button de sluiten
line_comment
nl
package ehb.group5.app.UI.views; import com.vaadin.flow.component.Text; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.CssImport; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.H1; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.vaadin.flow.server.VaadinSession; import com.vaadin.flow.theme.Theme; import com.vaadin.flow.theme.lumo.Lumo; import ehb.group5.app.UI.layouts.CommonLayout; import ehb.group5.app.backend.data.DatabaseService; import ehb.group5.app.backend.data.table.CompanyEntity; @Route("support") @PageTitle("Support services") @CssImport("./styles/support.css") public class SupportView extends CommonLayout { /* Author: LAMSAKAM Zakaria email: zakaria.lamsakam@student.ehb.be */ /* Ik heb het Vaadin documentatie gebruikt voor de textfield,de emailfield en de passwordfield. https://vaadin.com/docs/v14/ */ public SupportView(){ Div Supportdiv = new Div(); Supportdiv.setId("supportid"); //Titel aanmaken. Supportdiv.add(new H1("Support services")); //Knop aanmaken voor de eerste probleem. Button button = new Button("Ik heb een probleem met de facturatie"); //Notificatie tonen wanneer er op een button wordt geklikt. Dialog dialog = new Dialog(); dialog.add(new Text("Uw factuur bereikt zijn bestemming niet door onjuiste gegevens. Vraag vooraf alle gegevens op, begin met het e-mailadres van de verantwoordelijke voor de betaling van de facturen.\"" + ""+" Andere problemen bel dan deze telefoonnummer voor support: 0124592598"), //Event toevoegen<SUF> new Button("Close", e -> dialog.close())); //De breedte en lengte van de notificatie initialiseren. dialog.setWidth("600px"); dialog.setHeight("250px"); //Event toevoegen om de notificatie open te doen. button.addClickListener(event -> dialog.open()); //Knop aanmaken voor de tweede probleem. Button button2 = new Button("Ik heb een probleem met de betaling"); Dialog dialog2 = new Dialog(); //Hier wordt de text die in de noficatie zitten geïnstalleerd. dialog2.add(new Text("U kan dit oplossen door één of meerdere minder dringende overschrijvingen uit te vinken.\n" + " Vervolgens tekent u enkel de aangevinkte verrichtingen. "+" " + "Andere problemen bel dan deze telefoonnummer voor support: 0124392594"), new Button("Close", e -> dialog2.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button2.addClickListener(event -> dialog2.open()); //Knop aanmaken voor de derde probleem. Button button3 = new Button("Ik heb een probleem met het bewerken van de informatie "); Dialog dialog3 = new Dialog(); dialog3.add(new Text("BIC code (Bank Identification Code) is een unieke code die één welbepaalde bank identificeert en bestaat meestal uit 8 of 11 tekens." +" Andere problemen bel dan deze telefoonnummer voor support: 0184592599"), new Button("Close", e -> dialog3.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button3.addClickListener(event -> dialog3.open()); //Knop aanmaken voor de vierde probleem. Button button4 = new Button("Ik heb een probleem met de agenda"); Dialog dialog4 = new Dialog(); dialog4.add(new Text("Zorg ervoor dat je verbinding met internet hebt, controleer of de agenda zichtbaar is, zorg dat nieuwe afspraken worden toegevoegd aan je Google Agenda." +" Andere problemen bel dan deze telefoonnummer voor support: 0124692298"), new Button("Close", e -> dialog4.close())); dialog.setWidth("600px"); dialog.setHeight("250px"); button4.addClickListener(event -> dialog4.open()); //Laatste knop aanmaken voor de vijfde probleem. Button button5 = new Button("Andere probleem"); //Wanneer er geklikt wordt op de button gaan we gestuurd worden naar de pagina van de klasse die geplaats word. button5.addClickListener(buttonClickEvent ->{ UI.getCurrent().navigate(TicketView.class); }); //Alle buttons toevoegen aan de supportdiv. Supportdiv.add(button, button2,button3,button4,button5); Supportdiv.addClassName("centered-content"); getContainer().add(Supportdiv); } }
True
1,157
11
1,355
13
1,278
10
1,355
13
1,489
12
false
false
false
false
false
true
3,480
149980_7
package com.fourinone;_x000D_ _x000D_ import java.util.List;_x000D_ import java.util.ArrayList;_x000D_ _x000D_ public class MigrantWorker extends WorkerParallel implements ParkStatg_x000D_ {_x000D_ String host,workerType,workerjarname;_x000D_ int port;_x000D_ private int selfIndex=-1;_x000D_ private volatile boolean _interrupted;_x000D_ _x000D_ void waitWorkingByService(String workerType)_x000D_ {_x000D_ //publish service and reg heatbeat_x000D_ //try{_x000D_ //Worker wk = new WorkerService(this);_x000D_ /*BeanContext.startWorker(workerType, this);_x000D_ ParkPatternExector.createWorkerTypeNode(workerType, nodevalue);*/_x000D_ _x000D_ String[] wkcfg = ConfigContext.getWorkerConfig();_x000D_ waitWorkingByService(wkcfg[0], Integer.parseInt(wkcfg[1]), workerType);_x000D_ //}catch(RemoteException e){_x000D_ // System.out.println("waitWorking:"+e);_x000D_ //}_x000D_ }_x000D_ _x000D_ void waitWorkingByService(String host, int port, String workerType)//remove protected_x000D_ {_x000D_ //String[] wkcfg = ConfigContext.getWorkerConfig();_x000D_ //startWorker(wkcfg[0], Integer.parseInt(wkcfg[1]), sn, mwk);_x000D_ this.host = host;_x000D_ this.port = port;_x000D_ this.workerType = workerType;_x000D_ //BeanContext.startWorker(host, port, workerType, this);_x000D_ BeanContext.startWorker(host, port, workerType, this, this.getClass().equals(MigrantWorker.class));_x000D_ ParkPatternExector.createWorkerTypeNode(workerType, host+":"+port);_x000D_ }_x000D_ _x000D_ void waitWorkingByPark(String workerType)_x000D_ {_x000D_ ObjectBean ob = ParkPatternExector.createWorkerTypeNode(workerType, "wk_pk");_x000D_ _x000D_ while(true)_x000D_ {_x000D_ ObjectBean lastestOb = ParkPatternExector.getLastestObjectBean(ob);_x000D_ WareHouse whouse = doTask((WareHouse)lastestOb.toObject());_x000D_ ob = ParkPatternExector.updateObjectBean(lastestOb, whouse);_x000D_ }_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerElse()_x000D_ {_x000D_ return getWorkerElse(this.workerType);_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerElse(String workerType)_x000D_ {_x000D_ /*List<Workman> wklist = new ArrayList<Workman>();_x000D_ if(parallelPatternFlag!=1)_x000D_ {_x000D_ List<String[]> wslist = getWorkersService(host, port, workerType);_x000D_ for(String[] wsinfo:wslist)_x000D_ wklist.add(BeanContext.getWorkerElse(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]));_x000D_ }_x000D_ return wklist.toArray(new Workman[wklist.size()]);*/_x000D_ return getWorkers(host, port, workerType);_x000D_ }_x000D_ _x000D_ protected Workman getWorkerIndex(int index)_x000D_ {_x000D_ return getWorkerIndex(this.workerType, index);_x000D_ }_x000D_ _x000D_ protected Workman getWorkerIndex(String workerType, int index)_x000D_ {_x000D_ //if(parallelPatternFlag!=1)_x000D_ //{_x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ if(index>=0&&index<wslist.size())_x000D_ {_x000D_ String[] wsinfo = wslist.get(index);_x000D_ return BeanContext.getWorkman(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]);_x000D_ }else return null;_x000D_ //}_x000D_ //return null;_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerAll()_x000D_ {_x000D_ return getWorkerAll(this.workerType);_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerAll(String workerType)_x000D_ {_x000D_ return getWorkers(null, 0, workerType);_x000D_ }_x000D_ _x000D_ private Workman[] getWorkers(String host, int port, String workerType)_x000D_ {_x000D_ //System.out.println(host+":"+port);_x000D_ List<Workman> wklist = new ArrayList<Workman>();_x000D_ if(parallelPatternFlag!=1)_x000D_ {_x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ for(int i=0;i<wslist.size();i++)_x000D_ {_x000D_ String[] wsinfo = wslist.get(i);_x000D_ //System.out.println(wsinfo[0]+":"+wsinfo[1]);_x000D_ if(!wsinfo[0].equals(host)||Integer.parseInt(wsinfo[1])!=port)_x000D_ wklist.add(BeanContext.getWorkman(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]));_x000D_ else_x000D_ selfIndex = i;_x000D_ }_x000D_ }_x000D_ return wklist.toArray(new Workman[wklist.size()]);_x000D_ } _x000D_ _x000D_ protected int getSelfIndex()_x000D_ {_x000D_ if(selfIndex==-1)_x000D_ {_x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ for(int i=0;i<wslist.size();i++)_x000D_ {_x000D_ String[] wsinfo = wslist.get(i);_x000D_ if(wsinfo[0].equals(host)&&Integer.parseInt(wsinfo[1])==port)_x000D_ return i;_x000D_ }_x000D_ }_x000D_ return selfIndex;_x000D_ }_x000D_ _x000D_ protected Workman getWorkerElse(String workerType, String host, int port)_x000D_ {_x000D_ if(this.host.equals(host)&&this.port==port)_x000D_ return null;_x000D_ _x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ if(wslist!=null){_x000D_ for(int i=0;i<wslist.size();i++)_x000D_ {_x000D_ String[] wsinfo = wslist.get(i);_x000D_ //System.out.println(wsinfo[0]+":"+wsinfo[1]);_x000D_ _x000D_ if(wsinfo[0].equals(host)&&Integer.parseInt(wsinfo[1])==port)_x000D_ return BeanContext.getWorkman(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]);_x000D_ }_x000D_ }_x000D_ return null;_x000D_ }_x000D_ _x000D_ synchronized boolean receiveMaterials(WareHouse inhouse)_x000D_ {_x000D_ return receive(inhouse);_x000D_ }_x000D_ _x000D_ protected boolean receive(WareHouse inhouse)_x000D_ {_x000D_ return true;_x000D_ }_x000D_ _x000D_ protected WareHouse doTask(WareHouse inhouse)_x000D_ {_x000D_ WareHouse outhouse = new WareHouse();_x000D_ return outhouse;_x000D_ }_x000D_ _x000D_ protected boolean isInterrupted(){_x000D_ return _interrupted;_x000D_ }_x000D_ _x000D_ void interrupted(boolean _interrupted){_x000D_ this._interrupted = _interrupted;_x000D_ }_x000D_ _x000D_ public void setWorkerJar(String workerjarname){_x000D_ this.workerjarname = workerjarname;_x000D_ }_x000D_ _x000D_ public String getWorkerJar(){_x000D_ return workerjarname;_x000D_ }_x000D_ _x000D_ void setHost(String host){_x000D_ this.host = host;_x000D_ }_x000D_ _x000D_ String getHost(){_x000D_ return host;_x000D_ }_x000D_ _x000D_ void setWorkerType(String workerType){_x000D_ this.workerType = workerType;_x000D_ }_x000D_ _x000D_ String getWorkerType(){_x000D_ return workerType;_x000D_ }_x000D_ _x000D_ void setPort(int port){_x000D_ this.port = port;_x000D_ }_x000D_ _x000D_ int getPort(){_x000D_ return port;_x000D_ }_x000D_ _x000D_ void setSelfIndex(int selfIndex){_x000D_ this.selfIndex = selfIndex;_x000D_ }_x000D_ _x000D_ /*int getSelfIndex(){_x000D_ return selfIndex;_x000D_ }*/_x000D_ _x000D_ public static void main(String[] args){_x000D_ MigrantWorker mw = new MigrantWorker();_x000D_ //System.out.println(args.length);_x000D_ if(args.length==4)_x000D_ mw.setWorkerJar(args[3]);_x000D_ mw.waitWorking(args[0],Integer.parseInt(args[1]),args[2]);_x000D_ }_x000D_ }
lili6/fourinone
src/main/java/com/fourinone/MigrantWorker.java
2,094
/*int getSelfIndex(){_x000D_ return selfIndex;_x000D_ }*/
block_comment
nl
package com.fourinone;_x000D_ _x000D_ import java.util.List;_x000D_ import java.util.ArrayList;_x000D_ _x000D_ public class MigrantWorker extends WorkerParallel implements ParkStatg_x000D_ {_x000D_ String host,workerType,workerjarname;_x000D_ int port;_x000D_ private int selfIndex=-1;_x000D_ private volatile boolean _interrupted;_x000D_ _x000D_ void waitWorkingByService(String workerType)_x000D_ {_x000D_ //publish service and reg heatbeat_x000D_ //try{_x000D_ //Worker wk = new WorkerService(this);_x000D_ /*BeanContext.startWorker(workerType, this);_x000D_ ParkPatternExector.createWorkerTypeNode(workerType, nodevalue);*/_x000D_ _x000D_ String[] wkcfg = ConfigContext.getWorkerConfig();_x000D_ waitWorkingByService(wkcfg[0], Integer.parseInt(wkcfg[1]), workerType);_x000D_ //}catch(RemoteException e){_x000D_ // System.out.println("waitWorking:"+e);_x000D_ //}_x000D_ }_x000D_ _x000D_ void waitWorkingByService(String host, int port, String workerType)//remove protected_x000D_ {_x000D_ //String[] wkcfg = ConfigContext.getWorkerConfig();_x000D_ //startWorker(wkcfg[0], Integer.parseInt(wkcfg[1]), sn, mwk);_x000D_ this.host = host;_x000D_ this.port = port;_x000D_ this.workerType = workerType;_x000D_ //BeanContext.startWorker(host, port, workerType, this);_x000D_ BeanContext.startWorker(host, port, workerType, this, this.getClass().equals(MigrantWorker.class));_x000D_ ParkPatternExector.createWorkerTypeNode(workerType, host+":"+port);_x000D_ }_x000D_ _x000D_ void waitWorkingByPark(String workerType)_x000D_ {_x000D_ ObjectBean ob = ParkPatternExector.createWorkerTypeNode(workerType, "wk_pk");_x000D_ _x000D_ while(true)_x000D_ {_x000D_ ObjectBean lastestOb = ParkPatternExector.getLastestObjectBean(ob);_x000D_ WareHouse whouse = doTask((WareHouse)lastestOb.toObject());_x000D_ ob = ParkPatternExector.updateObjectBean(lastestOb, whouse);_x000D_ }_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerElse()_x000D_ {_x000D_ return getWorkerElse(this.workerType);_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerElse(String workerType)_x000D_ {_x000D_ /*List<Workman> wklist = new ArrayList<Workman>();_x000D_ if(parallelPatternFlag!=1)_x000D_ {_x000D_ List<String[]> wslist = getWorkersService(host, port, workerType);_x000D_ for(String[] wsinfo:wslist)_x000D_ wklist.add(BeanContext.getWorkerElse(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]));_x000D_ }_x000D_ return wklist.toArray(new Workman[wklist.size()]);*/_x000D_ return getWorkers(host, port, workerType);_x000D_ }_x000D_ _x000D_ protected Workman getWorkerIndex(int index)_x000D_ {_x000D_ return getWorkerIndex(this.workerType, index);_x000D_ }_x000D_ _x000D_ protected Workman getWorkerIndex(String workerType, int index)_x000D_ {_x000D_ //if(parallelPatternFlag!=1)_x000D_ //{_x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ if(index>=0&&index<wslist.size())_x000D_ {_x000D_ String[] wsinfo = wslist.get(index);_x000D_ return BeanContext.getWorkman(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]);_x000D_ }else return null;_x000D_ //}_x000D_ //return null;_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerAll()_x000D_ {_x000D_ return getWorkerAll(this.workerType);_x000D_ }_x000D_ _x000D_ protected Workman[] getWorkerAll(String workerType)_x000D_ {_x000D_ return getWorkers(null, 0, workerType);_x000D_ }_x000D_ _x000D_ private Workman[] getWorkers(String host, int port, String workerType)_x000D_ {_x000D_ //System.out.println(host+":"+port);_x000D_ List<Workman> wklist = new ArrayList<Workman>();_x000D_ if(parallelPatternFlag!=1)_x000D_ {_x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ for(int i=0;i<wslist.size();i++)_x000D_ {_x000D_ String[] wsinfo = wslist.get(i);_x000D_ //System.out.println(wsinfo[0]+":"+wsinfo[1]);_x000D_ if(!wsinfo[0].equals(host)||Integer.parseInt(wsinfo[1])!=port)_x000D_ wklist.add(BeanContext.getWorkman(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]));_x000D_ else_x000D_ selfIndex = i;_x000D_ }_x000D_ }_x000D_ return wklist.toArray(new Workman[wklist.size()]);_x000D_ } _x000D_ _x000D_ protected int getSelfIndex()_x000D_ {_x000D_ if(selfIndex==-1)_x000D_ {_x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ for(int i=0;i<wslist.size();i++)_x000D_ {_x000D_ String[] wsinfo = wslist.get(i);_x000D_ if(wsinfo[0].equals(host)&&Integer.parseInt(wsinfo[1])==port)_x000D_ return i;_x000D_ }_x000D_ }_x000D_ return selfIndex;_x000D_ }_x000D_ _x000D_ protected Workman getWorkerElse(String workerType, String host, int port)_x000D_ {_x000D_ if(this.host.equals(host)&&this.port==port)_x000D_ return null;_x000D_ _x000D_ List<String[]> wslist = getWorkersService(workerType);_x000D_ if(wslist!=null){_x000D_ for(int i=0;i<wslist.size();i++)_x000D_ {_x000D_ String[] wsinfo = wslist.get(i);_x000D_ //System.out.println(wsinfo[0]+":"+wsinfo[1]);_x000D_ _x000D_ if(wsinfo[0].equals(host)&&Integer.parseInt(wsinfo[1])==port)_x000D_ return BeanContext.getWorkman(wsinfo[0], Integer.parseInt(wsinfo[1]), wsinfo[2]);_x000D_ }_x000D_ }_x000D_ return null;_x000D_ }_x000D_ _x000D_ synchronized boolean receiveMaterials(WareHouse inhouse)_x000D_ {_x000D_ return receive(inhouse);_x000D_ }_x000D_ _x000D_ protected boolean receive(WareHouse inhouse)_x000D_ {_x000D_ return true;_x000D_ }_x000D_ _x000D_ protected WareHouse doTask(WareHouse inhouse)_x000D_ {_x000D_ WareHouse outhouse = new WareHouse();_x000D_ return outhouse;_x000D_ }_x000D_ _x000D_ protected boolean isInterrupted(){_x000D_ return _interrupted;_x000D_ }_x000D_ _x000D_ void interrupted(boolean _interrupted){_x000D_ this._interrupted = _interrupted;_x000D_ }_x000D_ _x000D_ public void setWorkerJar(String workerjarname){_x000D_ this.workerjarname = workerjarname;_x000D_ }_x000D_ _x000D_ public String getWorkerJar(){_x000D_ return workerjarname;_x000D_ }_x000D_ _x000D_ void setHost(String host){_x000D_ this.host = host;_x000D_ }_x000D_ _x000D_ String getHost(){_x000D_ return host;_x000D_ }_x000D_ _x000D_ void setWorkerType(String workerType){_x000D_ this.workerType = workerType;_x000D_ }_x000D_ _x000D_ String getWorkerType(){_x000D_ return workerType;_x000D_ }_x000D_ _x000D_ void setPort(int port){_x000D_ this.port = port;_x000D_ }_x000D_ _x000D_ int getPort(){_x000D_ return port;_x000D_ }_x000D_ _x000D_ void setSelfIndex(int selfIndex){_x000D_ this.selfIndex = selfIndex;_x000D_ }_x000D_ _x000D_ /*int getSelfIndex(){_x000D_ <SUF>*/_x000D_ _x000D_ public static void main(String[] args){_x000D_ MigrantWorker mw = new MigrantWorker();_x000D_ //System.out.println(args.length);_x000D_ if(args.length==4)_x000D_ mw.setWorkerJar(args[3]);_x000D_ mw.waitWorking(args[0],Integer.parseInt(args[1]),args[2]);_x000D_ }_x000D_ }
False
2,983
28
3,401
28
3,374
29
3,401
28
3,688
31
false
false
false
false
false
true
3,746
142557_11
/* ScriptsAtom.java * ========================================================================= * This file is originally part of the JMathTeX Library - http://jmathtex.sourceforge.net * * Copyright (C) 2004-2007 Universiteit Gent * Copyright (C) 2009 DENIZET Calixte * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License can be found in the file * LICENSE.txt provided with the source distribution of this program (see * the META-INF directory in the source jar). This license can also be * found on the GNU website at http://www.gnu.org/licenses/gpl.html. * * If you did not receive a copy of the GNU General Public License along * with this program, contact the lead developer, or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * Linking this library statically or dynamically with other modules * is making a combined work based on this library. Thus, the terms * and conditions of the GNU General Public License cover the whole * combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce * an executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under terms * of your choice, provided that you also meet, for each linked independent * module, the terms and conditions of the license of that module. * An independent module is a module which is not derived from or based * on this library. If you modify this library, you may extend this exception * to your version of the library, but you are not obliged to do so. * If you do not wish to do so, delete this exception statement from your * version. * */ /* Modified by Calixte Denizet */ package com.himamis.retex.renderer.share; import java.util.ArrayList; import com.himamis.retex.renderer.share.mhchem.CEEmptyAtom; import com.himamis.retex.renderer.share.serialize.HasTrueBase; /** * An atom representing scripts to be attached to another atom. */ public class ScriptsAtom extends Atom implements HasTrueBase { // base atom private Atom base; // subscript and superscript to be attached to the base (if not null) private Atom subscript; private Atom superscript; private TeXConstants.Align align; public ScriptsAtom(Atom base, Atom sub, Atom sup, TeXConstants.Align align) { this.base = base; subscript = sub; superscript = sup; this.align = align; } public ScriptsAtom(Atom base, Atom sub, Atom sup, boolean left) { this(base, sub, sup, left ? TeXConstants.Align.LEFT : TeXConstants.Align.RIGHT); } public ScriptsAtom(Atom base, Atom sub, Atom sup) { this(base, sub, sup, !(base instanceof CEEmptyAtom)); } @Override public Atom getTrueBase() { return base; } public void setBase(Atom base) { this.base = base; } public void setSup(Atom sup) { superscript = sup; } public void setSub(Atom sub) { subscript = sub; } public void addToSup(Atom a) { if (superscript == null) { superscript = a; } else if (superscript instanceof RowAtom) { ((RowAtom) superscript).add(a); } else { superscript = new RowAtom(superscript, a); } } public void addToSub(Atom a) { if (subscript == null) { subscript = a; } else if (subscript instanceof RowAtom) { ((RowAtom) subscript).add(a); } else { subscript = new RowAtom(subscript, a); } } public Atom getSup() { return superscript; } public Atom getSub() { return subscript; } @Override public Box createBox(TeXEnvironment env) { if (subscript == null && superscript == null) { return base.createBox(env); } else { final Atom trueBase = base.getBase(); if (trueBase instanceof RowAtom && ((RowAtom) trueBase).lookAtLast()) { return createBoxForRowAtom(env); } int style = env.getStyle(); if (base.type_limits == TeXConstants.SCRIPT_LIMITS || (base.type_limits == TeXConstants.SCRIPT_NORMAL && style == TeXConstants.STYLE_DISPLAY)) { return new BigOperatorAtom(base, subscript, superscript) .createBox(env).setAtom(this); } final boolean it = base.setAddItalicCorrection(subscript == null); Box b = base.createBox(env); base.setAddItalicCorrection(it); Box scriptspace = new StrutBox( env.lengthSettings().getLength("scriptspace", env), 0., 0., 0.); TeXFont tf = env.getTeXFont(); HorizontalBox hor = new HorizontalBox(b); FontInfo lastFontId = b.getLastFont(); // if no last font found (whitespace box), use default "mu font" if (lastFontId == null) { lastFontId = TeXFont.MUFONT; } TeXEnvironment subStyle = env.subStyle(); TeXEnvironment supStyle = env.supStyle(); // set delta and preliminary shift-up and shift-down values double delta = 0.; double shiftUp; double shiftDown; if (trueBase instanceof CharAtom) { final CharAtom ca = (CharAtom) trueBase; shiftUp = shiftDown = 0.; CharFont cf = ca.getCharFont(tf); if ((!ca.isMarkedAsTextSymbol() || !tf.hasSpace(cf.fontInfo)) && subscript != null) { delta = tf.getChar(cf, style).getItalic(); } } else { if (trueBase instanceof SymbolAtom && trueBase .getType() == TeXConstants.TYPE_BIG_OPERATOR) { if (trueBase.isMathMode() && trueBase.mustAddItalicCorrection()) { delta = trueBase.getItalic(env); } } shiftUp = b.getHeight() - tf.getSupDrop(supStyle.getStyle()); shiftDown = b.getDepth() + tf.getSubDrop(subStyle.getStyle()); } if (superscript == null) { // only subscript Box x = subscript.createBox(subStyle); // calculate and set shift amount x.setShift( Math.max(Math.max(shiftDown, tf.getSub1(style)), x.getHeight() - 4. * Math .abs(tf.getXHeight(style, lastFontId)) / 5.)); hor.add(x); return hor.setAtom(this); } else { Box x = superscript.createBox(supStyle); double msiz = x.getWidth(); if (subscript != null && align == TeXConstants.Align.RIGHT) { msiz = Math.max(msiz, subscript.createBox(subStyle).getWidth()); } HorizontalBox sup = new HorizontalBox(x, msiz, align); // add scriptspace (constant value!) sup.add(scriptspace); // adjust shift-up double p; if (style == TeXConstants.STYLE_DISPLAY) { p = tf.getSup1(style); } else if (env.crampStyle().getStyle() == style) { p = tf.getSup3(style); } else { p = tf.getSup2(style); } shiftUp = Math.max(Math.max(shiftUp, p), x.getDepth() + Math.abs(tf.getXHeight(style, lastFontId)) / 4.); if (subscript == null) { // only superscript sup.setShift(-shiftUp); hor.add(sup); } else { // both superscript and subscript Box y = subscript.createBox(subStyle); HorizontalBox sub = new HorizontalBox(y, msiz, align); // add scriptspace (constant value!) sub.add(scriptspace); // adjust shift-down shiftDown = Math.max(shiftDown, tf.getSub2(style)); // position both sub- and superscript double drt = tf.getDefaultRuleThickness(style); // space between sub- en double interSpace = shiftUp - x.getDepth() + shiftDown - y.getHeight(); // superscript if (interSpace < 4. * drt) { // too small shiftUp += 4. * drt - interSpace; // set bottom superscript at least 4/5 of X-height // above // baseline double psi = 4. * Math.abs(tf.getXHeight(style, lastFontId)) / 5. - (shiftUp - x.getDepth()); if (psi > 0.) { shiftUp += psi; shiftDown -= psi; } } // create total box VerticalBox vBox = new VerticalBox(); sup.setShift(delta); vBox.add(sup); // recalculate interspace interSpace = shiftUp - x.getDepth() + shiftDown - y.getHeight(); vBox.add(new StrutBox(0., interSpace, 0., 0.)); vBox.add(sub); vBox.setHeight(shiftUp + x.getHeight()); vBox.setDepth(shiftDown + y.getDepth()); hor.add(vBox); } return hor.setAtom(this); } } } private Box createBoxForRowAtom(TeXEnvironment env) { final Atom trueBase = base.getBase(); final RowAtom ra = (RowAtom) trueBase; final Atom last = ra.last(); final Box b = new ScriptsAtom(last, subscript, superscript, align) .createBox(env); final HorizontalBox hb = new HorizontalBox(base.createBox(env)); if (subscript != null) { final double italic = last.getItalic(env); hb.add(new StrutBox(-italic, 0., 0., 0.)); } final ArrayList<Box> c = ((HorizontalBox) b).getChildren(); for (int i = 1; i < c.size(); ++i) { hb.add(c.get(i)); } return hb; } @Override public int getLeftType() { return base.getLeftType(); } @Override public int getRightType() { return base.getRightType(); } @Override public int getLimits() { return base.getLimits(); } }
mstfelg/geosquared
retex/renderer-base/src/main/java/com/himamis/retex/renderer/share/ScriptsAtom.java
3,193
// space between sub- en
line_comment
nl
/* ScriptsAtom.java * ========================================================================= * This file is originally part of the JMathTeX Library - http://jmathtex.sourceforge.net * * Copyright (C) 2004-2007 Universiteit Gent * Copyright (C) 2009 DENIZET Calixte * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License can be found in the file * LICENSE.txt provided with the source distribution of this program (see * the META-INF directory in the source jar). This license can also be * found on the GNU website at http://www.gnu.org/licenses/gpl.html. * * If you did not receive a copy of the GNU General Public License along * with this program, contact the lead developer, or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. * * Linking this library statically or dynamically with other modules * is making a combined work based on this library. Thus, the terms * and conditions of the GNU General Public License cover the whole * combination. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce * an executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under terms * of your choice, provided that you also meet, for each linked independent * module, the terms and conditions of the license of that module. * An independent module is a module which is not derived from or based * on this library. If you modify this library, you may extend this exception * to your version of the library, but you are not obliged to do so. * If you do not wish to do so, delete this exception statement from your * version. * */ /* Modified by Calixte Denizet */ package com.himamis.retex.renderer.share; import java.util.ArrayList; import com.himamis.retex.renderer.share.mhchem.CEEmptyAtom; import com.himamis.retex.renderer.share.serialize.HasTrueBase; /** * An atom representing scripts to be attached to another atom. */ public class ScriptsAtom extends Atom implements HasTrueBase { // base atom private Atom base; // subscript and superscript to be attached to the base (if not null) private Atom subscript; private Atom superscript; private TeXConstants.Align align; public ScriptsAtom(Atom base, Atom sub, Atom sup, TeXConstants.Align align) { this.base = base; subscript = sub; superscript = sup; this.align = align; } public ScriptsAtom(Atom base, Atom sub, Atom sup, boolean left) { this(base, sub, sup, left ? TeXConstants.Align.LEFT : TeXConstants.Align.RIGHT); } public ScriptsAtom(Atom base, Atom sub, Atom sup) { this(base, sub, sup, !(base instanceof CEEmptyAtom)); } @Override public Atom getTrueBase() { return base; } public void setBase(Atom base) { this.base = base; } public void setSup(Atom sup) { superscript = sup; } public void setSub(Atom sub) { subscript = sub; } public void addToSup(Atom a) { if (superscript == null) { superscript = a; } else if (superscript instanceof RowAtom) { ((RowAtom) superscript).add(a); } else { superscript = new RowAtom(superscript, a); } } public void addToSub(Atom a) { if (subscript == null) { subscript = a; } else if (subscript instanceof RowAtom) { ((RowAtom) subscript).add(a); } else { subscript = new RowAtom(subscript, a); } } public Atom getSup() { return superscript; } public Atom getSub() { return subscript; } @Override public Box createBox(TeXEnvironment env) { if (subscript == null && superscript == null) { return base.createBox(env); } else { final Atom trueBase = base.getBase(); if (trueBase instanceof RowAtom && ((RowAtom) trueBase).lookAtLast()) { return createBoxForRowAtom(env); } int style = env.getStyle(); if (base.type_limits == TeXConstants.SCRIPT_LIMITS || (base.type_limits == TeXConstants.SCRIPT_NORMAL && style == TeXConstants.STYLE_DISPLAY)) { return new BigOperatorAtom(base, subscript, superscript) .createBox(env).setAtom(this); } final boolean it = base.setAddItalicCorrection(subscript == null); Box b = base.createBox(env); base.setAddItalicCorrection(it); Box scriptspace = new StrutBox( env.lengthSettings().getLength("scriptspace", env), 0., 0., 0.); TeXFont tf = env.getTeXFont(); HorizontalBox hor = new HorizontalBox(b); FontInfo lastFontId = b.getLastFont(); // if no last font found (whitespace box), use default "mu font" if (lastFontId == null) { lastFontId = TeXFont.MUFONT; } TeXEnvironment subStyle = env.subStyle(); TeXEnvironment supStyle = env.supStyle(); // set delta and preliminary shift-up and shift-down values double delta = 0.; double shiftUp; double shiftDown; if (trueBase instanceof CharAtom) { final CharAtom ca = (CharAtom) trueBase; shiftUp = shiftDown = 0.; CharFont cf = ca.getCharFont(tf); if ((!ca.isMarkedAsTextSymbol() || !tf.hasSpace(cf.fontInfo)) && subscript != null) { delta = tf.getChar(cf, style).getItalic(); } } else { if (trueBase instanceof SymbolAtom && trueBase .getType() == TeXConstants.TYPE_BIG_OPERATOR) { if (trueBase.isMathMode() && trueBase.mustAddItalicCorrection()) { delta = trueBase.getItalic(env); } } shiftUp = b.getHeight() - tf.getSupDrop(supStyle.getStyle()); shiftDown = b.getDepth() + tf.getSubDrop(subStyle.getStyle()); } if (superscript == null) { // only subscript Box x = subscript.createBox(subStyle); // calculate and set shift amount x.setShift( Math.max(Math.max(shiftDown, tf.getSub1(style)), x.getHeight() - 4. * Math .abs(tf.getXHeight(style, lastFontId)) / 5.)); hor.add(x); return hor.setAtom(this); } else { Box x = superscript.createBox(supStyle); double msiz = x.getWidth(); if (subscript != null && align == TeXConstants.Align.RIGHT) { msiz = Math.max(msiz, subscript.createBox(subStyle).getWidth()); } HorizontalBox sup = new HorizontalBox(x, msiz, align); // add scriptspace (constant value!) sup.add(scriptspace); // adjust shift-up double p; if (style == TeXConstants.STYLE_DISPLAY) { p = tf.getSup1(style); } else if (env.crampStyle().getStyle() == style) { p = tf.getSup3(style); } else { p = tf.getSup2(style); } shiftUp = Math.max(Math.max(shiftUp, p), x.getDepth() + Math.abs(tf.getXHeight(style, lastFontId)) / 4.); if (subscript == null) { // only superscript sup.setShift(-shiftUp); hor.add(sup); } else { // both superscript and subscript Box y = subscript.createBox(subStyle); HorizontalBox sub = new HorizontalBox(y, msiz, align); // add scriptspace (constant value!) sub.add(scriptspace); // adjust shift-down shiftDown = Math.max(shiftDown, tf.getSub2(style)); // position both sub- and superscript double drt = tf.getDefaultRuleThickness(style); // space between<SUF> double interSpace = shiftUp - x.getDepth() + shiftDown - y.getHeight(); // superscript if (interSpace < 4. * drt) { // too small shiftUp += 4. * drt - interSpace; // set bottom superscript at least 4/5 of X-height // above // baseline double psi = 4. * Math.abs(tf.getXHeight(style, lastFontId)) / 5. - (shiftUp - x.getDepth()); if (psi > 0.) { shiftUp += psi; shiftDown -= psi; } } // create total box VerticalBox vBox = new VerticalBox(); sup.setShift(delta); vBox.add(sup); // recalculate interspace interSpace = shiftUp - x.getDepth() + shiftDown - y.getHeight(); vBox.add(new StrutBox(0., interSpace, 0., 0.)); vBox.add(sub); vBox.setHeight(shiftUp + x.getHeight()); vBox.setDepth(shiftDown + y.getDepth()); hor.add(vBox); } return hor.setAtom(this); } } } private Box createBoxForRowAtom(TeXEnvironment env) { final Atom trueBase = base.getBase(); final RowAtom ra = (RowAtom) trueBase; final Atom last = ra.last(); final Box b = new ScriptsAtom(last, subscript, superscript, align) .createBox(env); final HorizontalBox hb = new HorizontalBox(base.createBox(env)); if (subscript != null) { final double italic = last.getItalic(env); hb.add(new StrutBox(-italic, 0., 0., 0.)); } final ArrayList<Box> c = ((HorizontalBox) b).getChildren(); for (int i = 1; i < c.size(); ++i) { hb.add(c.get(i)); } return hb; } @Override public int getLeftType() { return base.getLeftType(); } @Override public int getRightType() { return base.getRightType(); } @Override public int getLimits() { return base.getLimits(); } }
False
2,515
6
2,869
6
2,833
6
2,869
6
3,657
6
false
false
false
false
false
true
3,772
80554_26
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.util.Date; /** * The MedicationDispense class records detailed information about the provision of a supply of a medication * with the intention that it is subsequently consumed by a patient (usually in response to a prescription). * * @see <a href="https://www.hl7.org/fhir/medicationdispense.html"> * https://www.hl7.org/fhir/medicationdispense.html * </a> * @since 2.6 */ @Entity @Table(name = "medication_dispense") public class MedicationDispense extends BaseFormRecordableOpenmrsData { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "medication_dispense_id") private Integer medicationDispenseId; /** * FHIR:subject * Patient for whom the medication is intended */ @ManyToOne(optional = false) @JoinColumn(name = "patient_id") private Patient patient; /** * FHIR:context * Encounter when the dispensing event occurred */ @ManyToOne(optional = true) @JoinColumn(name = "encounter_id") private Encounter encounter; /** * FHIR:medication.medicationCodeableConcept * Corresponds to drugOrder.concept */ @ManyToOne(optional = false) @JoinColumn(name = "concept") private Concept concept; /** * FHIR:medication.reference(Medication) * Corresponds to drugOrder.drug */ @ManyToOne(optional = true) @JoinColumn(name = "drug_id") private Drug drug; /** * FHIR:location * Where the dispensed event occurred */ @ManyToOne(optional = true) @JoinColumn(name = "location_id") private Location location; /** * FHIR:performer.actor with null for performer.function. * Per <a href="https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer"> * https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer * </a>specification, It should be assumed that the actor is the dispenser of the medication */ @ManyToOne(optional = true) @JoinColumn(name = "dispenser") private Provider dispenser; /** * FHIR:authorizingPrescription * The drug order that led to this dispensing event; * note that authorizing prescription maps to a "MedicationRequest" FHIR resource */ @ManyToOne(optional = true) @JoinColumn(name = "drug_order_id") private DrugOrder drugOrder; /** * FHIR:status * @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status.html"> * https://www.hl7.org/fhir/valueset-medicationdispense-status.html * </a> * i.e. preparation, in-progress, cancelled, on-hold, completed, entered-in-error, stopped, declined, unknown */ @ManyToOne(optional = false) @JoinColumn(name = "status") private Concept status; /** * FHIR:statusReason.statusReasonCodeableConcept * @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html"> * https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html * </a> * i.e "Stock Out" */ @ManyToOne(optional = true) @JoinColumn(name = "status_reason") private Concept statusReason; /** * FHIR:type.codeableConcept * @see <a href="https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html"> * https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html * </a> for potential example concepts * i.e. "Refill" and "Partial Fill" */ @ManyToOne(optional = true) @JoinColumn(name = "type") private Concept type; /** * FHIR:quantity.value * Relates to drugOrder.quantity */ @Column(name = "quantity") private Double quantity; /** * FHIR:quantity.unit and/or quanity.code * Relates to drugOrder.quantityUnits */ @ManyToOne(optional = true) @JoinColumn(name = "quantity_units") private Concept quantityUnits; /** * FHIR:dosageInstructions.doseAndRate.dose.doseQuantity * Relates to drugOrder.dose */ @Column(name = "dose") private Double dose; /** * FHIR:dosageInstructions.doseAndRate.dose.quantity.unit and/or code * Relates to drugOrder.doseUnits */ @ManyToOne(optional = true) @JoinColumn(name = "dose_units") private Concept doseUnits; /** * FHIR:dosageInstructions.route * Relates to drugOrder.route */ @ManyToOne(optional = true) @JoinColumn(name = "route") private Concept route; /** * FHIR:DosageInstructions.timing.repeat.frequency+period+periodUnit * @see <a href="https://build.fhir.org/datatypes.html#Timing">https://build.fhir.org/datatypes.html#Timing</a> * Note that we will continue to map this as a single "frequency" concept, although it doesn't map well to FHIR, * to make consistent with DrugOrder in OpenMRS * Relates to drugOrder.frequency */ @ManyToOne(optional = true) @JoinColumn(name = "frequency") private OrderFrequency frequency; /** * FHIR:DosageInstructions.AsNeeded.asNeededBoolean * Relates to drugOrder.asNeeded */ @Column(name = "as_needed") private Boolean asNeeded; /** * FHIR:DosageInstructions.patientInstructions * Relates to drugOrder.dosingInstructions */ @Column(name = "dosing_instructions", length=65535) private String dosingInstructions; /** * FHIR:whenPrepared * From FHIR: "When product was packaged and reviewed" */ @Column(name = "date_prepared") private Date datePrepared; /** * FHIR:whenHandedOver * From FHIR: "When product was given out" */ @Column(name = "date_handed_over") private Date dateHandedOver; /** * FHIR:substitution.wasSubstituted * True/false whether a substitution was made during this dispense event */ @Column(name = "was_substituted") private Boolean wasSubstituted; /** * FHIR:substitution.type * @see <a href="https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html"> * https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html * </a> */ @ManyToOne(optional = true) @JoinColumn(name = "substitution_type") private Concept substitutionType; /** * FHIR:substitution.reason * @see <a href="https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html"> * https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html * </a> */ @ManyToOne(optional = true) @JoinColumn(name = "substitution_reason") private Concept substitutionReason; public MedicationDispense() { } /** * @see BaseOpenmrsObject#getId() */ @Override public Integer getId() { return getMedicationDispenseId(); } /** * @see BaseOpenmrsObject#setId(Integer) */ @Override public void setId(Integer id) { setMedicationDispenseId(id); } public Integer getMedicationDispenseId() { return medicationDispenseId; } public void setMedicationDispenseId(Integer medicationDispenseId) { this.medicationDispenseId = medicationDispenseId; } public Patient getPatient() { return patient; } public void setPatient(Patient patient) { this.patient = patient; } public Encounter getEncounter() { return encounter; } public void setEncounter(Encounter encounter) { this.encounter = encounter; } public Concept getConcept() { return concept; } public void setConcept(Concept concept) { this.concept = concept; } public Drug getDrug() { return drug; } public void setDrug(Drug drug) { this.drug = drug; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public Provider getDispenser() { return dispenser; } public void setDispenser(Provider dispenser) { this.dispenser = dispenser; } public DrugOrder getDrugOrder() { return drugOrder; } public void setDrugOrder(DrugOrder drugOrder) { this.drugOrder = drugOrder; } public Concept getStatus() { return status; } public void setStatus(Concept status) { this.status = status; } public Concept getStatusReason() { return statusReason; } public void setStatusReason(Concept statusReason) { this.statusReason = statusReason; } public Concept getType() { return type; } public void setType(Concept type) { this.type = type; } public Double getQuantity() { return quantity; } public void setQuantity(Double quantity) { this.quantity = quantity; } public Concept getQuantityUnits() { return quantityUnits; } public void setQuantityUnits(Concept quantityUnits) { this.quantityUnits = quantityUnits; } public Double getDose() { return dose; } public void setDose(Double dose) { this.dose = dose; } public Concept getDoseUnits() { return doseUnits; } public void setDoseUnits(Concept doseUnits) { this.doseUnits = doseUnits; } public Concept getRoute() { return route; } public void setRoute(Concept route) { this.route = route; } public OrderFrequency getFrequency() { return frequency; } public void setFrequency(OrderFrequency frequency) { this.frequency = frequency; } public Boolean getAsNeeded() { return asNeeded; } public void setAsNeeded(Boolean asNeeded) { this.asNeeded = asNeeded; } public String getDosingInstructions() { return dosingInstructions; } public void setDosingInstructions(String dosingInstructions) { this.dosingInstructions = dosingInstructions; } public Date getDatePrepared() { return datePrepared; } public void setDatePrepared(Date datePrepared) { this.datePrepared = datePrepared; } public Date getDateHandedOver() { return dateHandedOver; } public void setDateHandedOver(Date dateHandedOver) { this.dateHandedOver = dateHandedOver; } public Boolean getWasSubstituted() { return wasSubstituted; } public void setWasSubstituted(Boolean wasSubstituted) { this.wasSubstituted = wasSubstituted; } public Concept getSubstitutionType() { return substitutionType; } public void setSubstitutionType(Concept substitutionType) { this.substitutionType = substitutionType; } public Concept getSubstitutionReason() { return substitutionReason; } public void setSubstitutionReason(Concept substitutionReason) { this.substitutionReason = substitutionReason; } }
nareshmanojari1/openmrs-core
api/src/main/java/org/openmrs/MedicationDispense.java
3,720
/** * @see BaseOpenmrsObject#setId(Integer) */
block_comment
nl
/** * This Source Code Form is subject to the terms of the Mozilla Public License, * v. 2.0. If a copy of the MPL was not distributed with this file, You can * obtain one at http://mozilla.org/MPL/2.0/. OpenMRS is also distributed under * the terms of the Healthcare Disclaimer located at http://openmrs.org/license. * * Copyright (C) OpenMRS Inc. OpenMRS is a registered trademark and the OpenMRS * graphic logo is a trademark of OpenMRS Inc. */ package org.openmrs; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import java.util.Date; /** * The MedicationDispense class records detailed information about the provision of a supply of a medication * with the intention that it is subsequently consumed by a patient (usually in response to a prescription). * * @see <a href="https://www.hl7.org/fhir/medicationdispense.html"> * https://www.hl7.org/fhir/medicationdispense.html * </a> * @since 2.6 */ @Entity @Table(name = "medication_dispense") public class MedicationDispense extends BaseFormRecordableOpenmrsData { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "medication_dispense_id") private Integer medicationDispenseId; /** * FHIR:subject * Patient for whom the medication is intended */ @ManyToOne(optional = false) @JoinColumn(name = "patient_id") private Patient patient; /** * FHIR:context * Encounter when the dispensing event occurred */ @ManyToOne(optional = true) @JoinColumn(name = "encounter_id") private Encounter encounter; /** * FHIR:medication.medicationCodeableConcept * Corresponds to drugOrder.concept */ @ManyToOne(optional = false) @JoinColumn(name = "concept") private Concept concept; /** * FHIR:medication.reference(Medication) * Corresponds to drugOrder.drug */ @ManyToOne(optional = true) @JoinColumn(name = "drug_id") private Drug drug; /** * FHIR:location * Where the dispensed event occurred */ @ManyToOne(optional = true) @JoinColumn(name = "location_id") private Location location; /** * FHIR:performer.actor with null for performer.function. * Per <a href="https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer"> * https://www.hl7.org/fhir/medicationdispense-definitions.html#MedicationDispense.performer * </a>specification, It should be assumed that the actor is the dispenser of the medication */ @ManyToOne(optional = true) @JoinColumn(name = "dispenser") private Provider dispenser; /** * FHIR:authorizingPrescription * The drug order that led to this dispensing event; * note that authorizing prescription maps to a "MedicationRequest" FHIR resource */ @ManyToOne(optional = true) @JoinColumn(name = "drug_order_id") private DrugOrder drugOrder; /** * FHIR:status * @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status.html"> * https://www.hl7.org/fhir/valueset-medicationdispense-status.html * </a> * i.e. preparation, in-progress, cancelled, on-hold, completed, entered-in-error, stopped, declined, unknown */ @ManyToOne(optional = false) @JoinColumn(name = "status") private Concept status; /** * FHIR:statusReason.statusReasonCodeableConcept * @see <a href="https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html"> * https://www.hl7.org/fhir/valueset-medicationdispense-status-reason.html * </a> * i.e "Stock Out" */ @ManyToOne(optional = true) @JoinColumn(name = "status_reason") private Concept statusReason; /** * FHIR:type.codeableConcept * @see <a href="https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html"> * https://www.hl7.org/fhir/v3/ActPharmacySupplyType/vs.html * </a> for potential example concepts * i.e. "Refill" and "Partial Fill" */ @ManyToOne(optional = true) @JoinColumn(name = "type") private Concept type; /** * FHIR:quantity.value * Relates to drugOrder.quantity */ @Column(name = "quantity") private Double quantity; /** * FHIR:quantity.unit and/or quanity.code * Relates to drugOrder.quantityUnits */ @ManyToOne(optional = true) @JoinColumn(name = "quantity_units") private Concept quantityUnits; /** * FHIR:dosageInstructions.doseAndRate.dose.doseQuantity * Relates to drugOrder.dose */ @Column(name = "dose") private Double dose; /** * FHIR:dosageInstructions.doseAndRate.dose.quantity.unit and/or code * Relates to drugOrder.doseUnits */ @ManyToOne(optional = true) @JoinColumn(name = "dose_units") private Concept doseUnits; /** * FHIR:dosageInstructions.route * Relates to drugOrder.route */ @ManyToOne(optional = true) @JoinColumn(name = "route") private Concept route; /** * FHIR:DosageInstructions.timing.repeat.frequency+period+periodUnit * @see <a href="https://build.fhir.org/datatypes.html#Timing">https://build.fhir.org/datatypes.html#Timing</a> * Note that we will continue to map this as a single "frequency" concept, although it doesn't map well to FHIR, * to make consistent with DrugOrder in OpenMRS * Relates to drugOrder.frequency */ @ManyToOne(optional = true) @JoinColumn(name = "frequency") private OrderFrequency frequency; /** * FHIR:DosageInstructions.AsNeeded.asNeededBoolean * Relates to drugOrder.asNeeded */ @Column(name = "as_needed") private Boolean asNeeded; /** * FHIR:DosageInstructions.patientInstructions * Relates to drugOrder.dosingInstructions */ @Column(name = "dosing_instructions", length=65535) private String dosingInstructions; /** * FHIR:whenPrepared * From FHIR: "When product was packaged and reviewed" */ @Column(name = "date_prepared") private Date datePrepared; /** * FHIR:whenHandedOver * From FHIR: "When product was given out" */ @Column(name = "date_handed_over") private Date dateHandedOver; /** * FHIR:substitution.wasSubstituted * True/false whether a substitution was made during this dispense event */ @Column(name = "was_substituted") private Boolean wasSubstituted; /** * FHIR:substitution.type * @see <a href="https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html"> * https://www.hl7.org/fhir/v3/ActSubstanceAdminSubstitutionCode/vs.html * </a> */ @ManyToOne(optional = true) @JoinColumn(name = "substitution_type") private Concept substitutionType; /** * FHIR:substitution.reason * @see <a href="https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html"> * https://www.hl7.org/fhir/v3/SubstanceAdminSubstitutionReason/vs.html * </a> */ @ManyToOne(optional = true) @JoinColumn(name = "substitution_reason") private Concept substitutionReason; public MedicationDispense() { } /** * @see BaseOpenmrsObject#getId() */ @Override public Integer getId() { return getMedicationDispenseId(); } /** * @see BaseOpenmrsObject#setId(Integer) <SUF>*/ @Override public void setId(Integer id) { setMedicationDispenseId(id); } public Integer getMedicationDispenseId() { return medicationDispenseId; } public void setMedicationDispenseId(Integer medicationDispenseId) { this.medicationDispenseId = medicationDispenseId; } public Patient getPatient() { return patient; } public void setPatient(Patient patient) { this.patient = patient; } public Encounter getEncounter() { return encounter; } public void setEncounter(Encounter encounter) { this.encounter = encounter; } public Concept getConcept() { return concept; } public void setConcept(Concept concept) { this.concept = concept; } public Drug getDrug() { return drug; } public void setDrug(Drug drug) { this.drug = drug; } public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } public Provider getDispenser() { return dispenser; } public void setDispenser(Provider dispenser) { this.dispenser = dispenser; } public DrugOrder getDrugOrder() { return drugOrder; } public void setDrugOrder(DrugOrder drugOrder) { this.drugOrder = drugOrder; } public Concept getStatus() { return status; } public void setStatus(Concept status) { this.status = status; } public Concept getStatusReason() { return statusReason; } public void setStatusReason(Concept statusReason) { this.statusReason = statusReason; } public Concept getType() { return type; } public void setType(Concept type) { this.type = type; } public Double getQuantity() { return quantity; } public void setQuantity(Double quantity) { this.quantity = quantity; } public Concept getQuantityUnits() { return quantityUnits; } public void setQuantityUnits(Concept quantityUnits) { this.quantityUnits = quantityUnits; } public Double getDose() { return dose; } public void setDose(Double dose) { this.dose = dose; } public Concept getDoseUnits() { return doseUnits; } public void setDoseUnits(Concept doseUnits) { this.doseUnits = doseUnits; } public Concept getRoute() { return route; } public void setRoute(Concept route) { this.route = route; } public OrderFrequency getFrequency() { return frequency; } public void setFrequency(OrderFrequency frequency) { this.frequency = frequency; } public Boolean getAsNeeded() { return asNeeded; } public void setAsNeeded(Boolean asNeeded) { this.asNeeded = asNeeded; } public String getDosingInstructions() { return dosingInstructions; } public void setDosingInstructions(String dosingInstructions) { this.dosingInstructions = dosingInstructions; } public Date getDatePrepared() { return datePrepared; } public void setDatePrepared(Date datePrepared) { this.datePrepared = datePrepared; } public Date getDateHandedOver() { return dateHandedOver; } public void setDateHandedOver(Date dateHandedOver) { this.dateHandedOver = dateHandedOver; } public Boolean getWasSubstituted() { return wasSubstituted; } public void setWasSubstituted(Boolean wasSubstituted) { this.wasSubstituted = wasSubstituted; } public Concept getSubstitutionType() { return substitutionType; } public void setSubstitutionType(Concept substitutionType) { this.substitutionType = substitutionType; } public Concept getSubstitutionReason() { return substitutionReason; } public void setSubstitutionReason(Concept substitutionReason) { this.substitutionReason = substitutionReason; } }
False
2,738
16
3,290
17
3,278
18
3,290
17
3,952
20
false
false
false
false
false
true
1,499
111087_4
package main; public class Chip { private final String name; private double saldo; private boolean ingeCheckt = false; private final int[] cordsIngeCheckt = new int[2]; public Chip(String name, double saldo) { this.name = name; this.saldo = saldo; } // getters /** * Get name * * @return name */ public String getName() { return name; } /** * get saldo rounded to 2 decimals * * @return saldo rounded to 2 decimals */ public double getSaldo() { return Math.round(saldo * 100) / 100.0; } /** * get cordsIngeCheckt * * @param index 0 = x, 1 = y * @return cordsIngeCheckt */ public int getCordsIngeCheckt(int index) { return cordsIngeCheckt[index]; } /** * get ingecheckt * * @return ingecheckt */ public boolean isIngeCheckt() { return ingeCheckt; } // setters /** * verander saldo * * @param amount om toe te voegen */ public void changeSaldo(double amount) { this.saldo += amount; } /** * check chip uit */ public void checkUit(double cost) { ingeCheckt = false; changeSaldo(-cost); } /** * Slaat de coördinaten op waar er in is gecheckt en zet ingecheckt op true * * @param x coördinaat * @param y coördinaat */ public void incheckPlaats(int x, int y) { cordsIngeCheckt[0] = x; cordsIngeCheckt[1] = y; ingeCheckt = true; } }
Rutger505/OV-System
OVChipkaart/src/main/Chip.java
540
/** * verander saldo * * @param amount om toe te voegen */
block_comment
nl
package main; public class Chip { private final String name; private double saldo; private boolean ingeCheckt = false; private final int[] cordsIngeCheckt = new int[2]; public Chip(String name, double saldo) { this.name = name; this.saldo = saldo; } // getters /** * Get name * * @return name */ public String getName() { return name; } /** * get saldo rounded to 2 decimals * * @return saldo rounded to 2 decimals */ public double getSaldo() { return Math.round(saldo * 100) / 100.0; } /** * get cordsIngeCheckt * * @param index 0 = x, 1 = y * @return cordsIngeCheckt */ public int getCordsIngeCheckt(int index) { return cordsIngeCheckt[index]; } /** * get ingecheckt * * @return ingecheckt */ public boolean isIngeCheckt() { return ingeCheckt; } // setters /** * verander saldo <SUF>*/ public void changeSaldo(double amount) { this.saldo += amount; } /** * check chip uit */ public void checkUit(double cost) { ingeCheckt = false; changeSaldo(-cost); } /** * Slaat de coördinaten op waar er in is gecheckt en zet ingecheckt op true * * @param x coördinaat * @param y coördinaat */ public void incheckPlaats(int x, int y) { cordsIngeCheckt[0] = x; cordsIngeCheckt[1] = y; ingeCheckt = true; } }
True
454
22
464
22
500
22
464
22
548
25
false
false
false
false
false
true
3,320
153726_1
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openapitools.client.model.InvalidParams; /** * BadRequestFoutberichtAllOf */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class BadRequestFoutberichtAllOf { public static final String SERIALIZED_NAME_INVALID_PARAMS = "invalidParams"; @SerializedName(SERIALIZED_NAME_INVALID_PARAMS) private List<InvalidParams> invalidParams = null; public BadRequestFoutberichtAllOf invalidParams(List<InvalidParams> invalidParams) { this.invalidParams = invalidParams; return this; } public BadRequestFoutberichtAllOf addInvalidParamsItem(InvalidParams invalidParamsItem) { if (this.invalidParams == null) { this.invalidParams = new ArrayList<>(); } this.invalidParams.add(invalidParamsItem); return this; } /** * Foutmelding per fout in een parameter. Alle gevonden fouten worden één keer teruggemeld. * @return invalidParams **/ @javax.annotation.Nullable @ApiModelProperty(value = "Foutmelding per fout in een parameter. Alle gevonden fouten worden één keer teruggemeld.") public List<InvalidParams> getInvalidParams() { return invalidParams; } public void setInvalidParams(List<InvalidParams> invalidParams) { this.invalidParams = invalidParams; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BadRequestFoutberichtAllOf badRequestFoutberichtAllOf = (BadRequestFoutberichtAllOf) o; return Objects.equals(this.invalidParams, badRequestFoutberichtAllOf.invalidParams); } @Override public int hashCode() { return Objects.hash(invalidParams); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BadRequestFoutberichtAllOf {\n"); sb.append(" invalidParams: ").append(toIndentedString(invalidParams)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
kad-henger/Haal-Centraal-BRK-bevragen
code/java/src/main/java/org/openapitools/client/model/BadRequestFoutberichtAllOf.java
1,041
/** * Foutmelding per fout in een parameter. Alle gevonden fouten worden één keer teruggemeld. * @return invalidParams **/
block_comment
nl
/* * Kadaster - BRK-Bevragen API * D.m.v. deze toepassing worden meerdere, korte bevragingen op de Basis Registratie Kadaster beschikbaar gesteld. Deze toepassing betreft het verstrekken van Kadastrale Onroerende Zaak informatie. * * The version of the OpenAPI document: 1.1.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.client.model; import java.util.Objects; import java.util.Arrays; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.openapitools.client.model.InvalidParams; /** * BadRequestFoutberichtAllOf */ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-07-16T15:31:15.936+02:00[Europe/Amsterdam]") public class BadRequestFoutberichtAllOf { public static final String SERIALIZED_NAME_INVALID_PARAMS = "invalidParams"; @SerializedName(SERIALIZED_NAME_INVALID_PARAMS) private List<InvalidParams> invalidParams = null; public BadRequestFoutberichtAllOf invalidParams(List<InvalidParams> invalidParams) { this.invalidParams = invalidParams; return this; } public BadRequestFoutberichtAllOf addInvalidParamsItem(InvalidParams invalidParamsItem) { if (this.invalidParams == null) { this.invalidParams = new ArrayList<>(); } this.invalidParams.add(invalidParamsItem); return this; } /** * Foutmelding per fout<SUF>*/ @javax.annotation.Nullable @ApiModelProperty(value = "Foutmelding per fout in een parameter. Alle gevonden fouten worden één keer teruggemeld.") public List<InvalidParams> getInvalidParams() { return invalidParams; } public void setInvalidParams(List<InvalidParams> invalidParams) { this.invalidParams = invalidParams; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BadRequestFoutberichtAllOf badRequestFoutberichtAllOf = (BadRequestFoutberichtAllOf) o; return Objects.equals(this.invalidParams, badRequestFoutberichtAllOf.invalidParams); } @Override public int hashCode() { return Objects.hash(invalidParams); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class BadRequestFoutberichtAllOf {\n"); sb.append(" invalidParams: ").append(toIndentedString(invalidParams)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
True
801
36
921
38
930
34
921
38
1,060
43
false
false
false
false
false
true
3,759
73625_17
import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.EventHandler; import javafx.scene.input.ScrollEvent; import javafx.util.Duration; public class BalController implements Runnable{ private Bal bal; private BalView balView; private ControlePaneelNoord noordpaneel; private Timeline animation; private boolean doorgaan_thread = true; private double dt; private double valhoogte; private Thread draad; public BalController(Bal bal, BalView balview, ValBewegingPaneel valBewegingPaneel, ControlePaneelNoord noordpaneel) { //constructor van balcontroller this.bal = bal; this.balView = balview; this.noordpaneel = noordpaneel; } /** * Invoked when the mouse wheel is rotated. * * @param e * @see MouseWheelEvent */ @SuppressWarnings({ "deprecation", "static-access" }) @Override public void run() { //runnable voor de thread draad. Wordt gebruikt om de y as //positie te monitoren en zet de animatie stop zodra de y as over de gezete y waarde in noordpane is (default 100) while (doorgaan_thread) { if(this.bal.getY() < valhoogte) { //doe niets, hou de thread actief try { draad.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else{ //Y is groter dan valhoogte, dus stop de animatie this.animation.stop(); draad.stop(); } } } public EventHandler<ScrollEvent> getOnScrollEventHandler() { System.out.println("hey"); return onScrollEventHandler; } private EventHandler<ScrollEvent> onScrollEventHandler = new EventHandler<ScrollEvent>() { @Override public void handle(ScrollEvent event) { bal.setY(bal.getY()+1); event.consume(); } }; public void pleaseStart() { //start functie gelinkt aan de animatie button //reset de bal zodat de animatie altijd op y = 0 begint this.bal.reset(); //delta tijd is de invoer van noordpaneel delta tijd (default 20) this.dt = this.noordpaneel.getDt(); //valhoogte is de invoer van noordpaneel ybereik (default 100) this.valhoogte = this.noordpaneel.getYbereik(); //maak de animatie aan & laat deze bal.adjust() uitvoeren met een update voor de view voor oneidige periode animation = new Timeline(); animation.setCycleCount(Timeline.INDEFINITE); final KeyFrame kf = new KeyFrame(Duration.millis(this.dt), e -> this.bal.adjust(this.dt)); final KeyFrame kf2 = new KeyFrame(Duration.millis(this.dt), e -> this.balView.adjustBal()); animation.getKeyFrames().addAll(kf,kf2); //start de animatie animation.play(); //zet de buttons op disable zodat de waardes niet meer kunnen worden gewijzigd this.noordpaneel.setDisable(true); //maak de controle thread aan draad = new Thread(this); //daemon op true zodat de thread stopt bij het sluiten van de applicatie draad.setDaemon(true); draad.start(); } @SuppressWarnings("deprecation") public void pleaseStop() { //stop functie gelinkt aan de stop button this.noordpaneel.setDisable(false); //me stop de animatie en kill de thread this.animation.stop(); draad.stop(); } }
mvankampen/FreeFall
src/BalController.java
1,108
//me stop de animatie en kill de thread
line_comment
nl
import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.event.EventHandler; import javafx.scene.input.ScrollEvent; import javafx.util.Duration; public class BalController implements Runnable{ private Bal bal; private BalView balView; private ControlePaneelNoord noordpaneel; private Timeline animation; private boolean doorgaan_thread = true; private double dt; private double valhoogte; private Thread draad; public BalController(Bal bal, BalView balview, ValBewegingPaneel valBewegingPaneel, ControlePaneelNoord noordpaneel) { //constructor van balcontroller this.bal = bal; this.balView = balview; this.noordpaneel = noordpaneel; } /** * Invoked when the mouse wheel is rotated. * * @param e * @see MouseWheelEvent */ @SuppressWarnings({ "deprecation", "static-access" }) @Override public void run() { //runnable voor de thread draad. Wordt gebruikt om de y as //positie te monitoren en zet de animatie stop zodra de y as over de gezete y waarde in noordpane is (default 100) while (doorgaan_thread) { if(this.bal.getY() < valhoogte) { //doe niets, hou de thread actief try { draad.sleep(20); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else{ //Y is groter dan valhoogte, dus stop de animatie this.animation.stop(); draad.stop(); } } } public EventHandler<ScrollEvent> getOnScrollEventHandler() { System.out.println("hey"); return onScrollEventHandler; } private EventHandler<ScrollEvent> onScrollEventHandler = new EventHandler<ScrollEvent>() { @Override public void handle(ScrollEvent event) { bal.setY(bal.getY()+1); event.consume(); } }; public void pleaseStart() { //start functie gelinkt aan de animatie button //reset de bal zodat de animatie altijd op y = 0 begint this.bal.reset(); //delta tijd is de invoer van noordpaneel delta tijd (default 20) this.dt = this.noordpaneel.getDt(); //valhoogte is de invoer van noordpaneel ybereik (default 100) this.valhoogte = this.noordpaneel.getYbereik(); //maak de animatie aan & laat deze bal.adjust() uitvoeren met een update voor de view voor oneidige periode animation = new Timeline(); animation.setCycleCount(Timeline.INDEFINITE); final KeyFrame kf = new KeyFrame(Duration.millis(this.dt), e -> this.bal.adjust(this.dt)); final KeyFrame kf2 = new KeyFrame(Duration.millis(this.dt), e -> this.balView.adjustBal()); animation.getKeyFrames().addAll(kf,kf2); //start de animatie animation.play(); //zet de buttons op disable zodat de waardes niet meer kunnen worden gewijzigd this.noordpaneel.setDisable(true); //maak de controle thread aan draad = new Thread(this); //daemon op true zodat de thread stopt bij het sluiten van de applicatie draad.setDaemon(true); draad.start(); } @SuppressWarnings("deprecation") public void pleaseStop() { //stop functie gelinkt aan de stop button this.noordpaneel.setDisable(false); //me stop<SUF> this.animation.stop(); draad.stop(); } }
True
880
10
957
10
988
10
957
10
1,131
10
false
false
false
false
false
true
4,289
201440_14
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord value this.yCoord = yCoord; // initialize yCoord value this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
sethmenghi/boolean-forest
src/Objects/Owl.java
884
// initialize yCoord value
line_comment
nl
/** * OWL CLASS * * DESCRIPTION: * The Owl class is an object that declares the x- and y-coordinates of * an Owl object and the name of the Owl. * * SOURCES: * */ package Objects; public class Owl { // Public static final members of Owl class: public static final String BOB = "BOB"; // dimensions of image file are 158 x 159 public static final String ALICE = "ALICE"; // dimensions of image file are 158 x 159 public static final String CHLOE = "CHLOE"; // dimensions of image file are 87 x 88 public static final String DAVID = "DAVID"; // dimensions of image file are 106 x 107 // Private members of the Owl class: private int xCoord; // x-coordinate of Owl private int yCoord; // y-coordinate of Owl private String name; // name of Owl /** * DEFAULT CONSTRUCTOR: The constructor calls overloaded constructor * with x- and y-coordinates of 0 and the name BOB. * @param none */ public Owl() { this(0, 0, BOB); // call overridden Owl(int, int, name) } /** * OVERLOADED CONSTRUCTOR: Instantiates an Owl object and initializes the x- * and y-coordinates and name members. * @param xCoord * @param yCoord * @param name */ public Owl(int xCoord, int yCoord, String name) { this.xCoord = xCoord; // initialize xCoord value this.yCoord = yCoord; // initialize yCoord<SUF> this.name = name; // initialize name value } /** * SETTER: Sets the xCoord of the Owl. * @param xCoord */ public void setXCoord(int xCoord) { this.xCoord = xCoord; // set xCoord value of Owl } /** * SETTER: Sets the yCoord of the Owl. * @param yCoord */ public void setYCoord(int yCoord) { this.yCoord = yCoord; // set yCoord value of Owl } /** * SETTER: Sets the name of the Owl. * @param name */ public void setOwlName(String name) { this.name = name; // set name value of Owl } /** * GETTER: Returns the xCoord of the Owl. * @return xCoord */ public int getXCoord() { return xCoord; // return xCoord value of Owl } /** * GETTER: Returns the yCoord of the Owl. * @return yCoord */ public int getYCoord() { return yCoord; // return yCoord value of Owl } /** * GETTER: Returns the name of the Owl. * @return name */ public String getOwlName() { return name; // return name value of Owl } }
False
714
5
794
5
778
5
794
5
1,005
6
false
false
false
false
false
true
607
15645_5
package Classes;_x000D_ _x000D_ import java.security.MessageDigest;_x000D_ import java.security.NoSuchAlgorithmException;_x000D_ import java.util.Date;_x000D_ _x000D_ public class Account extends Persoon {_x000D_ _x000D_ //Attributes_x000D_ private String wachtwoord;_x000D_ private Date gbdatum;_x000D_ private String telnr;_x000D_ _x000D_ //Constructors_x000D_ public Account(int i, String vn, String tv, String an, String pc, String hnr, String toev, String em, String ww, String gbd, String tnr) {_x000D_ super(i, vn, tv, an, pc, hnr, toev, em);_x000D_ setWachtwoord(ww);_x000D_ setGbdatum(gbd);_x000D_ telnr = tnr;_x000D_ }_x000D_ _x000D_ //Getters_x000D_ public String getWachtwoord() {_x000D_ return wachtwoord;_x000D_ }_x000D_ _x000D_ public Date getGbdatum() {_x000D_ return gbdatum;_x000D_ }_x000D_ _x000D_ public String getTelnr() {_x000D_ return telnr;_x000D_ }_x000D_ _x000D_ //Setters_x000D_ public void setGbdatum(String gbd) {_x000D_ //Hier komt een methode die een MySQL Date omzet naar een Java Date_x000D_ }_x000D_ _x000D_ public void setTelnr(String tnr) {_x000D_ telnr = tnr;_x000D_ }_x000D_ _x000D_ public void setWachtwoord(String ww) {_x000D_ try {_x000D_ //MessageDigest met algoritme SHA-512_x000D_ MessageDigest md = MessageDigest.getInstance("SHA-512");_x000D_ //Wachtwoord wordt omgezet tot bytes en toegevoegd aan de MessageDigest_x000D_ md.update(ww.getBytes());_x000D_ //Hasht het (in bytes omgezette) wachtwoord en stopt die in de variabele bytes_x000D_ byte[] bytes = md.digest();_x000D_ //Bytes worden hier omgezet naar hexadecimalen_x000D_ StringBuilder sb = new StringBuilder();_x000D_ for (int i = 0; i < bytes.length; i++) {_x000D_ sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));_x000D_ }_x000D_ //De hexadecimale hash wordt opgeslagen in het attribuut wachtwoord_x000D_ wachtwoord = sb.toString();_x000D_ } catch (NoSuchAlgorithmException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ //Methods_x000D_ }_x000D_
GijsAlb/HSR01
HSR01JavaFX/src/Classes/Account.java
612
//De hexadecimale hash wordt opgeslagen in het attribuut wachtwoord_x000D_
line_comment
nl
package Classes;_x000D_ _x000D_ import java.security.MessageDigest;_x000D_ import java.security.NoSuchAlgorithmException;_x000D_ import java.util.Date;_x000D_ _x000D_ public class Account extends Persoon {_x000D_ _x000D_ //Attributes_x000D_ private String wachtwoord;_x000D_ private Date gbdatum;_x000D_ private String telnr;_x000D_ _x000D_ //Constructors_x000D_ public Account(int i, String vn, String tv, String an, String pc, String hnr, String toev, String em, String ww, String gbd, String tnr) {_x000D_ super(i, vn, tv, an, pc, hnr, toev, em);_x000D_ setWachtwoord(ww);_x000D_ setGbdatum(gbd);_x000D_ telnr = tnr;_x000D_ }_x000D_ _x000D_ //Getters_x000D_ public String getWachtwoord() {_x000D_ return wachtwoord;_x000D_ }_x000D_ _x000D_ public Date getGbdatum() {_x000D_ return gbdatum;_x000D_ }_x000D_ _x000D_ public String getTelnr() {_x000D_ return telnr;_x000D_ }_x000D_ _x000D_ //Setters_x000D_ public void setGbdatum(String gbd) {_x000D_ //Hier komt een methode die een MySQL Date omzet naar een Java Date_x000D_ }_x000D_ _x000D_ public void setTelnr(String tnr) {_x000D_ telnr = tnr;_x000D_ }_x000D_ _x000D_ public void setWachtwoord(String ww) {_x000D_ try {_x000D_ //MessageDigest met algoritme SHA-512_x000D_ MessageDigest md = MessageDigest.getInstance("SHA-512");_x000D_ //Wachtwoord wordt omgezet tot bytes en toegevoegd aan de MessageDigest_x000D_ md.update(ww.getBytes());_x000D_ //Hasht het (in bytes omgezette) wachtwoord en stopt die in de variabele bytes_x000D_ byte[] bytes = md.digest();_x000D_ //Bytes worden hier omgezet naar hexadecimalen_x000D_ StringBuilder sb = new StringBuilder();_x000D_ for (int i = 0; i < bytes.length; i++) {_x000D_ sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));_x000D_ }_x000D_ //De hexadecimale<SUF> wachtwoord = sb.toString();_x000D_ } catch (NoSuchAlgorithmException e) {_x000D_ e.printStackTrace();_x000D_ }_x000D_ }_x000D_ _x000D_ //Methods_x000D_ }_x000D_
True
891
26
950
30
975
25
950
30
1,049
27
false
false
false
false
false
true
420
154301_3
/* * @(#)PlafRes_nl.java 12.oct 2007 Versión 2.2 * * El contenido de este fichero está sujeto a la Licencia Pública openXpertya versión 1.1 (LPO) * en tanto en cuanto forme parte íntegra del total del producto denominado: openXpertya, solución * empresarial global , y siempre según los términos de dicha licencia LPO. * Una copia íntegra de dicha licencia está incluida con todas las fuentes del producto. * Partes del código son copyRight (c) 2002-2007 de Ingeniería Informática Integrada S.L., otras * partes son copyRight (c) 2003-2007 de Consultoría y Soporte en Redes y Tecnologías de la * Información S.L., otras partes son copyRight (c) 2005-2006 de Dataware Sistemas S.L., otras son * copyright (c) 2005-2006 de Indeos Consultoría S.L., otras son copyright (c) 2005-2006 de Disytel * Servicios Digitales S.A., y otras partes son adaptadas, ampliadas, traducidas, revisadas y/o * mejoradas a partir de código original de terceros, recogidos en el ADDENDUM A, sección 3 (A.3) * de dicha licencia LPO, y si dicho código es extraido como parte del total del producto, estará * sujeto a su respectiva licencia original. * Más información en http://www.openxpertya.org/ayuda/Licencia.html */ package org.compiere.plaf; import java.util.ListResourceBundle; /** * Translation Texts for Look & Feel * * @author Comunidad de Desarrollo openXpertya * *Basado en Codigo Original Modificado, Revisado y Optimizado de: * * Eldir Tomassen * @version $Id: PlafRes_nl.java,v 1.6 2005/03/11 20:34:36 jjanke Exp $ */ public class PlafRes_nl extends ListResourceBundle { /** The data */ static final Object[][] contents = new String[][] { { "BackColType", "Achtergrond Kleur Type" }, { "BackColType_Flat", "Egaal" }, { "BackColType_Gradient", "Verloop" }, { "BackColType_Lines", "Lijnen" }, { "BackColType_Texture", "Reli�f" }, // { "LookAndFeelEditor", "Look & Feel Editor" }, { "LookAndFeel", "Look & Feel" }, { "Theme", "Thema" }, { "EditCompiereTheme", "OpenXpertya Theme Bewerken" }, { "SetDefault", "Standaard Achtergrond" }, { "SetDefaultColor", "Achtergrond Kleur" }, { "ColorBlind", "Kleur Verloop" }, { "Example", "Voorbeeld" }, { "Reset", "Ongedaan maken" }, { "OK", "OK" }, { "Cancel", "Annuleren" }, // { "CompiereThemeEditor", "OpenXpertya Thema Editor" }, { "MetalColors", "Metaal Kleuren" }, { "CompiereColors", "OpenXpertya Kleuren" }, { "CompiereFonts", "OpenXpertya Lettertypen" }, { "Primary1Info", "Shaduw, Schijdingsteken" }, { "Primary1", "Primair 1" }, { "Primary2Info", "Schijdingslijn, Geselecteerd Menu" }, { "Primary2", "Primair 2" }, { "Primary3Info", "Tabel Geselecteerde Rij, Geselecteerde Tekst, ToolTip Achtergrond" }, { "Primary3", "Primair 3" }, { "Secondary1Info", "Begrenzing Lijnen" }, { "Secondary1", "Secundair 2" }, { "Secondary2Info", "Inactieve Tabs, Geselecteerde Velden, Inactieve Begrenzing + Tekst" }, { "Secondary2", "Secundait 2" }, { "Secondary3Info", "Achtergrond" }, { "Secondary3", "Secondair 3" }, // { "ControlFontInfo", "Beheer Lettertype" }, { "ControlFont", "Label Lettertype" }, { "SystemFontInfo", "Tool Tip, Boom Iconen" }, { "SystemFont", "Systeem Letterype" }, { "UserFontInfo", "Door Gebruiker ingevoerde gegevens" }, { "UserFont", "Veld Lettertype" }, // { "SmallFontInfo", "Reports" }, { "SmallFont", "Klein Lettertype" }, { "WindowTitleFont", "Titel Lettertype" }, { "MenuFont", "Menu Lettertype" }, // { "MandatoryInfo", "Verplicht Veld Achtergrond" }, { "Mandatory", "Verplicht" }, { "ErrorInfo", "Foutief Veld Achtergrond" }, { "Error", "Foutief" }, { "InfoInfo", "Informatie Veld Achtergrond" }, { "Info", "Informatie" }, { "WhiteInfo", "Lijnen" }, { "White", "Wit" }, { "BlackInfo", "Lijnen, Tekst" }, { "Black", "Zwart" }, { "InactiveInfo", "Inactief Veld Achtergrond" }, { "Inactive", "Inactief" }, { "TextOKInfo", "OK Tekst Voorgrond" }, { "TextOK", "Tekst - OK" }, { "TextIssueInfo", "Foutief Tekst Voorgrond" }, { "TextIssue", "Tekst - Foutief" }, // { "FontChooser", "Lettertype Selecteren" }, { "Fonts", "Lettertypen" }, { "Plain", "Normaal" }, { "Italic", "Schuin" }, { "Bold", "Vet" }, { "BoldItalic", "Vet & Schuin" }, { "Name", "Naam" }, { "Size", "Formaat" }, { "Style", "Stijl" }, { "TestString", "Dit is een test! De thema brwoser is bezig. 12,3456.78 LetterLOne = l1 LetterOZero = O0" }, { "FontString", "Lettertype" }, // { "CompiereColorEditor", "OpenXpertya Kleur Editor" }, { "CompiereType", "Kleur Type" }, { "GradientUpperColor", "Verloop Bovenste Kleur" }, { "GradientLowerColor", "Verloop Onderste Kleur" }, { "GradientStart", "Verloop Start" }, { "GradientDistance", "Verloop Afstand" }, { "TextureURL", "Textuur URL" }, { "TextureAlpha", "Textuur Alpha" }, { "TextureTaintColor", "Textuur Taint Kleur" }, { "LineColor", "Lijn Kleur" }, { "LineBackColor", "Achtergrond Kleur" }, { "LineWidth", "Lijn Breedte" }, { "LineDistance", "Lijn Reikwijdte" }, { "FlatColor", "Egale Kleur" } }; //~--- get methods -------------------------------------------------------- /** * Get Contents * @return contents */ public Object[][] getContents() { return contents; } } // Res /* * @(#)PlafRes_nl.java 02.jul 2007 * * Fin del fichero PlafRes_nl.java * * Versión 2.2 - Fundesle (2007) * */ //~ Formateado de acuerdo a Sistema Fundesle en 02.jul 2007
Disytel-Consulting-SA/libertya
looks/src/org/compiere/plaf/PlafRes_nl.java
2,040
//~--- get methods --------------------------------------------------------
line_comment
nl
/* * @(#)PlafRes_nl.java 12.oct 2007 Versión 2.2 * * El contenido de este fichero está sujeto a la Licencia Pública openXpertya versión 1.1 (LPO) * en tanto en cuanto forme parte íntegra del total del producto denominado: openXpertya, solución * empresarial global , y siempre según los términos de dicha licencia LPO. * Una copia íntegra de dicha licencia está incluida con todas las fuentes del producto. * Partes del código son copyRight (c) 2002-2007 de Ingeniería Informática Integrada S.L., otras * partes son copyRight (c) 2003-2007 de Consultoría y Soporte en Redes y Tecnologías de la * Información S.L., otras partes son copyRight (c) 2005-2006 de Dataware Sistemas S.L., otras son * copyright (c) 2005-2006 de Indeos Consultoría S.L., otras son copyright (c) 2005-2006 de Disytel * Servicios Digitales S.A., y otras partes son adaptadas, ampliadas, traducidas, revisadas y/o * mejoradas a partir de código original de terceros, recogidos en el ADDENDUM A, sección 3 (A.3) * de dicha licencia LPO, y si dicho código es extraido como parte del total del producto, estará * sujeto a su respectiva licencia original. * Más información en http://www.openxpertya.org/ayuda/Licencia.html */ package org.compiere.plaf; import java.util.ListResourceBundle; /** * Translation Texts for Look & Feel * * @author Comunidad de Desarrollo openXpertya * *Basado en Codigo Original Modificado, Revisado y Optimizado de: * * Eldir Tomassen * @version $Id: PlafRes_nl.java,v 1.6 2005/03/11 20:34:36 jjanke Exp $ */ public class PlafRes_nl extends ListResourceBundle { /** The data */ static final Object[][] contents = new String[][] { { "BackColType", "Achtergrond Kleur Type" }, { "BackColType_Flat", "Egaal" }, { "BackColType_Gradient", "Verloop" }, { "BackColType_Lines", "Lijnen" }, { "BackColType_Texture", "Reli�f" }, // { "LookAndFeelEditor", "Look & Feel Editor" }, { "LookAndFeel", "Look & Feel" }, { "Theme", "Thema" }, { "EditCompiereTheme", "OpenXpertya Theme Bewerken" }, { "SetDefault", "Standaard Achtergrond" }, { "SetDefaultColor", "Achtergrond Kleur" }, { "ColorBlind", "Kleur Verloop" }, { "Example", "Voorbeeld" }, { "Reset", "Ongedaan maken" }, { "OK", "OK" }, { "Cancel", "Annuleren" }, // { "CompiereThemeEditor", "OpenXpertya Thema Editor" }, { "MetalColors", "Metaal Kleuren" }, { "CompiereColors", "OpenXpertya Kleuren" }, { "CompiereFonts", "OpenXpertya Lettertypen" }, { "Primary1Info", "Shaduw, Schijdingsteken" }, { "Primary1", "Primair 1" }, { "Primary2Info", "Schijdingslijn, Geselecteerd Menu" }, { "Primary2", "Primair 2" }, { "Primary3Info", "Tabel Geselecteerde Rij, Geselecteerde Tekst, ToolTip Achtergrond" }, { "Primary3", "Primair 3" }, { "Secondary1Info", "Begrenzing Lijnen" }, { "Secondary1", "Secundair 2" }, { "Secondary2Info", "Inactieve Tabs, Geselecteerde Velden, Inactieve Begrenzing + Tekst" }, { "Secondary2", "Secundait 2" }, { "Secondary3Info", "Achtergrond" }, { "Secondary3", "Secondair 3" }, // { "ControlFontInfo", "Beheer Lettertype" }, { "ControlFont", "Label Lettertype" }, { "SystemFontInfo", "Tool Tip, Boom Iconen" }, { "SystemFont", "Systeem Letterype" }, { "UserFontInfo", "Door Gebruiker ingevoerde gegevens" }, { "UserFont", "Veld Lettertype" }, // { "SmallFontInfo", "Reports" }, { "SmallFont", "Klein Lettertype" }, { "WindowTitleFont", "Titel Lettertype" }, { "MenuFont", "Menu Lettertype" }, // { "MandatoryInfo", "Verplicht Veld Achtergrond" }, { "Mandatory", "Verplicht" }, { "ErrorInfo", "Foutief Veld Achtergrond" }, { "Error", "Foutief" }, { "InfoInfo", "Informatie Veld Achtergrond" }, { "Info", "Informatie" }, { "WhiteInfo", "Lijnen" }, { "White", "Wit" }, { "BlackInfo", "Lijnen, Tekst" }, { "Black", "Zwart" }, { "InactiveInfo", "Inactief Veld Achtergrond" }, { "Inactive", "Inactief" }, { "TextOKInfo", "OK Tekst Voorgrond" }, { "TextOK", "Tekst - OK" }, { "TextIssueInfo", "Foutief Tekst Voorgrond" }, { "TextIssue", "Tekst - Foutief" }, // { "FontChooser", "Lettertype Selecteren" }, { "Fonts", "Lettertypen" }, { "Plain", "Normaal" }, { "Italic", "Schuin" }, { "Bold", "Vet" }, { "BoldItalic", "Vet & Schuin" }, { "Name", "Naam" }, { "Size", "Formaat" }, { "Style", "Stijl" }, { "TestString", "Dit is een test! De thema brwoser is bezig. 12,3456.78 LetterLOne = l1 LetterOZero = O0" }, { "FontString", "Lettertype" }, // { "CompiereColorEditor", "OpenXpertya Kleur Editor" }, { "CompiereType", "Kleur Type" }, { "GradientUpperColor", "Verloop Bovenste Kleur" }, { "GradientLowerColor", "Verloop Onderste Kleur" }, { "GradientStart", "Verloop Start" }, { "GradientDistance", "Verloop Afstand" }, { "TextureURL", "Textuur URL" }, { "TextureAlpha", "Textuur Alpha" }, { "TextureTaintColor", "Textuur Taint Kleur" }, { "LineColor", "Lijn Kleur" }, { "LineBackColor", "Achtergrond Kleur" }, { "LineWidth", "Lijn Breedte" }, { "LineDistance", "Lijn Reikwijdte" }, { "FlatColor", "Egale Kleur" } }; //~--- get<SUF> /** * Get Contents * @return contents */ public Object[][] getContents() { return contents; } } // Res /* * @(#)PlafRes_nl.java 02.jul 2007 * * Fin del fichero PlafRes_nl.java * * Versión 2.2 - Fundesle (2007) * */ //~ Formateado de acuerdo a Sistema Fundesle en 02.jul 2007
False
1,865
7
1,996
6
1,811
9
1,996
6
2,079
10
false
false
false
false
false
true
2,517
165352_1
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.client.common; import ilarkesto.core.scope.Scope; import ilarkesto.gwt.client.AWidget; import scrum.client.Dao; import scrum.client.ScrumGwtApplication; import scrum.client.ScrumScopeManager; import scrum.client.admin.Auth; import scrum.client.admin.User; import scrum.client.i18n.Localizer; import scrum.client.project.Project; import scrum.client.sprint.Sprint; import scrum.client.workspace.Ui; public abstract class AScrumWidget extends AWidget { // --- helper --- // protected static final Navigator getNavigator() { // return Scope.get().getComponent(Navigator.class); // } protected static final User getCurrentUser() { assert getAuth().isUserLoggedIn(); return getAuth().getUser(); } public static final Localizer getLocalizer() { return Scope.get().getComponent(Localizer.class); } protected static final Auth getAuth() { return Scope.get().getComponent(Auth.class); } protected static final Project getCurrentProject() { assert ScrumScopeManager.isProjectScope(); return ScrumScopeManager.getProject(); } protected static final Sprint getCurrentSprint() { return getCurrentProject().getCurrentSprint(); } protected static final Ui getUi() { return Scope.get().getComponent(Ui.class); } protected static final ScrumGwtApplication getApp() { return (ScrumGwtApplication) Scope.get().getComponent("app"); } protected static final Dao getDao() { return Dao.get(); } }
dbuos/kunagi
src/main/java/scrum/client/common/AScrumWidget.java
656
// --- helper ---
line_comment
nl
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.client.common; import ilarkesto.core.scope.Scope; import ilarkesto.gwt.client.AWidget; import scrum.client.Dao; import scrum.client.ScrumGwtApplication; import scrum.client.ScrumScopeManager; import scrum.client.admin.Auth; import scrum.client.admin.User; import scrum.client.i18n.Localizer; import scrum.client.project.Project; import scrum.client.sprint.Sprint; import scrum.client.workspace.Ui; public abstract class AScrumWidget extends AWidget { // --- helper<SUF> // protected static final Navigator getNavigator() { // return Scope.get().getComponent(Navigator.class); // } protected static final User getCurrentUser() { assert getAuth().isUserLoggedIn(); return getAuth().getUser(); } public static final Localizer getLocalizer() { return Scope.get().getComponent(Localizer.class); } protected static final Auth getAuth() { return Scope.get().getComponent(Auth.class); } protected static final Project getCurrentProject() { assert ScrumScopeManager.isProjectScope(); return ScrumScopeManager.getProject(); } protected static final Sprint getCurrentSprint() { return getCurrentProject().getCurrentSprint(); } protected static final Ui getUi() { return Scope.get().getComponent(Ui.class); } protected static final ScrumGwtApplication getApp() { return (ScrumGwtApplication) Scope.get().getComponent("app"); } protected static final Dao getDao() { return Dao.get(); } }
False
497
4
601
4
578
4
601
4
692
4
false
false
false
false
false
true
1,735
114087_2
package bussimulator; import java.io.Console; import com.thoughtworks.xstream.XStream; import bussimulator.Halte.Positie; public class Bus { private Bedrijven bedrijf; private Lijnen lijn; private int halteNummer; private int totVolgendeHalte; private int richting; private boolean bijHalte; private String busID; Bus(Lijnen lijn, Bedrijven bedrijf, int richting) { this.lijn = lijn; this.bedrijf = bedrijf; this.richting = richting; this.halteNummer = -1; this.totVolgendeHalte = 0; this.bijHalte = false; this.busID = "Niet gestart"; } public void setbusID(int starttijd) { this.busID = starttijd + lijn.name() + richting; } public void naarVolgendeHalte() { Positie volgendeHalte = lijn.getHalte(halteNummer + richting).getPositie(); totVolgendeHalte = lijn.getHalte(halteNummer).afstand(volgendeHalte); } public boolean halteBereikt() { halteNummer += richting; bijHalte = true; if ((halteNummer >= lijn.getLengte() - 1) || (halteNummer == 0)) { System.out.printf("Bus %s (%s) heeft eindpunt (halte %s, richting %d) bereikt.%n", lijn.name(), this.bedrijf, lijn.getHalte(halteNummer), lijn.getRichting(halteNummer) * richting); return true; } else { System.out.printf("Bus %s heeft halte %s, richting %d bereikt.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer) * richting); naarVolgendeHalte(); } return false; } public void start() { halteNummer = (richting == 1) ? 0 : lijn.getLengte() - 1; System.out.printf("Bus %s is vertrokken van halte %s in richting %d.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer) * richting); naarVolgendeHalte(); } public boolean move() { boolean eindpuntBereikt = false; bijHalte = false; if (halteNummer == -1) { start(); } else { totVolgendeHalte--; if (totVolgendeHalte == 0) { eindpuntBereikt = halteBereikt(); } } return eindpuntBereikt; } public void sendETAs(int nu) { int i = 0; Bericht bericht = new Bericht(lijn.name(), bedrijf.name(), busID, nu); if (bijHalte) { ETA eta = new ETA(lijn.getHalte(halteNummer).name(), lijn.getRichting(halteNummer) * richting, 0); bericht.ETAs.add(eta); } Positie eerstVolgende = lijn.getHalte(halteNummer + richting).getPositie(); int tijdNaarHalte = totVolgendeHalte + nu; for (i = halteNummer + richting; !(i >= lijn.getLengte()) && !(i < 0); i = i + richting) { tijdNaarHalte += lijn.getHalte(i).afstand(eerstVolgende); ETA eta = new ETA(lijn.getHalte(i).name(), lijn.getRichting(i) * richting, tijdNaarHalte); // System.out.println(bericht.lijnNaam + " naar halte" + eta.halteNaam + " t=" + // tijdNaarHalte); bericht.ETAs.add(eta); eerstVolgende = lijn.getHalte(i).getPositie(); } bericht.eindpunt = lijn.getHalte(i - richting).name(); sendBericht(bericht); } public void sendLastETA(int nu) { Bericht bericht = new Bericht(lijn.name(), bedrijf.name(), busID, nu); String eindpunt = lijn.getHalte(halteNummer).name(); ETA eta = new ETA(eindpunt, lijn.getRichting(halteNummer) * richting, 0); bericht.ETAs.add(eta); bericht.eindpunt = eindpunt; sendBericht(bericht); } /** * Convert the message to XML and send to the producer. * * @param bericht */ public void sendBericht(Bericht bericht) { // Gebruik XStream om het binnengekomen bericht om te zetten // naar een XML bestand (String) XStream xstream = new XStream(); // Zorg er voor dat de XML-tags niet het volledige pad van de xstream.alias("Bericht", Bericht.class); xstream.alias("ETA", ETA.class); // Maak de XML String aan en verstuur het bericht String xml = xstream.toXML(bericht); Producer producer = new Producer(); producer.sendBericht(xml); } }
ThowV/4.2-eai
Simulator/bussimulator/Bus.java
1,475
// Gebruik XStream om het binnengekomen bericht om te zetten
line_comment
nl
package bussimulator; import java.io.Console; import com.thoughtworks.xstream.XStream; import bussimulator.Halte.Positie; public class Bus { private Bedrijven bedrijf; private Lijnen lijn; private int halteNummer; private int totVolgendeHalte; private int richting; private boolean bijHalte; private String busID; Bus(Lijnen lijn, Bedrijven bedrijf, int richting) { this.lijn = lijn; this.bedrijf = bedrijf; this.richting = richting; this.halteNummer = -1; this.totVolgendeHalte = 0; this.bijHalte = false; this.busID = "Niet gestart"; } public void setbusID(int starttijd) { this.busID = starttijd + lijn.name() + richting; } public void naarVolgendeHalte() { Positie volgendeHalte = lijn.getHalte(halteNummer + richting).getPositie(); totVolgendeHalte = lijn.getHalte(halteNummer).afstand(volgendeHalte); } public boolean halteBereikt() { halteNummer += richting; bijHalte = true; if ((halteNummer >= lijn.getLengte() - 1) || (halteNummer == 0)) { System.out.printf("Bus %s (%s) heeft eindpunt (halte %s, richting %d) bereikt.%n", lijn.name(), this.bedrijf, lijn.getHalte(halteNummer), lijn.getRichting(halteNummer) * richting); return true; } else { System.out.printf("Bus %s heeft halte %s, richting %d bereikt.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer) * richting); naarVolgendeHalte(); } return false; } public void start() { halteNummer = (richting == 1) ? 0 : lijn.getLengte() - 1; System.out.printf("Bus %s is vertrokken van halte %s in richting %d.%n", lijn.name(), lijn.getHalte(halteNummer), lijn.getRichting(halteNummer) * richting); naarVolgendeHalte(); } public boolean move() { boolean eindpuntBereikt = false; bijHalte = false; if (halteNummer == -1) { start(); } else { totVolgendeHalte--; if (totVolgendeHalte == 0) { eindpuntBereikt = halteBereikt(); } } return eindpuntBereikt; } public void sendETAs(int nu) { int i = 0; Bericht bericht = new Bericht(lijn.name(), bedrijf.name(), busID, nu); if (bijHalte) { ETA eta = new ETA(lijn.getHalte(halteNummer).name(), lijn.getRichting(halteNummer) * richting, 0); bericht.ETAs.add(eta); } Positie eerstVolgende = lijn.getHalte(halteNummer + richting).getPositie(); int tijdNaarHalte = totVolgendeHalte + nu; for (i = halteNummer + richting; !(i >= lijn.getLengte()) && !(i < 0); i = i + richting) { tijdNaarHalte += lijn.getHalte(i).afstand(eerstVolgende); ETA eta = new ETA(lijn.getHalte(i).name(), lijn.getRichting(i) * richting, tijdNaarHalte); // System.out.println(bericht.lijnNaam + " naar halte" + eta.halteNaam + " t=" + // tijdNaarHalte); bericht.ETAs.add(eta); eerstVolgende = lijn.getHalte(i).getPositie(); } bericht.eindpunt = lijn.getHalte(i - richting).name(); sendBericht(bericht); } public void sendLastETA(int nu) { Bericht bericht = new Bericht(lijn.name(), bedrijf.name(), busID, nu); String eindpunt = lijn.getHalte(halteNummer).name(); ETA eta = new ETA(eindpunt, lijn.getRichting(halteNummer) * richting, 0); bericht.ETAs.add(eta); bericht.eindpunt = eindpunt; sendBericht(bericht); } /** * Convert the message to XML and send to the producer. * * @param bericht */ public void sendBericht(Bericht bericht) { // Gebruik XStream<SUF> // naar een XML bestand (String) XStream xstream = new XStream(); // Zorg er voor dat de XML-tags niet het volledige pad van de xstream.alias("Bericht", Bericht.class); xstream.alias("ETA", ETA.class); // Maak de XML String aan en verstuur het bericht String xml = xstream.toXML(bericht); Producer producer = new Producer(); producer.sendBericht(xml); } }
True
1,304
19
1,504
19
1,270
13
1,504
19
1,630
18
false
false
false
false
false
true
2,625
152013_11
/* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package examples; import io.vertx.core.buffer.Buffer; import io.vertx.core.parsetools.JsonParser; import io.vertx.core.parsetools.RecordParser; /** * Example using the record parser. */ public class ParseToolsExamples { public void recordParserExample1() { final RecordParser parser = RecordParser.newDelimited("\n", h -> { System.out.println(h.toString()); }); parser.handle(Buffer.buffer("HELLO\nHOW ARE Y")); parser.handle(Buffer.buffer("OU?\nI AM")); parser.handle(Buffer.buffer("DOING OK")); parser.handle(Buffer.buffer("\n")); } public void recordParserExample2() { RecordParser.newFixed(4, h -> { System.out.println(h.toString()); }); } public void jsonParserExample1() { JsonParser parser = JsonParser.newParser(); // Set handlers for various events parser.handler(event -> { switch (event.type()) { case START_OBJECT: // Start an objet break; case END_OBJECT: // End an objet break; case START_ARRAY: // Start an array break; case END_ARRAY: // End an array break; case VALUE: // Handle a value String field = event.fieldName(); if (field != null) { // In an object } else { // In an array or top level if (event.isString()) { } else { // ... } } break; } }); } public void jsonParserExample2() { JsonParser parser = JsonParser.newParser(); // start array event // start object event // "firstName":"Bob" event parser.handle(Buffer.buffer("[{\"firstName\":\"Bob\",")); // "lastName":"Morane" event // end object event parser.handle(Buffer.buffer("\"lastName\":\"Morane\"},")); // start object event // "firstName":"Luke" event // "lastName":"Lucky" event // end object event parser.handle(Buffer.buffer("{\"firstName\":\"Luke\",\"lastName\":\"Lucky\"}")); // end array event parser.handle(Buffer.buffer("]")); // Always call end parser.end(); } public void jsonParserExample3() { JsonParser parser = JsonParser.newParser(); parser.objectValueMode(); parser.handler(event -> { switch (event.type()) { case START_ARRAY: // Start the array break; case END_ARRAY: // End the array break; case VALUE: // Handle each object break; } }); parser.handle(Buffer.buffer("[{\"firstName\":\"Bob\"},\"lastName\":\"Morane\"),...]")); parser.end(); } public void jsonParserExample4() { JsonParser parser = JsonParser.newParser(); parser.handler(event -> { // Start the object switch (event.type()) { case START_OBJECT: // Set object value mode to handle each entry, from now on the parser won't emit start object events parser.objectValueMode(); break; case VALUE: // Handle each object // Get the field in which this object was parsed String id = event.fieldName(); System.out.println("User with id " + id + " : " + event.value()); break; case END_OBJECT: // Set the object event mode so the parser emits start/end object events again parser.objectEventMode(); break; } }); parser.handle(Buffer.buffer("{\"39877483847\":{\"firstName\":\"Bob\"},\"lastName\":\"Morane\"),...}")); parser.end(); } public void jsonParserExample5() { JsonParser parser = JsonParser.newParser(); parser.handler(event -> { // Start the object switch (event.type()) { case START_OBJECT: // Set array value mode to handle each entry, from now on the parser won't emit start array events parser.arrayValueMode(); break; case VALUE: // Handle each array // Get the field in which this object was parsed System.out.println("Value : " + event.value()); break; case END_OBJECT: // Set the array event mode so the parser emits start/end object events again parser.arrayEventMode(); break; } }); parser.handle(Buffer.buffer("[0,1,2,3,4,...]")); parser.end(); } private static class User { private String firstName; private String lastName; } public void jsonParserExample6(JsonParser parser) { parser.handler(event -> { // Handle each object // Get the field in which this object was parsed String id = event.fieldName(); User user = event.mapTo(User.class); System.out.println("User with id " + id + " : " + user.firstName + " " + user.lastName); }); } public void jsonParserExample7() { JsonParser parser = JsonParser.newParser(); parser.exceptionHandler(err -> { // Catch any parsing or decoding error }); } }
eclipse-vertx/vert.x
src/main/java/examples/ParseToolsExamples.java
1,627
// start object event
line_comment
nl
/* * Copyright (c) 2011-2019 Contributors to the Eclipse Foundation * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 * which is available at https://www.apache.org/licenses/LICENSE-2.0. * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 */ package examples; import io.vertx.core.buffer.Buffer; import io.vertx.core.parsetools.JsonParser; import io.vertx.core.parsetools.RecordParser; /** * Example using the record parser. */ public class ParseToolsExamples { public void recordParserExample1() { final RecordParser parser = RecordParser.newDelimited("\n", h -> { System.out.println(h.toString()); }); parser.handle(Buffer.buffer("HELLO\nHOW ARE Y")); parser.handle(Buffer.buffer("OU?\nI AM")); parser.handle(Buffer.buffer("DOING OK")); parser.handle(Buffer.buffer("\n")); } public void recordParserExample2() { RecordParser.newFixed(4, h -> { System.out.println(h.toString()); }); } public void jsonParserExample1() { JsonParser parser = JsonParser.newParser(); // Set handlers for various events parser.handler(event -> { switch (event.type()) { case START_OBJECT: // Start an objet break; case END_OBJECT: // End an objet break; case START_ARRAY: // Start an array break; case END_ARRAY: // End an array break; case VALUE: // Handle a value String field = event.fieldName(); if (field != null) { // In an object } else { // In an array or top level if (event.isString()) { } else { // ... } } break; } }); } public void jsonParserExample2() { JsonParser parser = JsonParser.newParser(); // start array event // start object<SUF> // "firstName":"Bob" event parser.handle(Buffer.buffer("[{\"firstName\":\"Bob\",")); // "lastName":"Morane" event // end object event parser.handle(Buffer.buffer("\"lastName\":\"Morane\"},")); // start object event // "firstName":"Luke" event // "lastName":"Lucky" event // end object event parser.handle(Buffer.buffer("{\"firstName\":\"Luke\",\"lastName\":\"Lucky\"}")); // end array event parser.handle(Buffer.buffer("]")); // Always call end parser.end(); } public void jsonParserExample3() { JsonParser parser = JsonParser.newParser(); parser.objectValueMode(); parser.handler(event -> { switch (event.type()) { case START_ARRAY: // Start the array break; case END_ARRAY: // End the array break; case VALUE: // Handle each object break; } }); parser.handle(Buffer.buffer("[{\"firstName\":\"Bob\"},\"lastName\":\"Morane\"),...]")); parser.end(); } public void jsonParserExample4() { JsonParser parser = JsonParser.newParser(); parser.handler(event -> { // Start the object switch (event.type()) { case START_OBJECT: // Set object value mode to handle each entry, from now on the parser won't emit start object events parser.objectValueMode(); break; case VALUE: // Handle each object // Get the field in which this object was parsed String id = event.fieldName(); System.out.println("User with id " + id + " : " + event.value()); break; case END_OBJECT: // Set the object event mode so the parser emits start/end object events again parser.objectEventMode(); break; } }); parser.handle(Buffer.buffer("{\"39877483847\":{\"firstName\":\"Bob\"},\"lastName\":\"Morane\"),...}")); parser.end(); } public void jsonParserExample5() { JsonParser parser = JsonParser.newParser(); parser.handler(event -> { // Start the object switch (event.type()) { case START_OBJECT: // Set array value mode to handle each entry, from now on the parser won't emit start array events parser.arrayValueMode(); break; case VALUE: // Handle each array // Get the field in which this object was parsed System.out.println("Value : " + event.value()); break; case END_OBJECT: // Set the array event mode so the parser emits start/end object events again parser.arrayEventMode(); break; } }); parser.handle(Buffer.buffer("[0,1,2,3,4,...]")); parser.end(); } private static class User { private String firstName; private String lastName; } public void jsonParserExample6(JsonParser parser) { parser.handler(event -> { // Handle each object // Get the field in which this object was parsed String id = event.fieldName(); User user = event.mapTo(User.class); System.out.println("User with id " + id + " : " + user.firstName + " " + user.lastName); }); } public void jsonParserExample7() { JsonParser parser = JsonParser.newParser(); parser.exceptionHandler(err -> { // Catch any parsing or decoding error }); } }
False
1,217
4
1,327
4
1,466
4
1,327
4
1,597
4
false
false
false
false
false
true
3,096
47496_1
package uz.emv.sam.v1.db.tables.xml.zip; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uz.emv.sam.v1.db.tables.xml.InputStreamProvider; import uz.emv.sam.v1.db.tables.xml.InputStreamProviderFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Created by bdcuyp0 on 15-6-2016. */ public class ZipInputStreamProviderFactory implements InputStreamProviderFactory { private static final Logger LOG = LoggerFactory.getLogger(ZipInputStreamProviderFactory.class); private final byte[] zip; private final String suffix; public ZipInputStreamProviderFactory(final InputStream stream, final String suffix) { this.zip = copyToByteArray(stream); //LOG.info(new String(zip)); this.suffix = suffix; } private byte[] copyToByteArray(final InputStream stream) { try { return IOUtils.toByteArray(stream); } catch (IOException e) { throw new RuntimeException(e); } } @Override @NotNull public InputStreamProvider getInputStreamProvider(@NotNull final String samTableName) { final Pair<Map<String, Object>, byte[]> metaDataAndBytes = findBytes(samTableName, zip, suffix); if (metaDataAndBytes == null) { throw new RuntimeException("Could not find table " + samTableName + " in zipped inputstream with suffix " + suffix); } return new ByteArrayInputStreamProvider(metaDataAndBytes); } @Nullable private Pair<Map<String, Object>, byte[]> findBytes(@NotNull final String samTableName, final byte[] zip, final String suffix) { final List<Pair<Map<String, Object>, byte[]>> partialMatches = new ArrayList<Pair<Map<String, Object>, byte[]>>(); ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(zip)); ZipEntry entry = null; Pair<Map<String, Object>, byte[]> selected = null; try { entry = zipInputStream.getNextEntry(); while (entry != null) { Map<String, Object> metaData = new HashMap<String, Object>(); String version = parseVersion(entry); metaData.put("version", version); metaData.put("name", samTableName); if (suffix == null || entry.getName().endsWith(suffix)) { if (entry.getName().startsWith(samTableName + "#")) { selected = Pair.of(metaData, IOUtils.toByteArray(zipInputStream)); break; } else if (entry.getName().startsWith(samTableName)) { partialMatches.add(Pair.of(metaData, IOUtils.toByteArray(zipInputStream))); } } entry = zipInputStream.getNextEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(zipInputStream); } if (selected == null) { if (partialMatches.isEmpty()) { throw new RuntimeException("Could not find table: " + samTableName + " in zipinputstream"); } else if (partialMatches.size() > 1) { throw new RuntimeException("Could not determine table for: " + samTableName + " in zipinputstream, " + partialMatches.size() + " partial matches"); } else { selected = partialMatches.get(0); } } return selected; } @NotNull private String parseVersion(final ZipEntry entry) { LOG.debug(entry.getName()); final int hekje = entry.getName().indexOf("#"); int start = hekje == -1 ? 0 : (hekje + 1);//conditie is overbodig maar wel duidelijker: wat te doen als niet gevonden. final int underscore = entry.getName().indexOf("_", start); int stop = underscore == -1 ? start : underscore; return entry.getName().substring(start, stop); } }
imec-int/ritme
Sam/src/uz/emv/sam/v1/db/tables/xml/zip/ZipInputStreamProviderFactory.java
1,214
//conditie is overbodig maar wel duidelijker: wat te doen als niet gevonden.
line_comment
nl
package uz.emv.sam.v1.db.tables.xml.zip; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uz.emv.sam.v1.db.tables.xml.InputStreamProvider; import uz.emv.sam.v1.db.tables.xml.InputStreamProviderFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Created by bdcuyp0 on 15-6-2016. */ public class ZipInputStreamProviderFactory implements InputStreamProviderFactory { private static final Logger LOG = LoggerFactory.getLogger(ZipInputStreamProviderFactory.class); private final byte[] zip; private final String suffix; public ZipInputStreamProviderFactory(final InputStream stream, final String suffix) { this.zip = copyToByteArray(stream); //LOG.info(new String(zip)); this.suffix = suffix; } private byte[] copyToByteArray(final InputStream stream) { try { return IOUtils.toByteArray(stream); } catch (IOException e) { throw new RuntimeException(e); } } @Override @NotNull public InputStreamProvider getInputStreamProvider(@NotNull final String samTableName) { final Pair<Map<String, Object>, byte[]> metaDataAndBytes = findBytes(samTableName, zip, suffix); if (metaDataAndBytes == null) { throw new RuntimeException("Could not find table " + samTableName + " in zipped inputstream with suffix " + suffix); } return new ByteArrayInputStreamProvider(metaDataAndBytes); } @Nullable private Pair<Map<String, Object>, byte[]> findBytes(@NotNull final String samTableName, final byte[] zip, final String suffix) { final List<Pair<Map<String, Object>, byte[]>> partialMatches = new ArrayList<Pair<Map<String, Object>, byte[]>>(); ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(zip)); ZipEntry entry = null; Pair<Map<String, Object>, byte[]> selected = null; try { entry = zipInputStream.getNextEntry(); while (entry != null) { Map<String, Object> metaData = new HashMap<String, Object>(); String version = parseVersion(entry); metaData.put("version", version); metaData.put("name", samTableName); if (suffix == null || entry.getName().endsWith(suffix)) { if (entry.getName().startsWith(samTableName + "#")) { selected = Pair.of(metaData, IOUtils.toByteArray(zipInputStream)); break; } else if (entry.getName().startsWith(samTableName)) { partialMatches.add(Pair.of(metaData, IOUtils.toByteArray(zipInputStream))); } } entry = zipInputStream.getNextEntry(); } } catch (IOException e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(zipInputStream); } if (selected == null) { if (partialMatches.isEmpty()) { throw new RuntimeException("Could not find table: " + samTableName + " in zipinputstream"); } else if (partialMatches.size() > 1) { throw new RuntimeException("Could not determine table for: " + samTableName + " in zipinputstream, " + partialMatches.size() + " partial matches"); } else { selected = partialMatches.get(0); } } return selected; } @NotNull private String parseVersion(final ZipEntry entry) { LOG.debug(entry.getName()); final int hekje = entry.getName().indexOf("#"); int start = hekje == -1 ? 0 : (hekje + 1);//conditie is<SUF> final int underscore = entry.getName().indexOf("_", start); int stop = underscore == -1 ? start : underscore; return entry.getName().substring(start, stop); } }
True
868
25
1,010
28
1,075
19
1,010
28
1,189
24
false
false
false
false
false
true
687
56145_3
package nl.hr.cmi.infdev226a; import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * Een wachtrij (queue) werkt via het * first-in first-out principe; elementen worden toegevoegd * aan de achterkant en worden verwijderd aan de voorkant. * * In deze klasse implementeer je een Queue door alleen * maar gebruik te maken van de opslagmethode die de * klasse GelinkteLijst je biedt. De Node komt niet voor in deze klasse! * * In [Hubbard, hoofdstuk 6] wordt de Queue besproken. * */ public class Wachtrij{ private GelinkteLijst lijst; public Wachtrij(){ lijst = new GelinkteLijst(); } /** * Zet iets in de wachtrij * aan de achterkant: FIFO */ public void enqueue(Object o){ lijst.insertFirst(o); //bijvoorbeeld zo } /** * Haal iets van de wachtrij * Aan de voorkant: FIFO */ public Object dequeue(){throw new NotImplementedException();} /** * Het aantal elementen in de wachtrij * @return */ public int size(){throw new NotImplementedException();} /** * Is de lijst leeg? * @return */ public boolean isEmpty(){throw new NotImplementedException();} /** * Bekijk het eerste element in de wachtrij, * maar haalt het niet er vanaf. * Note: het eerste element is als eerste toegevoegd. * @return */ public Object front(){throw new NotImplementedException();} }
HeadhunterXamd/GelinkteLijsten
src/main/java/nl/hr/cmi/infdev226a/Wachtrij.java
480
/** * Haal iets van de wachtrij * Aan de voorkant: FIFO */
block_comment
nl
package nl.hr.cmi.infdev226a; import sun.reflect.generics.reflectiveObjects.NotImplementedException; /** * Een wachtrij (queue) werkt via het * first-in first-out principe; elementen worden toegevoegd * aan de achterkant en worden verwijderd aan de voorkant. * * In deze klasse implementeer je een Queue door alleen * maar gebruik te maken van de opslagmethode die de * klasse GelinkteLijst je biedt. De Node komt niet voor in deze klasse! * * In [Hubbard, hoofdstuk 6] wordt de Queue besproken. * */ public class Wachtrij{ private GelinkteLijst lijst; public Wachtrij(){ lijst = new GelinkteLijst(); } /** * Zet iets in de wachtrij * aan de achterkant: FIFO */ public void enqueue(Object o){ lijst.insertFirst(o); //bijvoorbeeld zo } /** * Haal iets van<SUF>*/ public Object dequeue(){throw new NotImplementedException();} /** * Het aantal elementen in de wachtrij * @return */ public int size(){throw new NotImplementedException();} /** * Is de lijst leeg? * @return */ public boolean isEmpty(){throw new NotImplementedException();} /** * Bekijk het eerste element in de wachtrij, * maar haalt het niet er vanaf. * Note: het eerste element is als eerste toegevoegd. * @return */ public Object front(){throw new NotImplementedException();} }
True
395
26
439
24
422
24
439
24
499
29
false
false
false
false
false
true
4,519
46632_0
package com.github.fontys.jms.serializer; import com.github.fontys.jms.messaging.RequestReply; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class RequestReplySerializer<REQUEST, REPLY> { private Gson gson; //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund private final Class<REQUEST> requestClass; private final Class<REPLY> replyClass; public RequestReplySerializer(Class<REQUEST> requestClass, Class<REPLY> replyClass){ this.requestClass = requestClass; this.replyClass = replyClass; gson = new GsonBuilder().create(); } public String requestToString(REQUEST request){ return gson.toJson(request); } public REQUEST requestFromString(String str){ return gson.fromJson(str, requestClass); } public RequestReply requestReplyFromString(String str){ return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, requestClass, replyClass).getType()); } public String requestReplyToString(RequestReply rr){ return gson.toJson(rr); } public String replyToString(REPLY reply){ return gson.toJson(reply); } public REPLY replyFromString(String str){ return gson.fromJson(str, replyClass); } }
timgoes1997/DPI-6
src/main/com/github/fontys/jms/serializer/RequestReplySerializer.java
409
//gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund
line_comment
nl
package com.github.fontys.jms.serializer; import com.github.fontys.jms.messaging.RequestReply; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class RequestReplySerializer<REQUEST, REPLY> { private Gson gson; //gebruikte eerst<SUF> private final Class<REQUEST> requestClass; private final Class<REPLY> replyClass; public RequestReplySerializer(Class<REQUEST> requestClass, Class<REPLY> replyClass){ this.requestClass = requestClass; this.replyClass = replyClass; gson = new GsonBuilder().create(); } public String requestToString(REQUEST request){ return gson.toJson(request); } public REQUEST requestFromString(String str){ return gson.fromJson(str, requestClass); } public RequestReply requestReplyFromString(String str){ return gson.fromJson(str, TypeToken.getParameterized(RequestReply.class, requestClass, replyClass).getType()); } public String requestReplyToString(RequestReply rr){ return gson.toJson(rr); } public String replyToString(REPLY reply){ return gson.toJson(reply); } public REPLY replyFromString(String str){ return gson.fromJson(str, replyClass); } }
True
285
34
337
40
346
27
337
40
417
36
false
false
false
false
false
true
2,653
65512_1
/* * Copyright 2017 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.flink.process; import com.navercorp.pinpoint.common.hbase.HbaseTemplate; import com.navercorp.pinpoint.common.hbase.TableNameProvider; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import com.navercorp.pinpoint.common.server.bo.serializer.agent.AgentIdRowKeyEncoder; import com.navercorp.pinpoint.common.server.dao.hbase.mapper.AgentInfoBoMapper; import com.navercorp.pinpoint.flink.cache.FlinkCacheConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Get; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.cache.annotation.Cacheable; import java.util.Objects; import static com.navercorp.pinpoint.common.hbase.HbaseColumnFamily.AGENTINFO_INFO; /** * @author minwoo.jung */ public class ApplicationCache { private final Logger logger = LogManager.getLogger(this.getClass()); private static final String SPEL_KEY = "#application.getAgentId() + '.' + #application.getAgentStartTime()"; public static final String NOT_FOUND_APP_ID = "notFoundId"; private final transient AgentInfoBoMapper agentInfoMapper = new AgentInfoBoMapper(); private final transient HbaseTemplate hbaseTemplate2; private final transient TableNameProvider tableNameProvider; private final AgentIdRowKeyEncoder rowKeyEncoder = new AgentIdRowKeyEncoder(); public ApplicationCache(HbaseTemplate hbaseTemplate2, TableNameProvider tableNameProvider) { this.hbaseTemplate2 = Objects.requireNonNull(hbaseTemplate2, "hbaseTemplate"); this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); } @Cacheable(cacheNames = "applicationId", key = SPEL_KEY, cacheManager = FlinkCacheConfiguration.APPLICATION_ID_CACHE_NAME) public String findApplicationId(ApplicationKey application) { final String agentId = application.getAgentId(); final long agentStartTimestamp = application.getAgentStartTime(); final byte[] rowKey = rowKeyEncoder.encodeRowKey(agentId, agentStartTimestamp); Get get = new Get(rowKey); get.addColumn(AGENTINFO_INFO.getName(), AGENTINFO_INFO.QUALIFIER_IDENTIFIER); AgentInfoBo agentInfo = null; try { TableName tableName = tableNameProvider.getTableName(AGENTINFO_INFO.getTable()); agentInfo = hbaseTemplate2.get(tableName, get, agentInfoMapper); } catch (Exception e) { logger.error("can't found application id({}). {}", agentId, e.getMessage()); } return getApplicationId(agentInfo, agentId); } private String getApplicationId(AgentInfoBo agentInfo, String agentId) { if (agentInfo == null) { logger.warn("can't found application id : {}", agentId); return NOT_FOUND_APP_ID; } return agentInfo.getApplicationName(); } public static class ApplicationKey { private final String agentId; private final long agentStartTime; public ApplicationKey(String agentId, long agentStartTime) { this.agentId = agentId; this.agentStartTime = agentStartTime; } public String getAgentId() { return agentId; } public long getAgentStartTime() { return agentStartTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ApplicationKey that = (ApplicationKey) o; if (agentStartTime != that.agentStartTime) return false; return agentId != null ? agentId.equals(that.agentId) : that.agentId == null; } @Override public int hashCode() { int result = agentId != null ? agentId.hashCode() : 0; result = 31 * result + (int) (agentStartTime ^ (agentStartTime >>> 32)); return result; } @Override public String toString() { return "ApplicationKey{" + "agentId='" + agentId + '\'' + ", agentStartTime=" + agentStartTime + '}'; } } }
emeroad/pinpoint
flink/src/main/java/com/navercorp/pinpoint/flink/process/ApplicationCache.java
1,317
/** * @author minwoo.jung */
block_comment
nl
/* * Copyright 2017 NAVER Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.navercorp.pinpoint.flink.process; import com.navercorp.pinpoint.common.hbase.HbaseTemplate; import com.navercorp.pinpoint.common.hbase.TableNameProvider; import com.navercorp.pinpoint.common.server.bo.AgentInfoBo; import com.navercorp.pinpoint.common.server.bo.serializer.agent.AgentIdRowKeyEncoder; import com.navercorp.pinpoint.common.server.dao.hbase.mapper.AgentInfoBoMapper; import com.navercorp.pinpoint.flink.cache.FlinkCacheConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Get; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.cache.annotation.Cacheable; import java.util.Objects; import static com.navercorp.pinpoint.common.hbase.HbaseColumnFamily.AGENTINFO_INFO; /** * @author minwoo.jung <SUF>*/ public class ApplicationCache { private final Logger logger = LogManager.getLogger(this.getClass()); private static final String SPEL_KEY = "#application.getAgentId() + '.' + #application.getAgentStartTime()"; public static final String NOT_FOUND_APP_ID = "notFoundId"; private final transient AgentInfoBoMapper agentInfoMapper = new AgentInfoBoMapper(); private final transient HbaseTemplate hbaseTemplate2; private final transient TableNameProvider tableNameProvider; private final AgentIdRowKeyEncoder rowKeyEncoder = new AgentIdRowKeyEncoder(); public ApplicationCache(HbaseTemplate hbaseTemplate2, TableNameProvider tableNameProvider) { this.hbaseTemplate2 = Objects.requireNonNull(hbaseTemplate2, "hbaseTemplate"); this.tableNameProvider = Objects.requireNonNull(tableNameProvider, "tableNameProvider"); } @Cacheable(cacheNames = "applicationId", key = SPEL_KEY, cacheManager = FlinkCacheConfiguration.APPLICATION_ID_CACHE_NAME) public String findApplicationId(ApplicationKey application) { final String agentId = application.getAgentId(); final long agentStartTimestamp = application.getAgentStartTime(); final byte[] rowKey = rowKeyEncoder.encodeRowKey(agentId, agentStartTimestamp); Get get = new Get(rowKey); get.addColumn(AGENTINFO_INFO.getName(), AGENTINFO_INFO.QUALIFIER_IDENTIFIER); AgentInfoBo agentInfo = null; try { TableName tableName = tableNameProvider.getTableName(AGENTINFO_INFO.getTable()); agentInfo = hbaseTemplate2.get(tableName, get, agentInfoMapper); } catch (Exception e) { logger.error("can't found application id({}). {}", agentId, e.getMessage()); } return getApplicationId(agentInfo, agentId); } private String getApplicationId(AgentInfoBo agentInfo, String agentId) { if (agentInfo == null) { logger.warn("can't found application id : {}", agentId); return NOT_FOUND_APP_ID; } return agentInfo.getApplicationName(); } public static class ApplicationKey { private final String agentId; private final long agentStartTime; public ApplicationKey(String agentId, long agentStartTime) { this.agentId = agentId; this.agentStartTime = agentStartTime; } public String getAgentId() { return agentId; } public long getAgentStartTime() { return agentStartTime; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ApplicationKey that = (ApplicationKey) o; if (agentStartTime != that.agentStartTime) return false; return agentId != null ? agentId.equals(that.agentId) : that.agentId == null; } @Override public int hashCode() { int result = agentId != null ? agentId.hashCode() : 0; result = 31 * result + (int) (agentStartTime ^ (agentStartTime >>> 32)); return result; } @Override public String toString() { return "ApplicationKey{" + "agentId='" + agentId + '\'' + ", agentStartTime=" + agentStartTime + '}'; } } }
False
1,004
10
1,158
12
1,210
11
1,158
12
1,375
13
false
false
false
false
false
true
563
164649_3
package be.intecbrussel; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class DateTime { public static void main(String[] args) { Instant epochDate = Instant.EPOCH; System.out.println("Epoch date -> " + epochDate + "\n"); // -> Epoch date geeft de start datum en tijd van een operating system aan. Instant now = Instant.now(); System.out.println("Now date -> " + now + "\n"); // -> Geeft tegenwoordige datum en standard tijd aan (coordinated universal time). LocalTime lt = LocalTime.now(); System.out.println("Local time -> " + lt + "\n"); // -> Geeft de tegenwoordige locale tijd aan. LocalDate ld = LocalDate.now(); System.out.println("Local date -> " + ld + "\n"); // -> Geeft de tegenwoordige locale datum aan. LocalDateTime ldt = LocalDateTime.now(); System.out.println("Local date and time -> " + ldt + "\n"); LocalDateTime date = LocalDateTime.of(2018, 01, 20, 12, 30); System.out.println("Written date and time -> " + date + "\n"); DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); String myFormattedDateTime = ldt.format(myFormat); System.out.println("Formatted date and time -> " + myFormattedDateTime + "\n"); /* * yyyy-MM-dd -> 2023-02-07 * dd/MM/yyyy -> 07/09/2023 * dd-MMM-yyyy -> 29-Feb-2023 * E, MMM dd yyyy -> Tue, Feb 07 2023 */ Duration secondsInHour = Duration.ofHours(1); System.out.println(secondsInHour.getSeconds() + " seconds" + "\n"); Duration secondsInDay = Duration.ofDays(1); System.out.println(secondsInDay.getSeconds() + " seconds" + "\n"); LocalDateTime newDate1 = LocalDateTime.of(2022, 8, 25, 11, 33, 15); LocalDateTime oldDate1 = LocalDateTime.of(2016, 8, 31, 10, 20, 55); Duration betweenDate = Duration.between(oldDate1, newDate1); System.out.println(betweenDate.getSeconds() + " seconds" + "\n"); Period tenDays = Period.ofDays(10).plusDays(10); System.out.println(tenDays.getDays() + "\n"); Period months1 = Period.ofMonths(1).plusMonths(25); System.out.println(months1.getMonths() + "\n"); LocalDate newDate2 = LocalDate.of(2022, 8, 25); LocalDate oldDate2 = LocalDate.of(2000, 1, 1); Period period = Period.between(oldDate2, newDate2); System.out.print(period.getYears() + " years, "); System.out.print(period.getMonths() + " months, "); System.out.print(period.getDays() + " days" + "\n"); LocalDateTime newDate3 = LocalDateTime.of(2022, 8, 25, 11, 33, 15); LocalDateTime oldDate3 = LocalDateTime.of(1021, 8, 31, 10, 20, 55); long millennia = ChronoUnit.MILLENNIA.between(oldDate3, newDate3); long centuries = ChronoUnit.CENTURIES.between(oldDate3, newDate3); long decades = ChronoUnit.DECADES.between(oldDate3, newDate3); long years = ChronoUnit.YEARS.between(oldDate3, newDate3); long months = ChronoUnit.MONTHS.between(oldDate3, newDate3); long weeks = ChronoUnit.WEEKS.between(oldDate3, newDate3); long days = ChronoUnit.DAYS.between(oldDate3, newDate3); long hours = ChronoUnit.HOURS.between(oldDate3, newDate3); long minutes = ChronoUnit.MINUTES.between(oldDate3, newDate3); long seconds = ChronoUnit.SECONDS.between(oldDate3, newDate3); System.out.println(millennia + " millennia"); System.out.println(centuries + " centuries"); System.out.println(decades + " decades"); System.out.println(years + " years"); System.out.println(months + " months"); System.out.println(weeks + " weeks"); System.out.println(days + " days"); System.out.println(hours + " hours"); System.out.println(minutes + " minutes"); System.out.println(seconds + " seconds" + "\n"); ChronoUnit chronoUnit1 = ChronoUnit.valueOf("DAYS"); Duration getDurationAttribute1 = chronoUnit1.getDuration(); System.out.println("Duration Estimated : " + getDurationAttribute1 + "\n"); ChronoUnit chronoUnit2 = ChronoUnit.valueOf("MONTHS"); Duration getDurationAttribute2 = chronoUnit2.getDuration(); System.out.println("Duration Estimated : " + getDurationAttribute2); } }
Gabe-Alvess/DateTime
src/be/intecbrussel/DateTime.java
1,441
// -> Geeft de tegenwoordige locale datum aan.
line_comment
nl
package be.intecbrussel; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; public class DateTime { public static void main(String[] args) { Instant epochDate = Instant.EPOCH; System.out.println("Epoch date -> " + epochDate + "\n"); // -> Epoch date geeft de start datum en tijd van een operating system aan. Instant now = Instant.now(); System.out.println("Now date -> " + now + "\n"); // -> Geeft tegenwoordige datum en standard tijd aan (coordinated universal time). LocalTime lt = LocalTime.now(); System.out.println("Local time -> " + lt + "\n"); // -> Geeft de tegenwoordige locale tijd aan. LocalDate ld = LocalDate.now(); System.out.println("Local date -> " + ld + "\n"); // -> Geeft<SUF> LocalDateTime ldt = LocalDateTime.now(); System.out.println("Local date and time -> " + ldt + "\n"); LocalDateTime date = LocalDateTime.of(2018, 01, 20, 12, 30); System.out.println("Written date and time -> " + date + "\n"); DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss"); String myFormattedDateTime = ldt.format(myFormat); System.out.println("Formatted date and time -> " + myFormattedDateTime + "\n"); /* * yyyy-MM-dd -> 2023-02-07 * dd/MM/yyyy -> 07/09/2023 * dd-MMM-yyyy -> 29-Feb-2023 * E, MMM dd yyyy -> Tue, Feb 07 2023 */ Duration secondsInHour = Duration.ofHours(1); System.out.println(secondsInHour.getSeconds() + " seconds" + "\n"); Duration secondsInDay = Duration.ofDays(1); System.out.println(secondsInDay.getSeconds() + " seconds" + "\n"); LocalDateTime newDate1 = LocalDateTime.of(2022, 8, 25, 11, 33, 15); LocalDateTime oldDate1 = LocalDateTime.of(2016, 8, 31, 10, 20, 55); Duration betweenDate = Duration.between(oldDate1, newDate1); System.out.println(betweenDate.getSeconds() + " seconds" + "\n"); Period tenDays = Period.ofDays(10).plusDays(10); System.out.println(tenDays.getDays() + "\n"); Period months1 = Period.ofMonths(1).plusMonths(25); System.out.println(months1.getMonths() + "\n"); LocalDate newDate2 = LocalDate.of(2022, 8, 25); LocalDate oldDate2 = LocalDate.of(2000, 1, 1); Period period = Period.between(oldDate2, newDate2); System.out.print(period.getYears() + " years, "); System.out.print(period.getMonths() + " months, "); System.out.print(period.getDays() + " days" + "\n"); LocalDateTime newDate3 = LocalDateTime.of(2022, 8, 25, 11, 33, 15); LocalDateTime oldDate3 = LocalDateTime.of(1021, 8, 31, 10, 20, 55); long millennia = ChronoUnit.MILLENNIA.between(oldDate3, newDate3); long centuries = ChronoUnit.CENTURIES.between(oldDate3, newDate3); long decades = ChronoUnit.DECADES.between(oldDate3, newDate3); long years = ChronoUnit.YEARS.between(oldDate3, newDate3); long months = ChronoUnit.MONTHS.between(oldDate3, newDate3); long weeks = ChronoUnit.WEEKS.between(oldDate3, newDate3); long days = ChronoUnit.DAYS.between(oldDate3, newDate3); long hours = ChronoUnit.HOURS.between(oldDate3, newDate3); long minutes = ChronoUnit.MINUTES.between(oldDate3, newDate3); long seconds = ChronoUnit.SECONDS.between(oldDate3, newDate3); System.out.println(millennia + " millennia"); System.out.println(centuries + " centuries"); System.out.println(decades + " decades"); System.out.println(years + " years"); System.out.println(months + " months"); System.out.println(weeks + " weeks"); System.out.println(days + " days"); System.out.println(hours + " hours"); System.out.println(minutes + " minutes"); System.out.println(seconds + " seconds" + "\n"); ChronoUnit chronoUnit1 = ChronoUnit.valueOf("DAYS"); Duration getDurationAttribute1 = chronoUnit1.getDuration(); System.out.println("Duration Estimated : " + getDurationAttribute1 + "\n"); ChronoUnit chronoUnit2 = ChronoUnit.valueOf("MONTHS"); Duration getDurationAttribute2 = chronoUnit2.getDuration(); System.out.println("Duration Estimated : " + getDurationAttribute2); } }
True
1,157
12
1,340
15
1,346
12
1,340
15
1,499
13
false
false
false
false
false
true
2,726
201039_3
package com.francelabs.datafari.servlets.admin.cluster; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.francelabs.datafari.utils.AuthenticatedUserName; import com.francelabs.datafari.utils.ClusterActionsConfiguration; import com.francelabs.datafari.utils.Environment; import com.francelabs.datafari.audit.AuditLogUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Servlet implementation class getAllUsersAndRoles */ @WebServlet("/admin/cluster/reinitializemcf") public class ClusterReinit extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(ClusterReinit.class); // Threshold to compare dates, if dates are closer than the threshold, they are // considered equal. This is in seconds. private static final long THRESHOLD = 10; private static final String DATAFARI_HOME = Environment.getEnvironmentVariable("DATAFARI_HOME") != null ? Environment.getEnvironmentVariable("DATAFARI_HOME") : "/opt/datafari"; private static final String SCRIPT_WORKING_DIR = DATAFARI_HOME + "/bin"; private static final String REPORT_BASE_DIR = DATAFARI_HOME + "/logs"; /** * @see HttpServlet#HttpServlet() */ public ClusterReinit() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String action = request.getParameter("action"); if (action != null && action.equals("getReport")) { ClusterActionsUtils.outputReport(request, response, ClusterAction.REINIT); } else { ClusterActionsUtils.outputStatus(request, response, ClusterAction.REINIT); } } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { ClusterActionsUtils.setUnmanagedDoPost(req, resp); } @Override protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { DateTimeFormatter dateFormatter = ClusterActionsConfiguration.dateFormatter; ClusterActionsConfiguration config = ClusterActionsConfiguration.getInstance(); final JSONObject jsonResponse = new JSONObject(); req.setCharacterEncoding("utf8"); resp.setContentType("application/json"); req.getParameter("annotatorActivation"); try { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); final JSONParser parser = new JSONParser(); JSONObject requestBody = (JSONObject) parser.parse(br); String lastReinitString = config.getProperty(ClusterActionsConfiguration.LAST_REINIT_DATE); Instant putDate = Instant.parse((String) requestBody.get("date")); Instant now = Instant.now(); Instant lastReinit = Instant.MIN; if (lastReinitString != null && !lastReinitString.equals("")) { Instant.parse(lastReinitString); } long nowToPutDate = Math.abs(now.until(putDate, ChronoUnit.SECONDS)); long lastReinitToPutDate = Math.abs(lastReinit.until(putDate, ChronoUnit.SECONDS)); if (lastReinitToPutDate > THRESHOLD && nowToPutDate < THRESHOLD) { // If the put date is far enough from the last restart // and close enough to the current time => we can restart // But we need first to check that the install is standard (mandatory) // and that we are either in unmanaged mode, or no other action is in progress String unmanagedString = config.getProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE); boolean unmanagedMode = unmanagedString != null && unmanagedString.contentEquals("true"); boolean noActionInProgress = true; for (ClusterAction action : ClusterAction.values()) { try { noActionInProgress = noActionInProgress && !ClusterActionsUtils.isActionInProgress(action); } catch (FileNotFoundException e) { logger.info("Last report file for " + action + " not found, actions are not blocked."); } } if (ClusterActionsUtils.isStandardInstall() && (unmanagedMode || noActionInProgress)) { // retrieve AuthenticatedUserName if user authenticated (it should be as we are // in the admin...) String authenticatedUserName = AuthenticatedUserName.getName(req); // Log for audit purposes who did the request String unmanagedModeNotice = unmanagedMode ? " with UNMANAGED UI state" : ""; AuditLogUtil.log("Reinitialization", authenticatedUserName, req.getRemoteAddr(), "Datafari full reinitialization request received from user " + authenticatedUserName + " from ip " + req.getRemoteAddr() + unmanagedModeNotice + " through the admin UI, answering YES to both questions: Do you confirm " + "that you successfully backed up the connectors beforehand (it " + "is part of the backup process) ? and Do you confirm that " + "you have understood that you will need to reindex you data ?"); String reportName = "cluster-reinitialization-" + dateFormatter.format(putDate) + ".log"; // Set the property file containing the last reinitialization date config.setProperty(ClusterActionsConfiguration.LAST_REINIT_DATE, dateFormatter.format(putDate)); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_IP, req.getRemoteAddr()); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_USER, authenticatedUserName); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_REPORT, reportName); config.setProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE, "false"); config.saveProperties(); // Wire up the call to the bash script final String workingDirectory = SCRIPT_WORKING_DIR; final String filePath = REPORT_BASE_DIR + File.separator + reportName; final String[] command = { "/bin/bash", "./reinitUtils/global_reinit_restore_mcf.sh" }; final ProcessBuilder p = new ProcessBuilder(command); p.redirectErrorStream(true); p.redirectOutput(new File(filePath)); p.directory(new File(workingDirectory)); // Not storing the Process in any manner, tomcat will be restarted anyway so any // variable would be lost, this would be useless. Could store a process ID but // it is not necessary as the report file will provide us information about the // status. p.start(); jsonResponse.put("success", "true"); jsonResponse.put("message", "Datafari reinitializing"); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); for (ClusterAction action : ClusterAction.values()) { try { if (ClusterActionsUtils.isActionInProgress(action)) { // Only the last action in progress will be added to the result // object, but there should be only one active at a time anyway. jsonResponse.put("message", "A " + action + " is in progress."); }; } catch (FileNotFoundException e) { // Nothing to do here, but the file being missing is not a problem, so // catch it to ensure it does not escalate. } } if(jsonResponse.get("message") == null) { jsonResponse.put("message", "An unidentified error prevented the action completion."); } } } else { // Send an error message. if (nowToPutDate >= THRESHOLD) { logger.warn("Trying to perform a cluster reinitialization with a date that is not now. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); jsonResponse.put("message", "Can't reinitialize with a date different than now, now and provided date differ by " + lastReinitToPutDate + "seconds"); } else if (lastReinitToPutDate <= THRESHOLD) { logger.warn( "Trying to perform a cluster reinitialization with a date that is too close to the last reinitialization. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); jsonResponse.put("success", "false"); jsonResponse.put("message", "Server already reinitialized at this date"); } } } catch (Exception e) { logger.error("Couldn't perform the cluster reinitialization.", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jsonResponse.clear(); jsonResponse.put("success", "false"); jsonResponse.put("message", "Unexpected server error while processing the reinitialization query"); } final PrintWriter out = resp.getWriter(); out.print(jsonResponse); } }
francelabs/datafari
datafari-webapp/src/main/java/com/francelabs/datafari/servlets/admin/cluster/ClusterReinit.java
2,709
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package com.francelabs.datafari.servlets.admin.cluster; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.francelabs.datafari.utils.AuthenticatedUserName; import com.francelabs.datafari.utils.ClusterActionsConfiguration; import com.francelabs.datafari.utils.Environment; import com.francelabs.datafari.audit.AuditLogUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; /** * Servlet implementation class getAllUsersAndRoles */ @WebServlet("/admin/cluster/reinitializemcf") public class ClusterReinit extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = LogManager.getLogger(ClusterReinit.class); // Threshold to compare dates, if dates are closer than the threshold, they are // considered equal. This is in seconds. private static final long THRESHOLD = 10; private static final String DATAFARI_HOME = Environment.getEnvironmentVariable("DATAFARI_HOME") != null ? Environment.getEnvironmentVariable("DATAFARI_HOME") : "/opt/datafari"; private static final String SCRIPT_WORKING_DIR = DATAFARI_HOME + "/bin"; private static final String REPORT_BASE_DIR = DATAFARI_HOME + "/logs"; /** * @see HttpServlet#HttpServlet() <SUF>*/ public ClusterReinit() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ @Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { final String action = request.getParameter("action"); if (action != null && action.equals("getReport")) { ClusterActionsUtils.outputReport(request, response, ClusterAction.REINIT); } else { ClusterActionsUtils.outputStatus(request, response, ClusterAction.REINIT); } } @Override protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { ClusterActionsUtils.setUnmanagedDoPost(req, resp); } @Override protected void doPut(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { DateTimeFormatter dateFormatter = ClusterActionsConfiguration.dateFormatter; ClusterActionsConfiguration config = ClusterActionsConfiguration.getInstance(); final JSONObject jsonResponse = new JSONObject(); req.setCharacterEncoding("utf8"); resp.setContentType("application/json"); req.getParameter("annotatorActivation"); try { BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream())); final JSONParser parser = new JSONParser(); JSONObject requestBody = (JSONObject) parser.parse(br); String lastReinitString = config.getProperty(ClusterActionsConfiguration.LAST_REINIT_DATE); Instant putDate = Instant.parse((String) requestBody.get("date")); Instant now = Instant.now(); Instant lastReinit = Instant.MIN; if (lastReinitString != null && !lastReinitString.equals("")) { Instant.parse(lastReinitString); } long nowToPutDate = Math.abs(now.until(putDate, ChronoUnit.SECONDS)); long lastReinitToPutDate = Math.abs(lastReinit.until(putDate, ChronoUnit.SECONDS)); if (lastReinitToPutDate > THRESHOLD && nowToPutDate < THRESHOLD) { // If the put date is far enough from the last restart // and close enough to the current time => we can restart // But we need first to check that the install is standard (mandatory) // and that we are either in unmanaged mode, or no other action is in progress String unmanagedString = config.getProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE); boolean unmanagedMode = unmanagedString != null && unmanagedString.contentEquals("true"); boolean noActionInProgress = true; for (ClusterAction action : ClusterAction.values()) { try { noActionInProgress = noActionInProgress && !ClusterActionsUtils.isActionInProgress(action); } catch (FileNotFoundException e) { logger.info("Last report file for " + action + " not found, actions are not blocked."); } } if (ClusterActionsUtils.isStandardInstall() && (unmanagedMode || noActionInProgress)) { // retrieve AuthenticatedUserName if user authenticated (it should be as we are // in the admin...) String authenticatedUserName = AuthenticatedUserName.getName(req); // Log for audit purposes who did the request String unmanagedModeNotice = unmanagedMode ? " with UNMANAGED UI state" : ""; AuditLogUtil.log("Reinitialization", authenticatedUserName, req.getRemoteAddr(), "Datafari full reinitialization request received from user " + authenticatedUserName + " from ip " + req.getRemoteAddr() + unmanagedModeNotice + " through the admin UI, answering YES to both questions: Do you confirm " + "that you successfully backed up the connectors beforehand (it " + "is part of the backup process) ? and Do you confirm that " + "you have understood that you will need to reindex you data ?"); String reportName = "cluster-reinitialization-" + dateFormatter.format(putDate) + ".log"; // Set the property file containing the last reinitialization date config.setProperty(ClusterActionsConfiguration.LAST_REINIT_DATE, dateFormatter.format(putDate)); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_IP, req.getRemoteAddr()); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_USER, authenticatedUserName); config.setProperty(ClusterActionsConfiguration.LAST_REINIT_REPORT, reportName); config.setProperty(ClusterActionsConfiguration.FORCE_UNMANAGED_STATE, "false"); config.saveProperties(); // Wire up the call to the bash script final String workingDirectory = SCRIPT_WORKING_DIR; final String filePath = REPORT_BASE_DIR + File.separator + reportName; final String[] command = { "/bin/bash", "./reinitUtils/global_reinit_restore_mcf.sh" }; final ProcessBuilder p = new ProcessBuilder(command); p.redirectErrorStream(true); p.redirectOutput(new File(filePath)); p.directory(new File(workingDirectory)); // Not storing the Process in any manner, tomcat will be restarted anyway so any // variable would be lost, this would be useless. Could store a process ID but // it is not necessary as the report file will provide us information about the // status. p.start(); jsonResponse.put("success", "true"); jsonResponse.put("message", "Datafari reinitializing"); } else { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); for (ClusterAction action : ClusterAction.values()) { try { if (ClusterActionsUtils.isActionInProgress(action)) { // Only the last action in progress will be added to the result // object, but there should be only one active at a time anyway. jsonResponse.put("message", "A " + action + " is in progress."); }; } catch (FileNotFoundException e) { // Nothing to do here, but the file being missing is not a problem, so // catch it to ensure it does not escalate. } } if(jsonResponse.get("message") == null) { jsonResponse.put("message", "An unidentified error prevented the action completion."); } } } else { // Send an error message. if (nowToPutDate >= THRESHOLD) { logger.warn("Trying to perform a cluster reinitialization with a date that is not now. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); jsonResponse.put("success", "false"); jsonResponse.put("message", "Can't reinitialize with a date different than now, now and provided date differ by " + lastReinitToPutDate + "seconds"); } else if (lastReinitToPutDate <= THRESHOLD) { logger.warn( "Trying to perform a cluster reinitialization with a date that is too close to the last reinitialization. " + "Current date: " + dateFormatter.format(now) + "; provided date: " + dateFormatter.format(putDate)); resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); jsonResponse.put("success", "false"); jsonResponse.put("message", "Server already reinitialized at this date"); } } } catch (Exception e) { logger.error("Couldn't perform the cluster reinitialization.", e); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); jsonResponse.clear(); jsonResponse.put("success", "false"); jsonResponse.put("message", "Unexpected server error while processing the reinitialization query"); } final PrintWriter out = resp.getWriter(); out.print(jsonResponse); } }
False
1,963
12
2,219
11
2,385
13
2,219
11
2,692
15
false
false
false
false
false
true
418
186119_6
package server.providers; import server.models.Event; import server.models.Student; import server.utility.Authenticator; import java.sql.*; import java.util.ArrayList; public class StudentTable extends DBmanager { private ResultSet resultSet; private Student student; /** * * @param idStudent * @return Attending Events * @throws IllegalAccessException */ public ArrayList getAttendingEvents(int idStudent) throws IllegalAccessException { ArrayList attendingEvents = new ArrayList(); //henter alle events en studerende deltager på. try { PreparedStatement getAttendingEvents = getConnection().prepareStatement ("SELECT she.*, s.*, e.* " + "FROM students_has_dsevent she " + "INNER JOIN students s " + "ON she.students_idStudent = s.idStudent " + "INNER JOIN dsevent e " + "ON she.dsevent_idEvent = e.idEvent " + "WHERE s.idStudent = ? AND e.isDeleted = 0"); getAttendingEvents.setInt(1, idStudent); resultSet = getAttendingEvents.executeQuery(); while (resultSet.next()) { try { //Opretter ny instans af de studenter der er i ArrayListen. (Måden man henter oplysninger). Event event = new Event(); event.setIdEvent(resultSet.getInt("idEvent")); event.setEventName(resultSet.getString("eventName")); event.setOwner(resultSet.getInt("owner")); event.setLocation(resultSet.getString("location")); event.setPrice(resultSet.getInt("price")); event.setEventDate(resultSet.getString("eventDate")); event.setDescription(resultSet.getString("description")); attendingEvents.add(event); } catch (Exception e) { e.printStackTrace(); } } resultSet.close(); getAttendingEvents.close(); } catch (SQLException sqlException) { System.out.println(sqlException.getMessage()); } //Returnerer attendingStudents med oplysninger. return attendingEvents; } /** * * @param student * @return True * @throws SQLException */ public boolean addStudent(Student student) throws SQLException { // Denne metode er taget fra henrik (Slack) long unixTime = System.currentTimeMillis() / 1000L; //generer salt password student.setSalt(student.getEmail() + unixTime); //generer hashed password med salt. student.setPassword(Authenticator.hashWithSalt(student.getPassword(), student.getSalt())); student.setCreatedTime(unixTime); PreparedStatement addStudentStatement = getConnection().prepareStatement ("INSERT INTO students (firstName, lastName, email, password, createdTime) VALUES (?, ?, ?, ?, ?)"); try { addStudentStatement.setString(1, student.getFirstName()); addStudentStatement.setString(2, student.getLastName()); addStudentStatement.setString(3, student.getEmail()); addStudentStatement.setString(4, student.getPassword()); addStudentStatement.setLong(5, student.getCreatedTime()); try { int rowsUpdated = addStudentStatement.executeUpdate(); if (rowsUpdated != 1) { throw new SQLException("More or less than 1 row was affected"); } } catch (SQLIntegrityConstraintViolationException integrity) { integrity.printStackTrace(); throw new SQLException("the user already exists"); } } catch (SQLException e) { e.printStackTrace(); throw new SQLException("SQL Error"); } addStudentStatement.close(); return true; } /** * * @param email * @return Student by Email */ public Student getStudentByEmail(String email) { try { PreparedStatement getStudentEmailStatement = getConnection().prepareStatement("SELECT * FROM students WHERE email = ?"); getStudentEmailStatement.setString(1, email); resultSet = getStudentEmailStatement.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setEmail(resultSet.getString("email")); student.setPassword(resultSet.getString("password")); student.setCreatedTime(resultSet.getLong("createdTime")); } if (student == null) { throw new IllegalArgumentException(); } resultSet.close(); getStudentEmailStatement.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } // Sletter en token i databasen til et bestemt idStudent /** * * @param idStudent * @return False * @throws SQLException */ public boolean deleteToken(String idStudent) throws SQLException { PreparedStatement deleteTokenStatement = getConnection().prepareStatement(" DELETE FROM tokens WHERE token = ?"); try { deleteTokenStatement.setString(1, idStudent); int rowsAffected = deleteTokenStatement.executeUpdate(); deleteTokenStatement.close(); if (rowsAffected == 1) { return true; } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } // Indsætter en token i DB til et bestemt idStudent /** * * @param token * @param idStudent * @return True or False * @throws SQLException */ public boolean addToken(String token, int idStudent) throws SQLException { PreparedStatement addTokenStatement; int rowsAffected = 0; try { addTokenStatement = getConnection().prepareStatement("INSERT INTO tokens (token, students_idStudent) VALUES (? , ?)"); addTokenStatement.setString(1, token); addTokenStatement.setInt(2, idStudent); rowsAffected = addTokenStatement.executeUpdate(); addTokenStatement.close(); } catch (SQLException e) { e.printStackTrace(); } if (rowsAffected == 1) { return true; } else { return false; } } /** * * @param token * @return Student * @throws SQLException */ public Student getStudentFromToken(String token) throws SQLException { try { PreparedStatement getStudentFromToken = getConnection().prepareStatement("SELECT idStudent, firstName, lastName, email, createdTime FROM students s INNER JOIN tokens t ON t.students_idStudent = s.idStudent WHERE t.token = ?"); getStudentFromToken.setString(1, token); resultSet = getStudentFromToken.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setFirstName(resultSet.getString("firstName")); student.setLastName(resultSet.getString("lastName")); student.setEmail(resultSet.getString("email")); student.setCreatedTime(resultSet.getLong("createdTime")); } resultSet.close(); getStudentFromToken.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } }
Distribuerede-Systemer-2017/STFU-new
src/main/java/server/providers/StudentTable.java
2,092
//generer salt password
line_comment
nl
package server.providers; import server.models.Event; import server.models.Student; import server.utility.Authenticator; import java.sql.*; import java.util.ArrayList; public class StudentTable extends DBmanager { private ResultSet resultSet; private Student student; /** * * @param idStudent * @return Attending Events * @throws IllegalAccessException */ public ArrayList getAttendingEvents(int idStudent) throws IllegalAccessException { ArrayList attendingEvents = new ArrayList(); //henter alle events en studerende deltager på. try { PreparedStatement getAttendingEvents = getConnection().prepareStatement ("SELECT she.*, s.*, e.* " + "FROM students_has_dsevent she " + "INNER JOIN students s " + "ON she.students_idStudent = s.idStudent " + "INNER JOIN dsevent e " + "ON she.dsevent_idEvent = e.idEvent " + "WHERE s.idStudent = ? AND e.isDeleted = 0"); getAttendingEvents.setInt(1, idStudent); resultSet = getAttendingEvents.executeQuery(); while (resultSet.next()) { try { //Opretter ny instans af de studenter der er i ArrayListen. (Måden man henter oplysninger). Event event = new Event(); event.setIdEvent(resultSet.getInt("idEvent")); event.setEventName(resultSet.getString("eventName")); event.setOwner(resultSet.getInt("owner")); event.setLocation(resultSet.getString("location")); event.setPrice(resultSet.getInt("price")); event.setEventDate(resultSet.getString("eventDate")); event.setDescription(resultSet.getString("description")); attendingEvents.add(event); } catch (Exception e) { e.printStackTrace(); } } resultSet.close(); getAttendingEvents.close(); } catch (SQLException sqlException) { System.out.println(sqlException.getMessage()); } //Returnerer attendingStudents med oplysninger. return attendingEvents; } /** * * @param student * @return True * @throws SQLException */ public boolean addStudent(Student student) throws SQLException { // Denne metode er taget fra henrik (Slack) long unixTime = System.currentTimeMillis() / 1000L; //generer salt<SUF> student.setSalt(student.getEmail() + unixTime); //generer hashed password med salt. student.setPassword(Authenticator.hashWithSalt(student.getPassword(), student.getSalt())); student.setCreatedTime(unixTime); PreparedStatement addStudentStatement = getConnection().prepareStatement ("INSERT INTO students (firstName, lastName, email, password, createdTime) VALUES (?, ?, ?, ?, ?)"); try { addStudentStatement.setString(1, student.getFirstName()); addStudentStatement.setString(2, student.getLastName()); addStudentStatement.setString(3, student.getEmail()); addStudentStatement.setString(4, student.getPassword()); addStudentStatement.setLong(5, student.getCreatedTime()); try { int rowsUpdated = addStudentStatement.executeUpdate(); if (rowsUpdated != 1) { throw new SQLException("More or less than 1 row was affected"); } } catch (SQLIntegrityConstraintViolationException integrity) { integrity.printStackTrace(); throw new SQLException("the user already exists"); } } catch (SQLException e) { e.printStackTrace(); throw new SQLException("SQL Error"); } addStudentStatement.close(); return true; } /** * * @param email * @return Student by Email */ public Student getStudentByEmail(String email) { try { PreparedStatement getStudentEmailStatement = getConnection().prepareStatement("SELECT * FROM students WHERE email = ?"); getStudentEmailStatement.setString(1, email); resultSet = getStudentEmailStatement.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setEmail(resultSet.getString("email")); student.setPassword(resultSet.getString("password")); student.setCreatedTime(resultSet.getLong("createdTime")); } if (student == null) { throw new IllegalArgumentException(); } resultSet.close(); getStudentEmailStatement.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } // Sletter en token i databasen til et bestemt idStudent /** * * @param idStudent * @return False * @throws SQLException */ public boolean deleteToken(String idStudent) throws SQLException { PreparedStatement deleteTokenStatement = getConnection().prepareStatement(" DELETE FROM tokens WHERE token = ?"); try { deleteTokenStatement.setString(1, idStudent); int rowsAffected = deleteTokenStatement.executeUpdate(); deleteTokenStatement.close(); if (rowsAffected == 1) { return true; } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } // Indsætter en token i DB til et bestemt idStudent /** * * @param token * @param idStudent * @return True or False * @throws SQLException */ public boolean addToken(String token, int idStudent) throws SQLException { PreparedStatement addTokenStatement; int rowsAffected = 0; try { addTokenStatement = getConnection().prepareStatement("INSERT INTO tokens (token, students_idStudent) VALUES (? , ?)"); addTokenStatement.setString(1, token); addTokenStatement.setInt(2, idStudent); rowsAffected = addTokenStatement.executeUpdate(); addTokenStatement.close(); } catch (SQLException e) { e.printStackTrace(); } if (rowsAffected == 1) { return true; } else { return false; } } /** * * @param token * @return Student * @throws SQLException */ public Student getStudentFromToken(String token) throws SQLException { try { PreparedStatement getStudentFromToken = getConnection().prepareStatement("SELECT idStudent, firstName, lastName, email, createdTime FROM students s INNER JOIN tokens t ON t.students_idStudent = s.idStudent WHERE t.token = ?"); getStudentFromToken.setString(1, token); resultSet = getStudentFromToken.executeQuery(); while (resultSet.next()) { student = new Student(); student.setIdStudent(resultSet.getInt("idStudent")); student.setFirstName(resultSet.getString("firstName")); student.setLastName(resultSet.getString("lastName")); student.setEmail(resultSet.getString("email")); student.setCreatedTime(resultSet.getLong("createdTime")); } resultSet.close(); getStudentFromToken.close(); } catch (SQLException e) { e.printStackTrace(); } return student; } }
False
1,434
5
1,576
5
1,720
5
1,576
5
1,958
5
false
false
false
false
false
true
3,927
167698_1
package org.daniils.vloerinspection.ui.login; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import android.content.Context; import android.content.SharedPreferences; import android.util.Patterns; import org.daniils.vloerinspection.data.api.VloerAPI; import org.daniils.vloerinspection.R; public class LoginViewModel extends ViewModel { private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>(); private MutableLiveData<LoginResult> loginResult = new MutableLiveData<>(); LiveData<LoginFormState> getLoginFormState() { return loginFormState; } LiveData<LoginResult> getLoginResult() { return loginResult; } public void login(String username, String password, boolean remember, Context context) { new VloerAPI(context).getUser(username, password, user -> { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(context.getString(R.string.pref_remember), remember); if (remember) { editor.putString(context.getString(R.string.username), username); editor.putString(context.getString(R.string.password), password); } editor.apply(); loginResult.setValue(new LoginResult(user)); }, error -> { loginResult.setValue(new LoginResult(R.string.login_failed)); error.printStackTrace(); }); } private SharedPreferences getSharedPreferences(Context context) { return context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE); } public void loadFormIfRemembered(Context context) { SharedPreferences sharedPreferences = getSharedPreferences(context); boolean remember = sharedPreferences.getBoolean(context.getString(R.string.pref_remember), false); if (remember) { String username = sharedPreferences.getString(context.getString(R.string.username), ""); String password = sharedPreferences.getString(context.getString(R.string.password), ""); loginFormState.setValue(new LoginFormState(username, password, true)); } } public void loginDataChanged(String username, String password) { if (!isUserNameValid(username)) { loginFormState.setValue(new LoginFormState(R.string.invalid_username, null)); } else if (!isPasswordValid(password)) { loginFormState.setValue(new LoginFormState(null, R.string.invalid_password)); } else { loginFormState.setValue(new LoginFormState(true)); } } // A placeholder username validation check private boolean isUserNameValid(String username) { if (username == null) { return false; } if (username.contains("@")) { return Patterns.EMAIL_ADDRESS.matcher(username).matches(); } else { return !username.trim().isEmpty(); } } // A placeholder password validation check private boolean isPasswordValid(String password) { return password != null && password.length() > 0; } }
ortemios/VloerInspection
app/src/main/java/org/daniils/vloerinspection/ui/login/LoginViewModel.java
882
// A placeholder password validation check
line_comment
nl
package org.daniils.vloerinspection.ui.login; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import android.content.Context; import android.content.SharedPreferences; import android.util.Patterns; import org.daniils.vloerinspection.data.api.VloerAPI; import org.daniils.vloerinspection.R; public class LoginViewModel extends ViewModel { private MutableLiveData<LoginFormState> loginFormState = new MutableLiveData<>(); private MutableLiveData<LoginResult> loginResult = new MutableLiveData<>(); LiveData<LoginFormState> getLoginFormState() { return loginFormState; } LiveData<LoginResult> getLoginResult() { return loginResult; } public void login(String username, String password, boolean remember, Context context) { new VloerAPI(context).getUser(username, password, user -> { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(context.getString(R.string.pref_remember), remember); if (remember) { editor.putString(context.getString(R.string.username), username); editor.putString(context.getString(R.string.password), password); } editor.apply(); loginResult.setValue(new LoginResult(user)); }, error -> { loginResult.setValue(new LoginResult(R.string.login_failed)); error.printStackTrace(); }); } private SharedPreferences getSharedPreferences(Context context) { return context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE); } public void loadFormIfRemembered(Context context) { SharedPreferences sharedPreferences = getSharedPreferences(context); boolean remember = sharedPreferences.getBoolean(context.getString(R.string.pref_remember), false); if (remember) { String username = sharedPreferences.getString(context.getString(R.string.username), ""); String password = sharedPreferences.getString(context.getString(R.string.password), ""); loginFormState.setValue(new LoginFormState(username, password, true)); } } public void loginDataChanged(String username, String password) { if (!isUserNameValid(username)) { loginFormState.setValue(new LoginFormState(R.string.invalid_username, null)); } else if (!isPasswordValid(password)) { loginFormState.setValue(new LoginFormState(null, R.string.invalid_password)); } else { loginFormState.setValue(new LoginFormState(true)); } } // A placeholder username validation check private boolean isUserNameValid(String username) { if (username == null) { return false; } if (username.contains("@")) { return Patterns.EMAIL_ADDRESS.matcher(username).matches(); } else { return !username.trim().isEmpty(); } } // A placeholder<SUF> private boolean isPasswordValid(String password) { return password != null && password.length() > 0; } }
False
564
6
711
6
746
6
711
6
846
6
false
false
false
false
false
true
3,920
19246_4
/* ***** BEGIN LICENSE BLOCK ***** * Version: EPL 2.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * License Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.eclipse.org/legal/epl-v20.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.truffleruby.algorithms; public final class Randomizer { private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; /* constant vector a */ private static final int UMASK = 0x80000000; /* most significant w-r bits */ private static final int LMASK = 0x7fffffff; /* least significant r bits */ private final int[] state = new int[N]; private int left = 1; private final Object seed; public Randomizer() { this(0L, 0); } public Randomizer(Object seed, int s) { this.seed = seed; state[0] = s; for (int j = 1; j < N; j++) { state[j] = (1812433253 * (state[j - 1] ^ (state[j - 1] >>> 30)) + j); } } public Randomizer(Object seed, int[] initKey) { this(seed, 19650218); int len = initKey.length; int i = 1; int j = 0; int k = Math.max(N, len); for (; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1664525)) + initKey[j] + j; i++; j++; if (i >= N) { state[0] = state[N - 1]; i = 1; } if (j >= len) { j = 0; } } for (k = N - 1; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1566083941)) - i; i++; if (i >= N) { state[0] = state[N - 1]; i = 1; } } state[0] = 0x80000000; } public Object getSeed() { return seed; } // MRI: genrand_int32 of mt19937.c public int unsynchronizedGenrandInt32() { if (--left <= 0) { nextState(); } int y = state[N - left]; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y; } private void nextState() { int p = 0; left = N; for (int j = N - M + 1; --j > 0; p++) { state[p] = state[p + M] ^ twist(state[p], state[p + 1]); } for (int j = M; --j > 0; p++) { state[p] = state[p + M - N] ^ twist(state[p], state[p + 1]); } state[p] = state[p + M - N] ^ twist(state[p], state[0]); } private static int mixbits(int u, int v) { return (u & UMASK) | (v & LMASK); } private static int twist(int u, int v) { return (mixbits(u, v) >>> 1) ^ (((v & 1) != 0) ? MATRIX_A : 0); } }
oracle/truffleruby
src/main/java/org/truffleruby/algorithms/Randomizer.java
1,362
// MRI: genrand_int32 of mt19937.c
line_comment
nl
/* ***** BEGIN LICENSE BLOCK ***** * Version: EPL 2.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Eclipse Public * License Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.eclipse.org/legal/epl-v20.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the EPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the EPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.truffleruby.algorithms; public final class Randomizer { private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; /* constant vector a */ private static final int UMASK = 0x80000000; /* most significant w-r bits */ private static final int LMASK = 0x7fffffff; /* least significant r bits */ private final int[] state = new int[N]; private int left = 1; private final Object seed; public Randomizer() { this(0L, 0); } public Randomizer(Object seed, int s) { this.seed = seed; state[0] = s; for (int j = 1; j < N; j++) { state[j] = (1812433253 * (state[j - 1] ^ (state[j - 1] >>> 30)) + j); } } public Randomizer(Object seed, int[] initKey) { this(seed, 19650218); int len = initKey.length; int i = 1; int j = 0; int k = Math.max(N, len); for (; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1664525)) + initKey[j] + j; i++; j++; if (i >= N) { state[0] = state[N - 1]; i = 1; } if (j >= len) { j = 0; } } for (k = N - 1; k > 0; k--) { state[i] = (state[i] ^ ((state[i - 1] ^ (state[i - 1] >>> 30)) * 1566083941)) - i; i++; if (i >= N) { state[0] = state[N - 1]; i = 1; } } state[0] = 0x80000000; } public Object getSeed() { return seed; } // MRI: genrand_int32<SUF> public int unsynchronizedGenrandInt32() { if (--left <= 0) { nextState(); } int y = state[N - left]; /* Tempering */ y ^= (y >>> 11); y ^= (y << 7) & 0x9d2c5680; y ^= (y << 15) & 0xefc60000; y ^= (y >>> 18); return y; } private void nextState() { int p = 0; left = N; for (int j = N - M + 1; --j > 0; p++) { state[p] = state[p + M] ^ twist(state[p], state[p + 1]); } for (int j = M; --j > 0; p++) { state[p] = state[p + M - N] ^ twist(state[p], state[p + 1]); } state[p] = state[p + M - N] ^ twist(state[p], state[0]); } private static int mixbits(int u, int v) { return (u & UMASK) | (v & LMASK); } private static int twist(int u, int v) { return (mixbits(u, v) >>> 1) ^ (((v & 1) != 0) ? MATRIX_A : 0); } }
False
1,208
16
1,289
19
1,357
18
1,289
19
1,455
20
false
false
false
false
false
true
2,333
142291_17
package com.github.captain_miao.agera.tutorial.helper; import android.databinding.BindingAdapter; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; import com.github.captain_miao.agera.tutorial.R; import com.squareup.picasso.MemoryPolicy; import com.squareup.picasso.Picasso; /** * @author YanLu * @since 16/4/25 */ public class PicassoBinding { private static final String TAG = "PicassoBinding"; @BindingAdapter({"imageUrl"}) public static void imageLoader(ImageView imageView, String url) { // Picasso.Builder builder = new Picasso.Builder(imageView.getContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); // builder.build().load(url).into(imageView); Picasso.with(imageView.getContext()).load(url).into(imageView); } @BindingAdapter({"imageUrl", "error"}) public static void imageLoader(ImageView imageView, String url, Drawable error) { // Picasso.Builder builder = new Picasso.Builder(imageView.getContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); // builder.build() // .load(url) // .error(error) // .into(imageView); Picasso.with(imageView.getContext()).load(url).error(error).into(imageView); } @BindingAdapter({"compressImageUrl"}) public static void loadImageCompress(ImageView imageView, String url) { //large -> b middle // Picasso.Builder builder = new Picasso.Builder(imageView.getContext().getApplicationContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); //recycle bitmap // Drawable drawable = imageView.getDrawable(); // if (drawable instanceof BitmapDrawable) { // imageView.setImageDrawable(null); // Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); // Log.d(TAG, "recycle bitmap, w:" + bitmap.getWidth() + ", h:" + bitmap.getHeight()); // bitmap.recycle(); // } Picasso.with(imageView.getContext().getApplicationContext()) .load(url) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) .placeholder(R.drawable.ic_image_load_place_holder) .config(Bitmap.Config.RGB_565) .tag(PicassoOnScrollListener.TAG) .into(imageView); } @BindingAdapter({"android:src"}) public static void setImageViewResource(ImageView imageView, int resource) { imageView.setImageResource(resource); } @BindingAdapter("{imageBitmap}") public static void setImageViewBitmap(ImageView iv, Bitmap bitmap) { iv.setImageBitmap(bitmap); } // @BindingAdapter({"imageUrl", "error", "android:clickable"}) // public static void imageLoader(ImageView imageView, String url, Drawable error, boolean clickable) { // Picasso.Builder builder = new Picasso.Builder(imageView.getContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); // builder.build() // .load(url) // .error(error) // .into(imageView); // Log.d(TAG, "android:clickable = " + clickable); // //// Picasso.with(imageView.getContext()).load(url).error(error).into(imageView); // } }
captain-miao/AndroidAgeraTutorial
app/src/main/java/com/github/captain_miao/agera/tutorial/helper/PicassoBinding.java
1,239
// Log.d(TAG, "recycle bitmap, w:" + bitmap.getWidth() + ", h:" + bitmap.getHeight());
line_comment
nl
package com.github.captain_miao.agera.tutorial.helper; import android.databinding.BindingAdapter; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.ImageView; import com.github.captain_miao.agera.tutorial.R; import com.squareup.picasso.MemoryPolicy; import com.squareup.picasso.Picasso; /** * @author YanLu * @since 16/4/25 */ public class PicassoBinding { private static final String TAG = "PicassoBinding"; @BindingAdapter({"imageUrl"}) public static void imageLoader(ImageView imageView, String url) { // Picasso.Builder builder = new Picasso.Builder(imageView.getContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); // builder.build().load(url).into(imageView); Picasso.with(imageView.getContext()).load(url).into(imageView); } @BindingAdapter({"imageUrl", "error"}) public static void imageLoader(ImageView imageView, String url, Drawable error) { // Picasso.Builder builder = new Picasso.Builder(imageView.getContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); // builder.build() // .load(url) // .error(error) // .into(imageView); Picasso.with(imageView.getContext()).load(url).error(error).into(imageView); } @BindingAdapter({"compressImageUrl"}) public static void loadImageCompress(ImageView imageView, String url) { //large -> b middle // Picasso.Builder builder = new Picasso.Builder(imageView.getContext().getApplicationContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); //recycle bitmap // Drawable drawable = imageView.getDrawable(); // if (drawable instanceof BitmapDrawable) { // imageView.setImageDrawable(null); // Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); // Log.d(TAG, "recycle<SUF> // bitmap.recycle(); // } Picasso.with(imageView.getContext().getApplicationContext()) .load(url) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) .placeholder(R.drawable.ic_image_load_place_holder) .config(Bitmap.Config.RGB_565) .tag(PicassoOnScrollListener.TAG) .into(imageView); } @BindingAdapter({"android:src"}) public static void setImageViewResource(ImageView imageView, int resource) { imageView.setImageResource(resource); } @BindingAdapter("{imageBitmap}") public static void setImageViewBitmap(ImageView iv, Bitmap bitmap) { iv.setImageBitmap(bitmap); } // @BindingAdapter({"imageUrl", "error", "android:clickable"}) // public static void imageLoader(ImageView imageView, String url, Drawable error, boolean clickable) { // Picasso.Builder builder = new Picasso.Builder(imageView.getContext()); // builder.listener(new Picasso.Listener() { // @Override // public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) { // exception.printStackTrace(); // Log.e("Picasso Error", uri.toString()); // } // }); // builder.build() // .load(url) // .error(error) // .into(imageView); // Log.d(TAG, "android:clickable = " + clickable); // //// Picasso.with(imageView.getContext()).load(url).error(error).into(imageView); // } }
False
853
25
1,043
28
1,025
28
1,043
28
1,164
31
false
false
false
false
false
true
1,620
31495_9
package com.example.android.roomwordssample.datastorage; import android.app.Application; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.os.AsyncTask; import android.util.Log; import com.example.android.roomwordssample.domain.LoginData; import com.example.android.roomwordssample.domain.LoginResponse; import com.example.android.roomwordssample.domain.User; import com.example.android.roomwordssample.domain.Word; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class UserRepository { private UserDao mUserDao; private MutableLiveData<User> mUser; private MutableLiveData<User> mUserProfile; private static volatile UserRepository instance; private final static String TAG = UserRepository.class.getSimpleName(); // Private - Singleton pattern! private UserRepository(Application application) { // Niet vergeten, nullpointer als je deze niet initialiseert zoals hieronder. mUser = new MutableLiveData<>(); mUserProfile = new MutableLiveData<>(); } // Get instance of Singleton WordRepository public static UserRepository getInstance(Application application) { if (instance == null) { instance = new UserRepository(application); } return instance; } // Room executes all queries on a separate thread. // Observed LiveData will notify the observer when the data has changed. public LiveData<User> getUser() { return mUser; } public void login(String emailAdress, String password) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://shareameal-api.herokuapp.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ShareAMealApiService service = retrofit.create(ShareAMealApiService.class); LoginData body = new LoginData(emailAdress, password); Log.d(TAG, "Calling login on service"); Call<LoginResponse> call = service.login(body); call.enqueue(new Callback<LoginResponse>() { @Override public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) { User loggedInUser = response.body().getResult(); mUser.setValue(loggedInUser); Log.d(TAG, "onPostExecute user logged in: " + loggedInUser.getDisplayName()); } @Override public void onFailure(Call<LoginResponse> call, Throwable t) { Log.d(TAG, "Error logging in: " + t.getMessage()); } }); } /** * Om het UserProfile op te halen moet de user eerst ingelogd zijn. We sturen een * JWT token mee om de user te identificeren/authenticeren. Als dat succesvol is * krijgen we het profile van de ingelogde user terug. */ public void getUserProfile(String jwtToken) { // Gebruik Retrofit om op de API in te loggen Log.d(TAG, "getProfile - User moet ingelogd zijn!"); new UserProfileAsyncTask().execute(jwtToken); } public LiveData<User> userProfile() { return mUserProfile; } public void logout() { // TODO: revoke authentication } /** * Toegevoegd om login asynchroon te maken * <p> * Let op: in dit geval is het profile dat we terug krijgen toevallig precies hetzelfde * als de LoginResponse die we al eerder gemaakt hebben. We hoeven dus geen nieuw Response * class te maken. Als je een ander API endpoint aanspreekt moet je dat wel doen! */ private class UserProfileAsyncTask extends AsyncTask<String, Void, LoginResponse> { @Override protected LoginResponse doInBackground(String... strings) { // Todo: check of we een token hebben, anders null of errormelding // De server authenticatie vereist een authorizatie header in de vorm // "Bearer <jwt token>". Dat is vastgelegd in de JWT specificatie. // String token = "Bearer " + strings[0]; try { // handle loggedInUser authentication Log.d(TAG, "doInBackground - stuur token mee"); Gson gson = new GsonBuilder() .setLenient() .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://shareameal-api.herokuapp.com/") .addConverterFactory(GsonConverterFactory.create(gson)) .build(); ShareAMealApiService service = retrofit.create(ShareAMealApiService.class); Log.d(TAG, "Calling getProfile on service - sending JWT Token!"); Call<LoginResponse> call = service.getUserProfile(token); Response<LoginResponse> response = call.execute(); Log.d(TAG, "Executed call, response.code = " + response.code()); if (response.isSuccessful()) { LoginResponse loginResponse = response.body(); Log.d(TAG, "Got result " + loginResponse.getResult().firstName); return loginResponse; } else { Log.d(TAG, "Error logging in: " + response.message()); return null; } } catch (Exception e) { Log.e(TAG, "Exception: " + e); return null; } } @Override protected void onPostExecute(LoginResponse result) { if (result != null) { User userProfile = result.getResult(); mUserProfile.setValue(userProfile); Log.d(TAG, "onPostExecute user profile found : " + userProfile.getDisplayName()); } else { // User niet ingelogd, doe hier iets beters. } } } }
Sno3t/EverythingSchool
Periode1.3/Programmeren-3/RetrofitLogin/app/src/main/java/com/example/android/roomwordssample/datastorage/UserRepository.java
1,650
// Todo: check of we een token hebben, anders null of errormelding
line_comment
nl
package com.example.android.roomwordssample.datastorage; import android.app.Application; import android.arch.lifecycle.LiveData; import android.arch.lifecycle.MutableLiveData; import android.os.AsyncTask; import android.util.Log; import com.example.android.roomwordssample.domain.LoginData; import com.example.android.roomwordssample.domain.LoginResponse; import com.example.android.roomwordssample.domain.User; import com.example.android.roomwordssample.domain.Word; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class UserRepository { private UserDao mUserDao; private MutableLiveData<User> mUser; private MutableLiveData<User> mUserProfile; private static volatile UserRepository instance; private final static String TAG = UserRepository.class.getSimpleName(); // Private - Singleton pattern! private UserRepository(Application application) { // Niet vergeten, nullpointer als je deze niet initialiseert zoals hieronder. mUser = new MutableLiveData<>(); mUserProfile = new MutableLiveData<>(); } // Get instance of Singleton WordRepository public static UserRepository getInstance(Application application) { if (instance == null) { instance = new UserRepository(application); } return instance; } // Room executes all queries on a separate thread. // Observed LiveData will notify the observer when the data has changed. public LiveData<User> getUser() { return mUser; } public void login(String emailAdress, String password) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://shareameal-api.herokuapp.com/") .addConverterFactory(GsonConverterFactory.create()) .build(); ShareAMealApiService service = retrofit.create(ShareAMealApiService.class); LoginData body = new LoginData(emailAdress, password); Log.d(TAG, "Calling login on service"); Call<LoginResponse> call = service.login(body); call.enqueue(new Callback<LoginResponse>() { @Override public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) { User loggedInUser = response.body().getResult(); mUser.setValue(loggedInUser); Log.d(TAG, "onPostExecute user logged in: " + loggedInUser.getDisplayName()); } @Override public void onFailure(Call<LoginResponse> call, Throwable t) { Log.d(TAG, "Error logging in: " + t.getMessage()); } }); } /** * Om het UserProfile op te halen moet de user eerst ingelogd zijn. We sturen een * JWT token mee om de user te identificeren/authenticeren. Als dat succesvol is * krijgen we het profile van de ingelogde user terug. */ public void getUserProfile(String jwtToken) { // Gebruik Retrofit om op de API in te loggen Log.d(TAG, "getProfile - User moet ingelogd zijn!"); new UserProfileAsyncTask().execute(jwtToken); } public LiveData<User> userProfile() { return mUserProfile; } public void logout() { // TODO: revoke authentication } /** * Toegevoegd om login asynchroon te maken * <p> * Let op: in dit geval is het profile dat we terug krijgen toevallig precies hetzelfde * als de LoginResponse die we al eerder gemaakt hebben. We hoeven dus geen nieuw Response * class te maken. Als je een ander API endpoint aanspreekt moet je dat wel doen! */ private class UserProfileAsyncTask extends AsyncTask<String, Void, LoginResponse> { @Override protected LoginResponse doInBackground(String... strings) { // Todo: check<SUF> // De server authenticatie vereist een authorizatie header in de vorm // "Bearer <jwt token>". Dat is vastgelegd in de JWT specificatie. // String token = "Bearer " + strings[0]; try { // handle loggedInUser authentication Log.d(TAG, "doInBackground - stuur token mee"); Gson gson = new GsonBuilder() .setLenient() .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://shareameal-api.herokuapp.com/") .addConverterFactory(GsonConverterFactory.create(gson)) .build(); ShareAMealApiService service = retrofit.create(ShareAMealApiService.class); Log.d(TAG, "Calling getProfile on service - sending JWT Token!"); Call<LoginResponse> call = service.getUserProfile(token); Response<LoginResponse> response = call.execute(); Log.d(TAG, "Executed call, response.code = " + response.code()); if (response.isSuccessful()) { LoginResponse loginResponse = response.body(); Log.d(TAG, "Got result " + loginResponse.getResult().firstName); return loginResponse; } else { Log.d(TAG, "Error logging in: " + response.message()); return null; } } catch (Exception e) { Log.e(TAG, "Exception: " + e); return null; } } @Override protected void onPostExecute(LoginResponse result) { if (result != null) { User userProfile = result.getResult(); mUserProfile.setValue(userProfile); Log.d(TAG, "onPostExecute user profile found : " + userProfile.getDisplayName()); } else { // User niet ingelogd, doe hier iets beters. } } } }
True
1,203
17
1,408
19
1,413
15
1,408
19
1,659
19
false
false
false
false
false
true
2,427
44285_5
import java.util.Arrays; import java.util.Scanner; /** * Game of Change * <p> * Based on the Basic game of Change here * https://github.com/coding-horror/basic-computer-games/blob/main/22%20Change/change.bas * <p> * Note: The idea was to create a version of the 1970's Basic game in Java, without introducing * new features - no additional text, error checking, etc has been added. */ public class Change { // Used for keyboard input private final Scanner kbScanner; private enum GAME_STATE { START_GAME, INPUT, CALCULATE, END_GAME, GAME_OVER } // Current game state private GAME_STATE gameState; // Amount of change needed to be given private double change; public Change() { kbScanner = new Scanner(System.in); gameState = GAME_STATE.START_GAME; } /** * Main game loop */ public void play() { do { switch (gameState) { case START_GAME: intro(); gameState = GAME_STATE.INPUT; break; case INPUT: double costOfItem = displayTextAndGetNumber("COST OF ITEM "); double amountPaid = displayTextAndGetNumber("AMOUNT OF PAYMENT "); change = amountPaid - costOfItem; if (change == 0) { // No change needed System.out.println("CORRECT AMOUNT, THANK YOU."); gameState = GAME_STATE.END_GAME; } else if (change < 0) { System.out.println("YOU HAVE SHORT-CHANGES ME $" + (costOfItem - amountPaid)); // Don't change game state so it will loop back and try again } else { // Change needed. gameState = GAME_STATE.CALCULATE; } break; case CALCULATE: System.out.println("YOUR CHANGE, $" + change); calculateChange(); gameState = GAME_STATE.END_GAME; break; case END_GAME: System.out.println("THANK YOU, COME AGAIN"); System.out.println(); gameState = GAME_STATE.INPUT; } } while (gameState != GAME_STATE.GAME_OVER); } /** * Calculate and output the change required for the purchase based on * what money was paid. */ private void calculateChange() { double originalChange = change; int tenDollarBills = (int) change / 10; if (tenDollarBills > 0) { System.out.println(tenDollarBills + " TEN DOLLAR BILL(S)"); } change = originalChange - (tenDollarBills * 10); int fiveDollarBills = (int) change / 5; if (fiveDollarBills > 0) { System.out.println(fiveDollarBills + " FIVE DOLLAR BILL(S)"); } change = originalChange - (tenDollarBills * 10 + fiveDollarBills * 5); int oneDollarBills = (int) change; if (oneDollarBills > 0) { System.out.println(oneDollarBills + " ONE DOLLAR BILL(S)"); } change = originalChange - (tenDollarBills * 10 + fiveDollarBills * 5 + oneDollarBills); change = change * 100; double cents = change; int halfDollars = (int) change / 50; if (halfDollars > 0) { System.out.println(halfDollars + " ONE HALF DOLLAR(S)"); } change = cents - (halfDollars * 50); int quarters = (int) change / 25; if (quarters > 0) { System.out.println(quarters + " QUARTER(S)"); } change = cents - (halfDollars * 50 + quarters * 25); int dimes = (int) change / 10; if (dimes > 0) { System.out.println(dimes + " DIME(S)"); } change = cents - (halfDollars * 50 + quarters * 25 + dimes * 10); int nickels = (int) change / 5; if (nickels > 0) { System.out.println(nickels + " NICKEL(S)"); } change = cents - (halfDollars * 50 + quarters * 25 + dimes * 10 + nickels * 5); int pennies = (int) (change + .5); if (pennies > 0) { System.out.println(pennies + " PENNY(S)"); } } private void intro() { System.out.println(simulateTabs(33) + "CHANGE"); System.out.println(simulateTabs(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println(); System.out.println("I, YOUR FRIENDLY MICROCOMPUTER, WILL DETERMINE"); System.out.println("THE CORRECT CHANGE FOR ITEMS COSTING UP TO $100."); System.out.println(); } /* * Print a message on the screen, then accept input from Keyboard. * Converts input to a Double * * @param text message to be displayed on screen. * @return what was typed by the player. */ private double displayTextAndGetNumber(String text) { return Double.parseDouble(displayTextAndGetInput(text)); } /* * Print a message on the screen, then accept input from Keyboard. * * @param text message to be displayed on screen. * @return what was typed by the player. */ private String displayTextAndGetInput(String text) { System.out.print(text); return kbScanner.next(); } /** * Simulate the old basic tab(xx) command which indented text by xx spaces. * * @param spaces number of spaces required * @return String with number of spaces */ private String simulateTabs(int spaces) { char[] spacesTemp = new char[spaces]; Arrays.fill(spacesTemp, ' '); return new String(spacesTemp); } }
coding-horror/basic-computer-games
22_Change/java/src/Change.java
1,746
// No change needed
line_comment
nl
import java.util.Arrays; import java.util.Scanner; /** * Game of Change * <p> * Based on the Basic game of Change here * https://github.com/coding-horror/basic-computer-games/blob/main/22%20Change/change.bas * <p> * Note: The idea was to create a version of the 1970's Basic game in Java, without introducing * new features - no additional text, error checking, etc has been added. */ public class Change { // Used for keyboard input private final Scanner kbScanner; private enum GAME_STATE { START_GAME, INPUT, CALCULATE, END_GAME, GAME_OVER } // Current game state private GAME_STATE gameState; // Amount of change needed to be given private double change; public Change() { kbScanner = new Scanner(System.in); gameState = GAME_STATE.START_GAME; } /** * Main game loop */ public void play() { do { switch (gameState) { case START_GAME: intro(); gameState = GAME_STATE.INPUT; break; case INPUT: double costOfItem = displayTextAndGetNumber("COST OF ITEM "); double amountPaid = displayTextAndGetNumber("AMOUNT OF PAYMENT "); change = amountPaid - costOfItem; if (change == 0) { // No change<SUF> System.out.println("CORRECT AMOUNT, THANK YOU."); gameState = GAME_STATE.END_GAME; } else if (change < 0) { System.out.println("YOU HAVE SHORT-CHANGES ME $" + (costOfItem - amountPaid)); // Don't change game state so it will loop back and try again } else { // Change needed. gameState = GAME_STATE.CALCULATE; } break; case CALCULATE: System.out.println("YOUR CHANGE, $" + change); calculateChange(); gameState = GAME_STATE.END_GAME; break; case END_GAME: System.out.println("THANK YOU, COME AGAIN"); System.out.println(); gameState = GAME_STATE.INPUT; } } while (gameState != GAME_STATE.GAME_OVER); } /** * Calculate and output the change required for the purchase based on * what money was paid. */ private void calculateChange() { double originalChange = change; int tenDollarBills = (int) change / 10; if (tenDollarBills > 0) { System.out.println(tenDollarBills + " TEN DOLLAR BILL(S)"); } change = originalChange - (tenDollarBills * 10); int fiveDollarBills = (int) change / 5; if (fiveDollarBills > 0) { System.out.println(fiveDollarBills + " FIVE DOLLAR BILL(S)"); } change = originalChange - (tenDollarBills * 10 + fiveDollarBills * 5); int oneDollarBills = (int) change; if (oneDollarBills > 0) { System.out.println(oneDollarBills + " ONE DOLLAR BILL(S)"); } change = originalChange - (tenDollarBills * 10 + fiveDollarBills * 5 + oneDollarBills); change = change * 100; double cents = change; int halfDollars = (int) change / 50; if (halfDollars > 0) { System.out.println(halfDollars + " ONE HALF DOLLAR(S)"); } change = cents - (halfDollars * 50); int quarters = (int) change / 25; if (quarters > 0) { System.out.println(quarters + " QUARTER(S)"); } change = cents - (halfDollars * 50 + quarters * 25); int dimes = (int) change / 10; if (dimes > 0) { System.out.println(dimes + " DIME(S)"); } change = cents - (halfDollars * 50 + quarters * 25 + dimes * 10); int nickels = (int) change / 5; if (nickels > 0) { System.out.println(nickels + " NICKEL(S)"); } change = cents - (halfDollars * 50 + quarters * 25 + dimes * 10 + nickels * 5); int pennies = (int) (change + .5); if (pennies > 0) { System.out.println(pennies + " PENNY(S)"); } } private void intro() { System.out.println(simulateTabs(33) + "CHANGE"); System.out.println(simulateTabs(15) + "CREATIVE COMPUTING MORRISTOWN, NEW JERSEY"); System.out.println(); System.out.println("I, YOUR FRIENDLY MICROCOMPUTER, WILL DETERMINE"); System.out.println("THE CORRECT CHANGE FOR ITEMS COSTING UP TO $100."); System.out.println(); } /* * Print a message on the screen, then accept input from Keyboard. * Converts input to a Double * * @param text message to be displayed on screen. * @return what was typed by the player. */ private double displayTextAndGetNumber(String text) { return Double.parseDouble(displayTextAndGetInput(text)); } /* * Print a message on the screen, then accept input from Keyboard. * * @param text message to be displayed on screen. * @return what was typed by the player. */ private String displayTextAndGetInput(String text) { System.out.print(text); return kbScanner.next(); } /** * Simulate the old basic tab(xx) command which indented text by xx spaces. * * @param spaces number of spaces required * @return String with number of spaces */ private String simulateTabs(int spaces) { char[] spacesTemp = new char[spaces]; Arrays.fill(spacesTemp, ' '); return new String(spacesTemp); } }
False
1,392
4
1,514
4
1,560
4
1,514
4
1,832
4
false
false
false
false
false
true
965
17836_7
package Server; import Classes.*; import Interfaces.IGameManager; import Interfaces.IGameObject; import Interfaces.IUser; import LibGDXSerialzableClasses.SerializableColor; import com.badlogic.gdx.math.Vector2; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.*; /** * Created by michel on 15-11-2016. */ public class ServerGameManger extends UnicastRemoteObject implements IGameManager { private String name; private List<IGameObject> everything; private Map<String, List<IGameObject>> idObjects; //TODO gebruik list voor het opslaan voor eigen objecten niet voor opslaan van objecten die voor mij bedoelt zijn. private ArrayList<User> userList; private ArrayList<String> stringUserList; private Random r = new Random(); private Level level; private float matchTime = 5f * 60 * 1000; private transient Timer matchTimer; private boolean matchStarted; private PreGameManager pgm; public ServerGameManger() throws RemoteException { Constructor(); } public ServerGameManger(String name) throws RemoteException { Constructor(); this.name = name; } public ServerGameManger(String name, PreGameManager preGameManager) throws RemoteException { Constructor(); this.name = name; pgm = preGameManager; } private <T> ArrayList<T> getObjectList(ArrayList<Object> list, Class<T> tocast) { ArrayList<T> returnList = new ArrayList<>(); for (Object go : list) { try { T igo = tocast.cast(go); returnList.add(igo); } catch (ClassCastException e) { System.out.println("Cast Error " + e.getMessage()); } } return returnList; } @Override public List<IGameObject> GetTick(String id) { if (id.equals("Spectator")) { return GetEverything(); } List<IGameObject> allbutmeobject = new ArrayList<>(); for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet()) { if (!objlist.getKey().equals(id)) { //System.out.println("Adding from " + objlist.getKey() + " TO " + id); allbutmeobject.addAll(objlist.getValue()); } } allbutmeobject.addAll(everything); return allbutmeobject; } public List<IGameObject> GetEverything() { List<IGameObject> alllist = new ArrayList<>(); for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet()) { alllist.addAll(objlist.getValue()); } return alllist; } @Override public void SetTick(String id, IGameObject object) { //System.out.println("New Object From : " + id); /* idObjects.putIfAbsent(id, new ArrayList<>(everything)); //Waaneer id niet bestaat voeg alles toe aan die speler everything.add(object); // voeg nieuw object toe aan iedereen idObjects.entrySet().stream().filter(entry -> !entry.getKey().equals(id)).forEach(entry -> entry.getValue().add(object)); //voeg object toe aan iedereen behalve ik */ if(!matchStarted){ try { startMatch(); } catch (RemoteException e) { e.printStackTrace(); } } idObjects.putIfAbsent(id, new ArrayList<>()); idObjects.get(id).add(object); } @Override public void UpdateTick(String id, long objectId, Vector2 newPostion, float newRotation) throws RemoteException { for(IGameObject obj : idObjects.get(id)) { if (obj.getID() == objectId) { obj.setPosition(newPostion); obj.setRotation(newRotation); break; } } } @Override public void UpdateTick(String id, IGameObject object) throws RemoteException { //System.out.println("Update Object From : " + id); /* //Update de position voor iedereen for (IGameObject go : everything) { if (go.getID() == object.getID()) { go.setPosition(object.getPosition()); go.setRotation(object.getRotation()); break; } } //Update de position voor iedereen behalve mij for (Map.Entry<String, List<IGameObject>> entry : idObjects.entrySet()) { if (!entry.getKey().equals(id)) { for (IGameObject obj : entry.getValue()) { if (obj.getID() == object.getID()) { obj.setPosition(object.getPosition()); obj.setRotation(object.getRotation()); break; } } } }*/ for(IGameObject obj : idObjects.get(id)) { if (obj.getID() == object.getID()) { obj.setPosition(object.getPosition()); obj.setRotation(object.getRotation()); break; } } } private void AddForEveryOne() { } private void AddForEveryOneButMe() { } private void AddForMe() { } private void RemoveForEveryOne() { } private void RemoveForEveryOneButMe() { } private void RemoveForMe() { } private void Constructor() throws RemoteException { everything = new ArrayList<>(); userList = new ArrayList<>(); stringUserList = new ArrayList<>(); idObjects = new HashMap<>(100); level = new Level(); matchTimer = new Timer(); } @Override public void DeleteTick(String id, IGameObject object) throws RemoteException { //haald object overal weg waar hij bestaat //idObjects.entrySet().forEach(stringListEntry -> stringListEntry.getValue().removeIf(gameObject -> gameObject.getID() == object.getID())); //everything.removeIf(gameObject -> gameObject.getID() == object.getID()); idObjects.get(id).removeIf(obj -> obj.getID() == object.getID()); } @Override public void DeleteUser(String id) { //delete alles van een user //idObjects.entrySet().forEach(set -> everything.removeIf(obj -> obj.getID() == ((IGameObject) set.getValue()).getID())); //idObjects.entrySet().removeIf(keyid -> Objects.equals(keyid.getKey(), id)); /* if (idObjects.get(id) instanceof User) { User user = (User) idObjects.get(id); for (Object object : everything) { if (object instanceof Player) { if (user.getName().equals(((Player) object).getName())) { Player player = (Player) object; user.UpdateData(player.getKills(), player.getDeaths(), player.getShotsHit(), player.getShots(), player.getKills() >= 10 ? true : false); } } } }*/ idObjects.remove(id); userList.removeIf(user -> user.getName().equals(id)); } @Override public Level GetLevel() throws RemoteException { return level; } @Override public ArrayList<String> getUsers() throws RemoteException { stringUserList.clear(); for (User u : userList) { stringUserList.add(u.getName()); } return stringUserList; } @Override public void addUser(IUser user) throws RemoteException { userList.add((User) user); } @Override public void startMatch() throws RemoteException { System.out.println("Match start"); final ServerGameManger me = this; matchTimer.schedule(new TimerTask() { @Override public void run() { System.out.println("game over bitch!!"); matchTimer.cancel(); try { StopGameObject sgo = new StopGameObject(); everything.add(sgo); } catch (RemoteException e) { e.printStackTrace(); } pgm.StopLobby(me.getName()); userList.forEach( u -> pgm.getConnectionInstance().UpdateStats(u)); } },(long) matchTime, (long) matchTime); matchStarted = true; } public IGameObject CreatePlayer(String name) throws RemoteException { Player p; p = new Player(false); p.setName(name); p.setColor(SerializableColor.getRandomColor()); return p; } public String getName() { return name; } public void addUser(User user) { userList.add(user); } }
Lehcim1995/PTS3-Game
server/src/main/java/Server/ServerGameManger.java
2,505
//haald object overal weg waar hij bestaat
line_comment
nl
package Server; import Classes.*; import Interfaces.IGameManager; import Interfaces.IGameObject; import Interfaces.IUser; import LibGDXSerialzableClasses.SerializableColor; import com.badlogic.gdx.math.Vector2; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.*; /** * Created by michel on 15-11-2016. */ public class ServerGameManger extends UnicastRemoteObject implements IGameManager { private String name; private List<IGameObject> everything; private Map<String, List<IGameObject>> idObjects; //TODO gebruik list voor het opslaan voor eigen objecten niet voor opslaan van objecten die voor mij bedoelt zijn. private ArrayList<User> userList; private ArrayList<String> stringUserList; private Random r = new Random(); private Level level; private float matchTime = 5f * 60 * 1000; private transient Timer matchTimer; private boolean matchStarted; private PreGameManager pgm; public ServerGameManger() throws RemoteException { Constructor(); } public ServerGameManger(String name) throws RemoteException { Constructor(); this.name = name; } public ServerGameManger(String name, PreGameManager preGameManager) throws RemoteException { Constructor(); this.name = name; pgm = preGameManager; } private <T> ArrayList<T> getObjectList(ArrayList<Object> list, Class<T> tocast) { ArrayList<T> returnList = new ArrayList<>(); for (Object go : list) { try { T igo = tocast.cast(go); returnList.add(igo); } catch (ClassCastException e) { System.out.println("Cast Error " + e.getMessage()); } } return returnList; } @Override public List<IGameObject> GetTick(String id) { if (id.equals("Spectator")) { return GetEverything(); } List<IGameObject> allbutmeobject = new ArrayList<>(); for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet()) { if (!objlist.getKey().equals(id)) { //System.out.println("Adding from " + objlist.getKey() + " TO " + id); allbutmeobject.addAll(objlist.getValue()); } } allbutmeobject.addAll(everything); return allbutmeobject; } public List<IGameObject> GetEverything() { List<IGameObject> alllist = new ArrayList<>(); for (Map.Entry<String, List<IGameObject>> objlist : idObjects.entrySet()) { alllist.addAll(objlist.getValue()); } return alllist; } @Override public void SetTick(String id, IGameObject object) { //System.out.println("New Object From : " + id); /* idObjects.putIfAbsent(id, new ArrayList<>(everything)); //Waaneer id niet bestaat voeg alles toe aan die speler everything.add(object); // voeg nieuw object toe aan iedereen idObjects.entrySet().stream().filter(entry -> !entry.getKey().equals(id)).forEach(entry -> entry.getValue().add(object)); //voeg object toe aan iedereen behalve ik */ if(!matchStarted){ try { startMatch(); } catch (RemoteException e) { e.printStackTrace(); } } idObjects.putIfAbsent(id, new ArrayList<>()); idObjects.get(id).add(object); } @Override public void UpdateTick(String id, long objectId, Vector2 newPostion, float newRotation) throws RemoteException { for(IGameObject obj : idObjects.get(id)) { if (obj.getID() == objectId) { obj.setPosition(newPostion); obj.setRotation(newRotation); break; } } } @Override public void UpdateTick(String id, IGameObject object) throws RemoteException { //System.out.println("Update Object From : " + id); /* //Update de position voor iedereen for (IGameObject go : everything) { if (go.getID() == object.getID()) { go.setPosition(object.getPosition()); go.setRotation(object.getRotation()); break; } } //Update de position voor iedereen behalve mij for (Map.Entry<String, List<IGameObject>> entry : idObjects.entrySet()) { if (!entry.getKey().equals(id)) { for (IGameObject obj : entry.getValue()) { if (obj.getID() == object.getID()) { obj.setPosition(object.getPosition()); obj.setRotation(object.getRotation()); break; } } } }*/ for(IGameObject obj : idObjects.get(id)) { if (obj.getID() == object.getID()) { obj.setPosition(object.getPosition()); obj.setRotation(object.getRotation()); break; } } } private void AddForEveryOne() { } private void AddForEveryOneButMe() { } private void AddForMe() { } private void RemoveForEveryOne() { } private void RemoveForEveryOneButMe() { } private void RemoveForMe() { } private void Constructor() throws RemoteException { everything = new ArrayList<>(); userList = new ArrayList<>(); stringUserList = new ArrayList<>(); idObjects = new HashMap<>(100); level = new Level(); matchTimer = new Timer(); } @Override public void DeleteTick(String id, IGameObject object) throws RemoteException { //haald object<SUF> //idObjects.entrySet().forEach(stringListEntry -> stringListEntry.getValue().removeIf(gameObject -> gameObject.getID() == object.getID())); //everything.removeIf(gameObject -> gameObject.getID() == object.getID()); idObjects.get(id).removeIf(obj -> obj.getID() == object.getID()); } @Override public void DeleteUser(String id) { //delete alles van een user //idObjects.entrySet().forEach(set -> everything.removeIf(obj -> obj.getID() == ((IGameObject) set.getValue()).getID())); //idObjects.entrySet().removeIf(keyid -> Objects.equals(keyid.getKey(), id)); /* if (idObjects.get(id) instanceof User) { User user = (User) idObjects.get(id); for (Object object : everything) { if (object instanceof Player) { if (user.getName().equals(((Player) object).getName())) { Player player = (Player) object; user.UpdateData(player.getKills(), player.getDeaths(), player.getShotsHit(), player.getShots(), player.getKills() >= 10 ? true : false); } } } }*/ idObjects.remove(id); userList.removeIf(user -> user.getName().equals(id)); } @Override public Level GetLevel() throws RemoteException { return level; } @Override public ArrayList<String> getUsers() throws RemoteException { stringUserList.clear(); for (User u : userList) { stringUserList.add(u.getName()); } return stringUserList; } @Override public void addUser(IUser user) throws RemoteException { userList.add((User) user); } @Override public void startMatch() throws RemoteException { System.out.println("Match start"); final ServerGameManger me = this; matchTimer.schedule(new TimerTask() { @Override public void run() { System.out.println("game over bitch!!"); matchTimer.cancel(); try { StopGameObject sgo = new StopGameObject(); everything.add(sgo); } catch (RemoteException e) { e.printStackTrace(); } pgm.StopLobby(me.getName()); userList.forEach( u -> pgm.getConnectionInstance().UpdateStats(u)); } },(long) matchTime, (long) matchTime); matchStarted = true; } public IGameObject CreatePlayer(String name) throws RemoteException { Player p; p = new Player(false); p.setName(name); p.setColor(SerializableColor.getRandomColor()); return p; } public String getName() { return name; } public void addUser(User user) { userList.add(user); } }
True
1,862
11
2,053
13
2,255
9
2,053
13
2,534
11
false
false
false
false
false
true
457
41814_4
package org.example; // need to calculate complexity... Anyway, 4x exercise copy, 1x work on UI, in necessity Tue for UI // DONE: https://codingbat.com/java // IN PROGRESS: https://www.w3resource.com/java-exercises/ // https://www.idtech.com/blog/how-to-practice-java-online-with-free-coding-websites // https://pythonistaplanet.com/java-programming-exercises-with-solutions/?utm_content=cmp-true4 // 1 already 2 done 3 done 4 done 5 done // https://www.codezclub.com/java-solved-programs-problems-solutions/ // 1 done 2 done 3 done 4 done // https://code-exercises.com/ ?? vaak te moeilijk // https://www.geeksforgeeks.org/java-programming-examples/7 /* https://edabit.com/challenge/vzhWSMR2A6wDyFK2o https://edabit.com/challenge/i8bDeBaQtZg6wDGYL https://edabit.com/challenge/pzLMEsMpbCLsPXqy2 https://edabit.com/challenge/KsowZk9crJSRd9uko https://edabit.com/challenge/ZfZMvwTzcTTG2QRzA */ // more string exercises (EdaBit? CodeWars?) // Sieve of eratostenes // rondes 1, 2 [animal game] 3, 4 [animal game 2] 5[animal game 2?] 6[animal game 2>github] public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } }
EWLameijer/JavaExercises
src/main/java/org/example/Main.java
476
// https://code-exercises.com/ ?? vaak te moeilijk
line_comment
nl
package org.example; // need to calculate complexity... Anyway, 4x exercise copy, 1x work on UI, in necessity Tue for UI // DONE: https://codingbat.com/java // IN PROGRESS: https://www.w3resource.com/java-exercises/ // https://www.idtech.com/blog/how-to-practice-java-online-with-free-coding-websites // https://pythonistaplanet.com/java-programming-exercises-with-solutions/?utm_content=cmp-true4 // 1 already 2 done 3 done 4 done 5 done // https://www.codezclub.com/java-solved-programs-problems-solutions/ // 1 done 2 done 3 done 4 done // https://code-exercises.com/ ??<SUF> // https://www.geeksforgeeks.org/java-programming-examples/7 /* https://edabit.com/challenge/vzhWSMR2A6wDyFK2o https://edabit.com/challenge/i8bDeBaQtZg6wDGYL https://edabit.com/challenge/pzLMEsMpbCLsPXqy2 https://edabit.com/challenge/KsowZk9crJSRd9uko https://edabit.com/challenge/ZfZMvwTzcTTG2QRzA */ // more string exercises (EdaBit? CodeWars?) // Sieve of eratostenes // rondes 1, 2 [animal game] 3, 4 [animal game 2] 5[animal game 2?] 6[animal game 2>github] public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } }
False
379
15
428
17
415
13
428
17
482
19
false
false
false
false
false
true
761
66549_3
package Game.Models; import Framework.AI.BotInterface; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class AI implements BotInterface { private TTTGame TTTGame; private HashMap<String, Integer> possibleTurns; private char player; private int[] lastMove = new int[2]; public AI(TTTGame TTTGame, char player) { this.TTTGame = TTTGame; this.possibleTurns = new HashMap<>(); this.player = player; } public char getPlayer() { return this.player; } public int[] doTurn(char[][] board) { //check de open vakjes. //dan: check of de andere gebruiker kan winnen met een van de open vakjes. //zoja: geef dat vakje een score van 10. Sla op in mogelijke zet array //Check per vakje of de AI kan winnen ná het zetten van het vakje. Zoja: geef score van 5 aan dat vakje //Anders: geef score -1 int score; for(int y = 0; y < board.length; y++) { for(int x = 0; x < board[y].length; x++) { if(board[y][x] == ' ') { score = this.getScore(y, x, board); this.possibleTurns.put("" + y + x, score); } else { this.possibleTurns.put("" + y + x, -1); } } } System.out.println(this.possibleTurns); this.placeTurn(); // Return this turns AI move [0:x, 1:y] return this.lastMove; } private int getScore(int y, int x, char[][] board) { //board[y][x] = this.player; //check if I can win with this position if(this.checkIfICanWin(y, x, board)) { board[y][x] = ' '; return 5; } //check if the other player can win with this position if(this.checkIfOtherCanWin(y, x, board)) { board[y][x] = ' '; return 10; } board[y][x] = ' '; //check if I can with after placing this position return 0; } private boolean checkIfICanWin(int y, int x, char[][] testBoard) { testBoard[y][x] = this.player; return (testBoard[y][0] == this.player && testBoard[y][1] == this.player && testBoard[y][2] == this.player) || (testBoard[0][x] == this.player && testBoard[1][x] == this.player && testBoard[2][x] == this.player) || (testBoard[0][0] == this.player && testBoard[1][1] == this.player && testBoard[2][2] == this.player) || (testBoard[0][2] == this.player && testBoard[1][1] == this.player && testBoard[2][0] == this.player); } private boolean checkIfOtherCanWin(int y, int x, char[][] testBoard) { char player = this.oppositePlayer(); testBoard[y][x] = player; System.out.println("Huidige speler AI: " + this.player + ", andere speler: " + player); return (testBoard[y][0] == player && testBoard[y][1] == player && testBoard[y][2] == player) || (testBoard[0][x] == player && testBoard[1][x] == player && testBoard[2][x] == player) || (testBoard[0][0] == player && testBoard[1][1] == player && testBoard[2][2] == player) || (testBoard[0][2] == player && testBoard[1][1] == player && testBoard[2][0] == player); } private void placeTurn() { //Initialize the biggest key-value pair Map.Entry<String, Integer> biggest = null; //Loop through all key-value pairs in the possible turns (all potential positions) for (Map.Entry<String, Integer> entry : this.possibleTurns.entrySet()) { //If a value is bigger than the current iteration, replace the former key-value pair with this new one. //The biggest key-value pair has the higest priority if (biggest == null || entry.getValue().compareTo(biggest.getValue()) > 0) { biggest = entry; } } //Get the current playing board char[][] newBoard = this.TTTGame.getBoard(); //Subtract the x value from the key int y = Integer.valueOf(biggest.getKey().split("")[0]); //subtract the y value from the key int x = Integer.valueOf(biggest.getKey().split("")[1]); //make a new board where the AI placed his turn if(newBoard[y][x] == ' ') { newBoard[y][x] = this.player; } // use this to return the last AI move this.lastMove[0] = x; this.lastMove[1] = y; System.out.println(this.lastMove[1]+""+this.lastMove[0]); //Replace the tic-tac-toe board with the board where the AI placed his turn this.TTTGame.setBoard(newBoard); } private char oppositePlayer() { if(this.player == 'O') { return 'X'; } return 'O'; } }
Iniedergeval-Cool/tictactoe
src/Game/Models/AI.java
1,548
//Check per vakje of de AI kan winnen ná het zetten van het vakje. Zoja: geef score van 5 aan dat vakje
line_comment
nl
package Game.Models; import Framework.AI.BotInterface; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class AI implements BotInterface { private TTTGame TTTGame; private HashMap<String, Integer> possibleTurns; private char player; private int[] lastMove = new int[2]; public AI(TTTGame TTTGame, char player) { this.TTTGame = TTTGame; this.possibleTurns = new HashMap<>(); this.player = player; } public char getPlayer() { return this.player; } public int[] doTurn(char[][] board) { //check de open vakjes. //dan: check of de andere gebruiker kan winnen met een van de open vakjes. //zoja: geef dat vakje een score van 10. Sla op in mogelijke zet array //Check per<SUF> //Anders: geef score -1 int score; for(int y = 0; y < board.length; y++) { for(int x = 0; x < board[y].length; x++) { if(board[y][x] == ' ') { score = this.getScore(y, x, board); this.possibleTurns.put("" + y + x, score); } else { this.possibleTurns.put("" + y + x, -1); } } } System.out.println(this.possibleTurns); this.placeTurn(); // Return this turns AI move [0:x, 1:y] return this.lastMove; } private int getScore(int y, int x, char[][] board) { //board[y][x] = this.player; //check if I can win with this position if(this.checkIfICanWin(y, x, board)) { board[y][x] = ' '; return 5; } //check if the other player can win with this position if(this.checkIfOtherCanWin(y, x, board)) { board[y][x] = ' '; return 10; } board[y][x] = ' '; //check if I can with after placing this position return 0; } private boolean checkIfICanWin(int y, int x, char[][] testBoard) { testBoard[y][x] = this.player; return (testBoard[y][0] == this.player && testBoard[y][1] == this.player && testBoard[y][2] == this.player) || (testBoard[0][x] == this.player && testBoard[1][x] == this.player && testBoard[2][x] == this.player) || (testBoard[0][0] == this.player && testBoard[1][1] == this.player && testBoard[2][2] == this.player) || (testBoard[0][2] == this.player && testBoard[1][1] == this.player && testBoard[2][0] == this.player); } private boolean checkIfOtherCanWin(int y, int x, char[][] testBoard) { char player = this.oppositePlayer(); testBoard[y][x] = player; System.out.println("Huidige speler AI: " + this.player + ", andere speler: " + player); return (testBoard[y][0] == player && testBoard[y][1] == player && testBoard[y][2] == player) || (testBoard[0][x] == player && testBoard[1][x] == player && testBoard[2][x] == player) || (testBoard[0][0] == player && testBoard[1][1] == player && testBoard[2][2] == player) || (testBoard[0][2] == player && testBoard[1][1] == player && testBoard[2][0] == player); } private void placeTurn() { //Initialize the biggest key-value pair Map.Entry<String, Integer> biggest = null; //Loop through all key-value pairs in the possible turns (all potential positions) for (Map.Entry<String, Integer> entry : this.possibleTurns.entrySet()) { //If a value is bigger than the current iteration, replace the former key-value pair with this new one. //The biggest key-value pair has the higest priority if (biggest == null || entry.getValue().compareTo(biggest.getValue()) > 0) { biggest = entry; } } //Get the current playing board char[][] newBoard = this.TTTGame.getBoard(); //Subtract the x value from the key int y = Integer.valueOf(biggest.getKey().split("")[0]); //subtract the y value from the key int x = Integer.valueOf(biggest.getKey().split("")[1]); //make a new board where the AI placed his turn if(newBoard[y][x] == ' ') { newBoard[y][x] = this.player; } // use this to return the last AI move this.lastMove[0] = x; this.lastMove[1] = y; System.out.println(this.lastMove[1]+""+this.lastMove[0]); //Replace the tic-tac-toe board with the board where the AI placed his turn this.TTTGame.setBoard(newBoard); } private char oppositePlayer() { if(this.player == 'O') { return 'X'; } return 'O'; } }
True
1,244
34
1,357
39
1,415
31
1,357
39
1,521
37
false
false
false
false
false
true
2,558
26177_37
package com.renderapi; import java.io.*; import java.net.*; import org.json.simple.*; import org.json.simple.parser.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; class FileSaveHandler extends Thread { // Deze Streams en Socket zijn voor de file interactie op een bepaalde port. DataInputStream dataInput; DataOutputStream dataOutput; Socket sock; // de message RenderAPI.NetworkMessageType.UPLOADFILE sla ik op in clientText // deze is static en wordt door RenderCommands.doCmdSendFile() gecontroleerd. // de execution thread wacht dus netjes of deze thread haar taak gedaan heeft. static String clientText = ""; // de Server Socket // kiest zelf een vrije poort ServerSocket serverSock; // hou de actieve (dus geopende) TCP poort bij. int activePort = -1; // het JSON commando geeft filename en size. // RenderCommands.doCmdSendFile() (Die deze thread start) // stuurt deze naar de constructor. long size = 0; String project; String file; // Volgens mij is dit niet echt hard nodig // En bevindt zich er vrijwel altijd een transfer in de queue // DESIGNQUESTION uitvoerig testen van deze functionaliteit? ArrayList<TransferAttributes> transferQueue; public FileSaveHandler( long size, String projNumStr, String fileName ) { // De transfer queue this.transferQueue = new ArrayList<TransferAttributes>(); // File metadata this.size = size; this.project = projNumStr; this.file = fileName; } public int getActivePort() { // Wordt niet gebruikt return this.activePort; } public static String getClientText() { // RenderCommands.doCmdSendFile() wacht netjes of de thread een wait message heeft gestuurd. // DESIGNQUESTION Als de wait message niet gestruurd wordt, gaat dat ten koste van de latency. Testen? return FileSaveHandler.clientText; } public static void clearClientText() { // Deze is nodig om ervoor te zorgen dat er bij het eerste upload commando, get poortnummer vernieuwt. FileSaveHandler.clientText = ""; } public static String stripNewlines( String str ) { // uiteindelijk heb ik de JSON errors en messages op een regel gezet. str = str.replace("\n", "").replace("\r", ""); return str; } public void closeAll(Socket sock, ServerSocket serverSock) { // Sluit Streams en Socket try { this.dataInput.close(); this.dataOutput.close(); sock.close(); serverSock.close(); } catch (IOException ex ) { ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "Could not close: " + ex.getMessage() ); } } @Override public void run() { // Voor de file upload wait message String msg; try { // genereer een vrije TCP poort this.serverSock = new ServerSocket( 0 ); this.activePort = serverSock.getLocalPort(); } catch ( IOException ex ) { // TODO stuur de error naar de Client in plaats van de wait message? ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "Could not bind socket. File upload canceled"); return; } // Schrijf naar de server log dat de TCP connectie er is ServerLog.attachMessage( RenderAPI.MessageType.NOTICE, "FileHandler Thread created. filesize: " + this.size + " port: " + this.activePort ); // Emit de file wait boodschap msg = MessageHandler.prepareMessage( RenderAPI.NetworkMessageType.UPLOADFILE, project, size, file, this.serverSock.getLocalPort() ); // RenderCommands.doCmdSendFile() leest welke wait er is. FileSaveHandler.clientText = msg ; // Voeg de transfer toe aan de queue TransferAttributes attr; attr = new TransferAttributes(this.serverSock, this.activePort, this.file, this.size ); transferQueue.add(attr); // Debug the transfer queue for(TransferAttributes attributes: transferQueue ) { ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Transfer queue index: " + transferQueue.indexOf(attributes) + " port: " + attributes.port + " file name: \"" + attributes.fileName + "\" file size: " + attributes.fileSize ); } // Lus door de transferqueue // DESIGNQUESTION uitgebreid debuggen? for(TransferAttributes attributes: transferQueue ) { String message = ""; try { // De Thread wacht hier op een socket connectie, dit kan eventueel duren. // DESIGNQUESTION timeout installeren? this.sock = attributes.sock.accept(); this.dataInput = new DataInputStream(this.sock.getInputStream()); this.dataOutput = new DataOutputStream(this.sock.getOutputStream()); } catch ( IOException ex ) { // TODO stuur de error naar de Client in plaats van de wait message? ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IO Error: " + ex.getMessage() ); return; } // FileTransfer opent het bestand, en leest van de Socket sock. FileTransfer transferObj = new FileTransfer(this.sock, attributes.port, attributes.fileName, attributes.fileSize ); // Probeer het bestand op te slaan message = transferObj.saveFile(); // TODO send message to socket output! try { dataOutput.writeBytes( message); } catch( IOException e ) { // Log de error message ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "Cound not send text: " + stripNewlines(message) + " IO Error " + e.getMessage() ); } // Log dat de file gestuurd is. ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "File object transferred." ); } // verwijder de file metadata van de queue // DESIGNQUESTION Hoop dat dit de juiste is, Uitvoerig testen? transferQueue.remove(attr); // Sluit alle sockets en streams. closeAll(sock, serverSock); } }
digidagmar/RenderSolution
src/com/renderapi/FileSaveHandler.java
1,768
// Log dat de file gestuurd is.
line_comment
nl
package com.renderapi; import java.io.*; import java.net.*; import org.json.simple.*; import org.json.simple.parser.*; import java.nio.charset.StandardCharsets; import java.util.ArrayList; class FileSaveHandler extends Thread { // Deze Streams en Socket zijn voor de file interactie op een bepaalde port. DataInputStream dataInput; DataOutputStream dataOutput; Socket sock; // de message RenderAPI.NetworkMessageType.UPLOADFILE sla ik op in clientText // deze is static en wordt door RenderCommands.doCmdSendFile() gecontroleerd. // de execution thread wacht dus netjes of deze thread haar taak gedaan heeft. static String clientText = ""; // de Server Socket // kiest zelf een vrije poort ServerSocket serverSock; // hou de actieve (dus geopende) TCP poort bij. int activePort = -1; // het JSON commando geeft filename en size. // RenderCommands.doCmdSendFile() (Die deze thread start) // stuurt deze naar de constructor. long size = 0; String project; String file; // Volgens mij is dit niet echt hard nodig // En bevindt zich er vrijwel altijd een transfer in de queue // DESIGNQUESTION uitvoerig testen van deze functionaliteit? ArrayList<TransferAttributes> transferQueue; public FileSaveHandler( long size, String projNumStr, String fileName ) { // De transfer queue this.transferQueue = new ArrayList<TransferAttributes>(); // File metadata this.size = size; this.project = projNumStr; this.file = fileName; } public int getActivePort() { // Wordt niet gebruikt return this.activePort; } public static String getClientText() { // RenderCommands.doCmdSendFile() wacht netjes of de thread een wait message heeft gestuurd. // DESIGNQUESTION Als de wait message niet gestruurd wordt, gaat dat ten koste van de latency. Testen? return FileSaveHandler.clientText; } public static void clearClientText() { // Deze is nodig om ervoor te zorgen dat er bij het eerste upload commando, get poortnummer vernieuwt. FileSaveHandler.clientText = ""; } public static String stripNewlines( String str ) { // uiteindelijk heb ik de JSON errors en messages op een regel gezet. str = str.replace("\n", "").replace("\r", ""); return str; } public void closeAll(Socket sock, ServerSocket serverSock) { // Sluit Streams en Socket try { this.dataInput.close(); this.dataOutput.close(); sock.close(); serverSock.close(); } catch (IOException ex ) { ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "Could not close: " + ex.getMessage() ); } } @Override public void run() { // Voor de file upload wait message String msg; try { // genereer een vrije TCP poort this.serverSock = new ServerSocket( 0 ); this.activePort = serverSock.getLocalPort(); } catch ( IOException ex ) { // TODO stuur de error naar de Client in plaats van de wait message? ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "Could not bind socket. File upload canceled"); return; } // Schrijf naar de server log dat de TCP connectie er is ServerLog.attachMessage( RenderAPI.MessageType.NOTICE, "FileHandler Thread created. filesize: " + this.size + " port: " + this.activePort ); // Emit de file wait boodschap msg = MessageHandler.prepareMessage( RenderAPI.NetworkMessageType.UPLOADFILE, project, size, file, this.serverSock.getLocalPort() ); // RenderCommands.doCmdSendFile() leest welke wait er is. FileSaveHandler.clientText = msg ; // Voeg de transfer toe aan de queue TransferAttributes attr; attr = new TransferAttributes(this.serverSock, this.activePort, this.file, this.size ); transferQueue.add(attr); // Debug the transfer queue for(TransferAttributes attributes: transferQueue ) { ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "Transfer queue index: " + transferQueue.indexOf(attributes) + " port: " + attributes.port + " file name: \"" + attributes.fileName + "\" file size: " + attributes.fileSize ); } // Lus door de transferqueue // DESIGNQUESTION uitgebreid debuggen? for(TransferAttributes attributes: transferQueue ) { String message = ""; try { // De Thread wacht hier op een socket connectie, dit kan eventueel duren. // DESIGNQUESTION timeout installeren? this.sock = attributes.sock.accept(); this.dataInput = new DataInputStream(this.sock.getInputStream()); this.dataOutput = new DataOutputStream(this.sock.getOutputStream()); } catch ( IOException ex ) { // TODO stuur de error naar de Client in plaats van de wait message? ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "IO Error: " + ex.getMessage() ); return; } // FileTransfer opent het bestand, en leest van de Socket sock. FileTransfer transferObj = new FileTransfer(this.sock, attributes.port, attributes.fileName, attributes.fileSize ); // Probeer het bestand op te slaan message = transferObj.saveFile(); // TODO send message to socket output! try { dataOutput.writeBytes( message); } catch( IOException e ) { // Log de error message ServerLog.attachMessage( RenderAPI.MessageType.ERROR, "Cound not send text: " + stripNewlines(message) + " IO Error " + e.getMessage() ); } // Log dat<SUF> ServerLog.attachMessage( RenderAPI.MessageType.DEBUG, "File object transferred." ); } // verwijder de file metadata van de queue // DESIGNQUESTION Hoop dat dit de juiste is, Uitvoerig testen? transferQueue.remove(attr); // Sluit alle sockets en streams. closeAll(sock, serverSock); } }
True
1,433
10
1,639
11
1,582
10
1,640
11
1,914
10
false
false
false
false
false
true
3,327
190035_2
/** * AccessODF - Accessibility checker for OpenOffice.org and LibreOffice Writer. * * Copyright (c) 2011 by DocArch <http://www.docarch.be>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package be.docarch.accessodf.ooo; import java.util.Locale; import java.util.ResourceBundle; import java.util.MissingResourceException; import be.docarch.accessodf.Check; /** * * @author Bert Frees */ public class GeneralCheck extends Check { private static final String L10N_BUNDLE = "be/docarch/accessodf/ooo/l10n/checks"; public static enum ID { E_ManyTitles, E_EmptyTitle, E_EmptyHeading, E_HeadingSkip, E_HeadingInFrame, E_NoLanguage, E_NoDefaultLanguage, E_NoHyperlinkLanguage, E_ImageAnchorFloat, A_NoTitle, A_NoHeadings, A_NoSubtitle, A_AlternateLevel, A_FakeUnorderedList, // *** A_FakeOrderedList, // *** A_FakeTable, A_FakeText, A_FakeQuote, // *** paragraaf met marges aan beide kanten A_FakeHeading, A_LinkedImage, A_ImageWithoutAlt, A_FormulaWithoutAlt, A_ObjectWithoutAlt, A_MergedCells, // niet 100% betrouwbaar => nieuwe checker mbv xpath? A_NestedTable, A_NoTableHeading, A_BreakRows, A_BigTable, A_CaptionBelowBigTable, A_UnidentifiedLanguage, A_LowContrast, A_JustifiedText, A_SmallText, A_AllCaps, // voorlopig genegeerd A_LongUnderline, A_LongItalic, A_HasForms, A_NoHyperlinkText, A_FakeLine, A_FlashText } private ID identifier; public GeneralCheck(ID identifier) { this.identifier = identifier; } public String getIdentifier() { return identifier.name(); } public Status getStatus() { if (identifier.name().startsWith("E_")) { return Status.ERROR; } else if (identifier == ID.A_ImageWithoutAlt) { return Status.ERROR; } else if (identifier == ID.A_LowContrast) { return Status.ERROR; } else if (identifier.name().startsWith("A_")) { return Status.ALERT; } else { return null; } } public String getName(Locale locale) { if (identifier == null) { return null; } try { ResourceBundle bundle = ResourceBundle.getBundle(L10N_BUNDLE, locale); return bundle.getString("name_" + identifier.name()); } catch (MissingResourceException e) { return identifier.name(); } } public String getDescription(Locale locale) { if (identifier == null) { return null; } try { ResourceBundle bundle = ResourceBundle.getBundle(L10N_BUNDLE, locale); return bundle.getString("description_" + identifier.name()); } catch (MissingResourceException e) { return ""; } } public String getSuggestion(Locale locale) { if (identifier == null) { return null; } try { ResourceBundle bundle = ResourceBundle.getBundle(L10N_BUNDLE, locale); return bundle.getString("suggestion_" + identifier.name()); } catch (MissingResourceException e) { return ""; } } }
kalinjul/accessodf
accessodf-addon/src/main/java/be/docarch/accessodf/ooo/GeneralCheck.java
1,231
// *** paragraaf met marges aan beide kanten
line_comment
nl
/** * AccessODF - Accessibility checker for OpenOffice.org and LibreOffice Writer. * * Copyright (c) 2011 by DocArch <http://www.docarch.be>. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package be.docarch.accessodf.ooo; import java.util.Locale; import java.util.ResourceBundle; import java.util.MissingResourceException; import be.docarch.accessodf.Check; /** * * @author Bert Frees */ public class GeneralCheck extends Check { private static final String L10N_BUNDLE = "be/docarch/accessodf/ooo/l10n/checks"; public static enum ID { E_ManyTitles, E_EmptyTitle, E_EmptyHeading, E_HeadingSkip, E_HeadingInFrame, E_NoLanguage, E_NoDefaultLanguage, E_NoHyperlinkLanguage, E_ImageAnchorFloat, A_NoTitle, A_NoHeadings, A_NoSubtitle, A_AlternateLevel, A_FakeUnorderedList, // *** A_FakeOrderedList, // *** A_FakeTable, A_FakeText, A_FakeQuote, // *** paragraaf met<SUF> A_FakeHeading, A_LinkedImage, A_ImageWithoutAlt, A_FormulaWithoutAlt, A_ObjectWithoutAlt, A_MergedCells, // niet 100% betrouwbaar => nieuwe checker mbv xpath? A_NestedTable, A_NoTableHeading, A_BreakRows, A_BigTable, A_CaptionBelowBigTable, A_UnidentifiedLanguage, A_LowContrast, A_JustifiedText, A_SmallText, A_AllCaps, // voorlopig genegeerd A_LongUnderline, A_LongItalic, A_HasForms, A_NoHyperlinkText, A_FakeLine, A_FlashText } private ID identifier; public GeneralCheck(ID identifier) { this.identifier = identifier; } public String getIdentifier() { return identifier.name(); } public Status getStatus() { if (identifier.name().startsWith("E_")) { return Status.ERROR; } else if (identifier == ID.A_ImageWithoutAlt) { return Status.ERROR; } else if (identifier == ID.A_LowContrast) { return Status.ERROR; } else if (identifier.name().startsWith("A_")) { return Status.ALERT; } else { return null; } } public String getName(Locale locale) { if (identifier == null) { return null; } try { ResourceBundle bundle = ResourceBundle.getBundle(L10N_BUNDLE, locale); return bundle.getString("name_" + identifier.name()); } catch (MissingResourceException e) { return identifier.name(); } } public String getDescription(Locale locale) { if (identifier == null) { return null; } try { ResourceBundle bundle = ResourceBundle.getBundle(L10N_BUNDLE, locale); return bundle.getString("description_" + identifier.name()); } catch (MissingResourceException e) { return ""; } } public String getSuggestion(Locale locale) { if (identifier == null) { return null; } try { ResourceBundle bundle = ResourceBundle.getBundle(L10N_BUNDLE, locale); return bundle.getString("suggestion_" + identifier.name()); } catch (MissingResourceException e) { return ""; } } }
True
923
13
1,023
15
1,108
13
1,023
15
1,244
14
false
false
false
false
false
true
4,303
113523_2
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.sdklib.repository.descriptors; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.sdklib.AndroidVersion; import com.android.sdklib.internal.repository.packages.License; import com.android.sdklib.repository.FullRevision; import com.android.sdklib.repository.MajorRevision; /** * Implementation detail of {@link IPkgDescExtra} for extra packages. */ public final class PkgDescExtra extends PkgDesc implements IPkgDescExtra { private final String[] mOldPaths; private final String mNameDisplay; PkgDescExtra(@NonNull PkgType type, @Nullable License license, @Nullable String listDisplay, @Nullable String descriptionShort, @Nullable String descriptionUrl, boolean isObsolete, @Nullable FullRevision fullRevision, @Nullable MajorRevision majorRevision, @Nullable AndroidVersion androidVersion, @Nullable String path, @Nullable IdDisplay tag, @Nullable IdDisplay vendor, @Nullable FullRevision minToolsRev, @Nullable FullRevision minPlatformToolsRev, @NonNull String nameDisplay, @Nullable final String[] oldPaths) { super(type, license, listDisplay, descriptionShort, descriptionUrl, isObsolete, fullRevision, majorRevision, androidVersion, path, tag, vendor, minToolsRev, minPlatformToolsRev, null, //customIsUpdateFor null); //customPath mNameDisplay = nameDisplay; mOldPaths = oldPaths != null ? oldPaths : new String[0]; } @NonNull @Override public String[] getOldPaths() { return mOldPaths; } @NonNull @Override public String getNameDisplay() { return mNameDisplay; } // ---- Helpers ---- /** * Helper method that converts the old_paths property string into the * an old paths array. * * @param oldPathsProperty A possibly-null old_path property string. * @return A list of old paths split by their separator. Can be empty but not null. */ @NonNull public static String[] convertOldPaths(@Nullable String oldPathsProperty) { if (oldPathsProperty == null || oldPathsProperty.length() == 0) { return new String[0]; } return oldPathsProperty.split(";"); //$NON-NLS-1$ } /** * Helper to computhe whether the extra path of both {@link IPkgDescExtra}s * are compatible with each other, which means they are either equal or are * matched between existing path and the potential old paths list. * <p/> * This also covers backward compatibility -- in earlier schemas the vendor id was * merged into the path string when reloading installed extras. * * @param lhs A non-null {@link IPkgDescExtra}. * @param rhs Another non-null {@link IPkgDescExtra}. * @return true if the paths are compatible. */ public static boolean compatibleVendorAndPath( @NonNull IPkgDescExtra lhs, @NonNull IPkgDescExtra rhs) { String[] epOldPaths = rhs.getOldPaths(); int lenEpOldPaths = epOldPaths.length; for (int indexEp = -1; indexEp < lenEpOldPaths; indexEp++) { if (sameVendorAndPath( lhs.getVendor().getId(), lhs.getPath(), rhs.getVendor().getId(), indexEp < 0 ? rhs.getPath() : epOldPaths[indexEp])) { return true; } } String[] thisOldPaths = lhs.getOldPaths(); int lenThisOldPaths = thisOldPaths.length; for (int indexThis = -1; indexThis < lenThisOldPaths; indexThis++) { if (sameVendorAndPath( lhs.getVendor().getId(), indexThis < 0 ? lhs.getPath() : thisOldPaths[indexThis], rhs.getVendor().getId(), rhs.getPath())) { return true; } } return false; } private static boolean sameVendorAndPath( @Nullable String thisVendor, @Nullable String thisPath, @Nullable String otherVendor, @Nullable String otherPath) { // To be backward compatible, we need to support the old vendor-path form // in either the current or the remote package. // // The vendor test below needs to account for an old installed package // (e.g. with an install path of vendor-name) that has then been updated // in-place and thus when reloaded contains the vendor name in both the // path and the vendor attributes. if (otherPath != null && thisPath != null && thisVendor != null) { if (otherPath.equals(thisVendor + '-' + thisPath) && (otherVendor == null || otherVendor.length() == 0 || otherVendor.equals(thisVendor))) { return true; } } if (thisPath != null && otherPath != null && otherVendor != null) { if (thisPath.equals(otherVendor + '-' + otherPath) && (thisVendor == null || thisVendor.length() == 0 || thisVendor.equals(otherVendor))) { return true; } } if (thisPath != null && thisPath.equals(otherPath)) { if ((thisVendor == null && otherVendor == null) || (thisVendor != null && thisVendor.equals(otherVendor))) { return true; } } return false; } }
shenghuntianlang/java-n-IDE-for-Android
javacompiler/src/main/java/com/android/sdklib/repository/descriptors/PkgDescExtra.java
1,742
// ---- Helpers ----
line_comment
nl
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.sdklib.repository.descriptors; import com.android.annotations.NonNull; import com.android.annotations.Nullable; import com.android.sdklib.AndroidVersion; import com.android.sdklib.internal.repository.packages.License; import com.android.sdklib.repository.FullRevision; import com.android.sdklib.repository.MajorRevision; /** * Implementation detail of {@link IPkgDescExtra} for extra packages. */ public final class PkgDescExtra extends PkgDesc implements IPkgDescExtra { private final String[] mOldPaths; private final String mNameDisplay; PkgDescExtra(@NonNull PkgType type, @Nullable License license, @Nullable String listDisplay, @Nullable String descriptionShort, @Nullable String descriptionUrl, boolean isObsolete, @Nullable FullRevision fullRevision, @Nullable MajorRevision majorRevision, @Nullable AndroidVersion androidVersion, @Nullable String path, @Nullable IdDisplay tag, @Nullable IdDisplay vendor, @Nullable FullRevision minToolsRev, @Nullable FullRevision minPlatformToolsRev, @NonNull String nameDisplay, @Nullable final String[] oldPaths) { super(type, license, listDisplay, descriptionShort, descriptionUrl, isObsolete, fullRevision, majorRevision, androidVersion, path, tag, vendor, minToolsRev, minPlatformToolsRev, null, //customIsUpdateFor null); //customPath mNameDisplay = nameDisplay; mOldPaths = oldPaths != null ? oldPaths : new String[0]; } @NonNull @Override public String[] getOldPaths() { return mOldPaths; } @NonNull @Override public String getNameDisplay() { return mNameDisplay; } // ---- Helpers<SUF> /** * Helper method that converts the old_paths property string into the * an old paths array. * * @param oldPathsProperty A possibly-null old_path property string. * @return A list of old paths split by their separator. Can be empty but not null. */ @NonNull public static String[] convertOldPaths(@Nullable String oldPathsProperty) { if (oldPathsProperty == null || oldPathsProperty.length() == 0) { return new String[0]; } return oldPathsProperty.split(";"); //$NON-NLS-1$ } /** * Helper to computhe whether the extra path of both {@link IPkgDescExtra}s * are compatible with each other, which means they are either equal or are * matched between existing path and the potential old paths list. * <p/> * This also covers backward compatibility -- in earlier schemas the vendor id was * merged into the path string when reloading installed extras. * * @param lhs A non-null {@link IPkgDescExtra}. * @param rhs Another non-null {@link IPkgDescExtra}. * @return true if the paths are compatible. */ public static boolean compatibleVendorAndPath( @NonNull IPkgDescExtra lhs, @NonNull IPkgDescExtra rhs) { String[] epOldPaths = rhs.getOldPaths(); int lenEpOldPaths = epOldPaths.length; for (int indexEp = -1; indexEp < lenEpOldPaths; indexEp++) { if (sameVendorAndPath( lhs.getVendor().getId(), lhs.getPath(), rhs.getVendor().getId(), indexEp < 0 ? rhs.getPath() : epOldPaths[indexEp])) { return true; } } String[] thisOldPaths = lhs.getOldPaths(); int lenThisOldPaths = thisOldPaths.length; for (int indexThis = -1; indexThis < lenThisOldPaths; indexThis++) { if (sameVendorAndPath( lhs.getVendor().getId(), indexThis < 0 ? lhs.getPath() : thisOldPaths[indexThis], rhs.getVendor().getId(), rhs.getPath())) { return true; } } return false; } private static boolean sameVendorAndPath( @Nullable String thisVendor, @Nullable String thisPath, @Nullable String otherVendor, @Nullable String otherPath) { // To be backward compatible, we need to support the old vendor-path form // in either the current or the remote package. // // The vendor test below needs to account for an old installed package // (e.g. with an install path of vendor-name) that has then been updated // in-place and thus when reloaded contains the vendor name in both the // path and the vendor attributes. if (otherPath != null && thisPath != null && thisVendor != null) { if (otherPath.equals(thisVendor + '-' + thisPath) && (otherVendor == null || otherVendor.length() == 0 || otherVendor.equals(thisVendor))) { return true; } } if (thisPath != null && otherPath != null && otherVendor != null) { if (thisPath.equals(otherVendor + '-' + otherPath) && (thisVendor == null || thisVendor.length() == 0 || thisVendor.equals(otherVendor))) { return true; } } if (thisPath != null && thisPath.equals(otherPath)) { if ((thisVendor == null && otherVendor == null) || (thisVendor != null && thisVendor.equals(otherVendor))) { return true; } } return false; } }
False
1,327
4
1,410
4
1,533
4
1,410
4
1,729
5
false
false
false
false
false
true
2,731
8382_2
/* * Copyright (C) 2013 FrankkieNL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.frankkie.bronylivewallpaper; import android.app.Dialog; import android.content.Context; import android.content.pm.ApplicationInfo; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import org.apache.http.NameValuePair; /** * CUSTOM LOGGER * * Deze class zo gemaakt, * dat hij zoveel mogelijk lijkt op het bestaande Log-systeem, * en dat hij op dezelfde manier kan worden aangeroepen. * Als je alle logs via deze class laat lopen, * kan je makkelijk logging in en uit schakelen. * Ook exceptions kan je hiermee printen mbv de writer. * Voor later is het ook handig, (aanpasbaarheid) * als voortaan de logs naar een file moeten of zo, * hoef je niet alle logs in de app aan te passen, * maar alleen deze class. * * Voorbeeld: * normaal: * Log.v("tag", "bericht"); * voortaan: * CLog.v("bericht"); * @author Frankkie */ public class CLog extends OutputStream { private ByteArrayOutputStream bos = new ByteArrayOutputStream(); public static String TAG = "CLog"; /** * Minimum errorlevel om te worden gelogd. * Waardes komen van android.util.Log.*; */ public static int errorLevel = Log.VERBOSE; public static boolean shouldLog = true; /** * door deze printwriter kan je meteen zo doen: * exception.printStackTrace(CLog.writer); */ public static PrintWriter writer = new PrintWriter(new CLog()); public CLog(Context c) { setShouldLogByDebuggable(c); } public CLog(Context c, String tag) { setShouldLogByDebuggable(c); setTag(tag); } public static boolean checkDebuggable(Context c) { return (0 != (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)); } public static void setShouldLog(boolean bool){ shouldLog = bool; } public static void setShouldLogByDebuggable(Context c) { shouldLog = checkDebuggable(c); } public CLog() { // le nothin' } public CLog(String tag) { setTag(tag); } @Override public void write(int b) throws IOException { if (b == (int) '\n') { String s = new String(this.bos.toByteArray()); CLog.v(TAG, s); this.bos = new ByteArrayOutputStream(); } else { this.bos.write(b); } } public static void setTag(String s) { TAG = s; } public static String getTag() { return TAG; } /** * print exceptions * @param e */ public static void ex(Exception e) { if (shouldLog) { e.printStackTrace(); } } /** * print exceptions * @param e */ public static void exOLD(Exception e) { if (shouldLog) { e.printStackTrace(writer); } } public static void e(String tag, String msg) { if (shouldLog && errorLevel <= Log.ERROR) { Log.e(tag, msg); } } public static void d(String tag, String msg) { if (shouldLog && errorLevel <= Log.DEBUG) { Log.d(tag, msg); } } public static void i(String tag, String msg) { if (shouldLog && errorLevel <= Log.INFO) { Log.i(tag, msg); } } public static void v(String tag, String msg) { if (shouldLog && errorLevel <= Log.VERBOSE) { Log.v(tag, msg); } } public static void w(String tag, String msg) { if (shouldLog && errorLevel <= Log.WARN) { Log.w(tag, msg); } } public static void e(Object msg) { e(TAG, msg.toString()); } public static void d(Object msg) { d(TAG, msg.toString()); } public static void i(Object msg) { i(TAG, msg.toString()); } public static void v(Object msg) { v(TAG, msg.toString()); } public static void w(Object msg) { w(TAG, msg.toString()); } /** * Print all parameter of List<NameValuePair> * @param pairs the pairs to be printed */ public static void printNameValuePairs(List<NameValuePair> pairs) { if (!shouldLog) { return; } Iterator i = pairs.iterator(); while (i.hasNext()) { NameValuePair p = (NameValuePair) i.next(); v(p.getName() + ":" + p.getValue()); } } /** * Het sluiten van een dialog geeft veel te * vaak een exception, waar we toch niets mee doen. * @param d */ public static void dismissDialog(Dialog d) { try { d.dismiss(); } catch (Exception e) { //./ignore } } }
frankkienl/BronyLiveWallpaper
BronyLiveWallpaper/src/main/java/nl/frankkie/bronylivewallpaper/CLog.java
1,592
/** * Minimum errorlevel om te worden gelogd. * Waardes komen van android.util.Log.*; */
block_comment
nl
/* * Copyright (C) 2013 FrankkieNL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package nl.frankkie.bronylivewallpaper; import android.app.Dialog; import android.content.Context; import android.content.pm.ApplicationInfo; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.util.List; import org.apache.http.NameValuePair; /** * CUSTOM LOGGER * * Deze class zo gemaakt, * dat hij zoveel mogelijk lijkt op het bestaande Log-systeem, * en dat hij op dezelfde manier kan worden aangeroepen. * Als je alle logs via deze class laat lopen, * kan je makkelijk logging in en uit schakelen. * Ook exceptions kan je hiermee printen mbv de writer. * Voor later is het ook handig, (aanpasbaarheid) * als voortaan de logs naar een file moeten of zo, * hoef je niet alle logs in de app aan te passen, * maar alleen deze class. * * Voorbeeld: * normaal: * Log.v("tag", "bericht"); * voortaan: * CLog.v("bericht"); * @author Frankkie */ public class CLog extends OutputStream { private ByteArrayOutputStream bos = new ByteArrayOutputStream(); public static String TAG = "CLog"; /** * Minimum errorlevel om<SUF>*/ public static int errorLevel = Log.VERBOSE; public static boolean shouldLog = true; /** * door deze printwriter kan je meteen zo doen: * exception.printStackTrace(CLog.writer); */ public static PrintWriter writer = new PrintWriter(new CLog()); public CLog(Context c) { setShouldLogByDebuggable(c); } public CLog(Context c, String tag) { setShouldLogByDebuggable(c); setTag(tag); } public static boolean checkDebuggable(Context c) { return (0 != (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)); } public static void setShouldLog(boolean bool){ shouldLog = bool; } public static void setShouldLogByDebuggable(Context c) { shouldLog = checkDebuggable(c); } public CLog() { // le nothin' } public CLog(String tag) { setTag(tag); } @Override public void write(int b) throws IOException { if (b == (int) '\n') { String s = new String(this.bos.toByteArray()); CLog.v(TAG, s); this.bos = new ByteArrayOutputStream(); } else { this.bos.write(b); } } public static void setTag(String s) { TAG = s; } public static String getTag() { return TAG; } /** * print exceptions * @param e */ public static void ex(Exception e) { if (shouldLog) { e.printStackTrace(); } } /** * print exceptions * @param e */ public static void exOLD(Exception e) { if (shouldLog) { e.printStackTrace(writer); } } public static void e(String tag, String msg) { if (shouldLog && errorLevel <= Log.ERROR) { Log.e(tag, msg); } } public static void d(String tag, String msg) { if (shouldLog && errorLevel <= Log.DEBUG) { Log.d(tag, msg); } } public static void i(String tag, String msg) { if (shouldLog && errorLevel <= Log.INFO) { Log.i(tag, msg); } } public static void v(String tag, String msg) { if (shouldLog && errorLevel <= Log.VERBOSE) { Log.v(tag, msg); } } public static void w(String tag, String msg) { if (shouldLog && errorLevel <= Log.WARN) { Log.w(tag, msg); } } public static void e(Object msg) { e(TAG, msg.toString()); } public static void d(Object msg) { d(TAG, msg.toString()); } public static void i(Object msg) { i(TAG, msg.toString()); } public static void v(Object msg) { v(TAG, msg.toString()); } public static void w(Object msg) { w(TAG, msg.toString()); } /** * Print all parameter of List<NameValuePair> * @param pairs the pairs to be printed */ public static void printNameValuePairs(List<NameValuePair> pairs) { if (!shouldLog) { return; } Iterator i = pairs.iterator(); while (i.hasNext()) { NameValuePair p = (NameValuePair) i.next(); v(p.getName() + ":" + p.getValue()); } } /** * Het sluiten van een dialog geeft veel te * vaak een exception, waar we toch niets mee doen. * @param d */ public static void dismissDialog(Dialog d) { try { d.dismiss(); } catch (Exception e) { //./ignore } } }
True
1,267
26
1,434
29
1,513
30
1,434
29
1,644
33
false
false
false
false
false
true