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
4,698
69092_4
import data.AdresDAOHibernate; import data.OVChipkaartDAOHibernate; import data.ProductDAOHibernate; import data.ReizigerDAOHibernate; import data.interfaces.AdresDAO; import data.interfaces.OVChipkaartDAO; import data.interfaces.ProductDAO; import data.interfaces.ReizigerDAO; import domain.Adres; import domain.OVChipkaart; import domain.Product; import domain.Reiziger; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.Metamodel; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import java.sql.Date; import java.sql.SQLException; import java.util.List; /** * Testklasse - deze klasse test alle andere klassen in deze package. * * System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions). * * @author tijmen.muller@hu.nl */ public class Main { // Creëer een factory voor Hibernate sessions. private static final SessionFactory factory; static { try { // Create a Hibernate session factory factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } /** * Retouneer een Hibernate session. * * @return Hibernate session * @throws HibernateException */ private static Session getSession() throws HibernateException { return factory.openSession(); } public static void main(String[] args) throws SQLException { //testFetchAll(); testDAO(); } /** * P6. Haal alle (geannoteerde) entiteiten uit de database. */ private static void testFetchAll() { Session session = getSession(); try { Metamodel metamodel = session.getSessionFactory().getMetamodel(); for (EntityType<?> entityType : metamodel.getEntities()) { Query query = session.createQuery("from " + entityType.getName()); System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:"); for (Object o : query.list()) { System.out.println(" " + o); } System.out.println(); } } finally { session.close(); } } private static void testDAO() { Session session = getSession(); Transaction transaction = session.getTransaction(); try { // make DAO OVChipkaartDAO ovChipkaartDAO = new OVChipkaartDAOHibernate(session); AdresDAO adresDAO = new AdresDAOHibernate(session); ReizigerDAO reizigerDAO = new ReizigerDAOHibernate(session); ProductDAO productDAO = new ProductDAOHibernate(session); // test DAO testReizigerDAO(reizigerDAO); testAdresDAO(adresDAO, reizigerDAO); testOVChipDAO(ovChipkaartDAO, reizigerDAO); testProductDAO(productDAO, reizigerDAO); } catch (Exception e){ e.printStackTrace(); System.out.println("ROLLBACK!!!"); transaction.rollback(); } finally { session.close(); } } private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testReizigerDAO----------"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17")); List<Reiziger> reizigers= rdao.findAll(); System.out.println("findAll gives:"); for (Reiziger r : reizigers) { System.out.println(r); } System.out.println("\nfindByGbdatum gives:"); for (Reiziger r : rdao.findByGbdatum("2002-12-03")) { System.out.println(r); } // test save System.out.println("\nsave before: " + reizigers.size()); rdao.save(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); System.out.println("\nupdate before: " + rdao.findById(100)); reiziger.setVoorletters("jag"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + reizigers.size()); rdao.delete(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); } private static void testAdresDAO(AdresDAO adao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testAdresDAO----------"); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); List<Adres> adresList = adao.findAll(); System.out.println("\nfindAll gives:"); for (Adres a : adresList) { System.out.println(a); } // test save System.out.println("\nsave before: " + adresList.size()); rdao.save(reiziger); adresList = adao.findAll(); System.out.println("after: " + adresList.size()); System.out.println("\nfindById gives: " + adao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + adao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); adres.setHuisnummer("3B"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + adresList.size()); rdao.delete(reiziger); adresList = adao.findAll(); System.out.println("delete after: " + adresList.size()); } private static void testOVChipDAO(OVChipkaartDAO odao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testOVChipkaartDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); reiziger.addOVChipkaart(ovChipkaart); List<OVChipkaart> kaartList = odao.findAll(); System.out.println("\nfindAll gives:"); for (OVChipkaart o : kaartList) { System.out.println(o); } // test save System.out.println("\nsave before: " + kaartList.size()); rdao.save(reiziger); kaartList = odao.findAll(); System.out.println("after: " + kaartList.size()); System.out.println("\nfindById gives: " + odao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + odao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); ovChipkaart.setSaldo(69); reiziger.addOVChipkaart(ovChipkaart2); ovChipkaart2.setReiziger(reiziger); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + kaartList.size()); rdao.delete(reiziger); kaartList = odao.findAll(); System.out.println("delete after: " + kaartList.size()); } private static void testProductDAO(ProductDAO pdao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testProductDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); Product product = new Product(100,"test","test",100); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); ovChipkaart2.setReiziger(reiziger); product.addOvChip(ovChipkaart); rdao.save(reiziger); List<Product> productList = pdao.findAll(); System.out.println("\nfindAll gives:"); for (Product p : productList) { System.out.println(p); } // test save System.out.println("\nsave before: " + productList.size()); pdao.save(product); productList = pdao.findAll(); System.out.println("after: " + productList.size()); System.out.println("\nfindById gives: " + pdao.findById(product.getProductNummer())); System.out.println("\nfindByOVChipkaart gives: " + pdao.findByOvChipkaart(ovChipkaart)); // test update System.out.println("\nupdate before: " + pdao.findById(product.getProductNummer())); product.addOvChip(ovChipkaart2); product.setBeschrijving("tset"); pdao.update(product); System.out.println("update after: " + pdao.findById(product.getProductNummer())); // test delete System.out.println("\ndelete before: " + productList.size()); pdao.delete(product); productList = pdao.findAll(); System.out.println("delete after: " + productList.size()); rdao.delete(reiziger); } }
wiemanboy/DataPersistency-Hibernate
src/main/java/Main.java
3,208
/** * P6. Haal alle (geannoteerde) entiteiten uit de database. */
block_comment
nl
import data.AdresDAOHibernate; import data.OVChipkaartDAOHibernate; import data.ProductDAOHibernate; import data.ReizigerDAOHibernate; import data.interfaces.AdresDAO; import data.interfaces.OVChipkaartDAO; import data.interfaces.ProductDAO; import data.interfaces.ReizigerDAO; import domain.Adres; import domain.OVChipkaart; import domain.Product; import domain.Reiziger; import jakarta.persistence.metamodel.EntityType; import jakarta.persistence.metamodel.Metamodel; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.query.Query; import java.sql.Date; import java.sql.SQLException; import java.util.List; /** * Testklasse - deze klasse test alle andere klassen in deze package. * * System.out.println() is alleen in deze klasse toegestaan (behalve voor exceptions). * * @author tijmen.muller@hu.nl */ public class Main { // Creëer een factory voor Hibernate sessions. private static final SessionFactory factory; static { try { // Create a Hibernate session factory factory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { throw new ExceptionInInitializerError(ex); } } /** * Retouneer een Hibernate session. * * @return Hibernate session * @throws HibernateException */ private static Session getSession() throws HibernateException { return factory.openSession(); } public static void main(String[] args) throws SQLException { //testFetchAll(); testDAO(); } /** * P6. Haal alle<SUF>*/ private static void testFetchAll() { Session session = getSession(); try { Metamodel metamodel = session.getSessionFactory().getMetamodel(); for (EntityType<?> entityType : metamodel.getEntities()) { Query query = session.createQuery("from " + entityType.getName()); System.out.println("[Test] Alle objecten van type " + entityType.getName() + " uit database:"); for (Object o : query.list()) { System.out.println(" " + o); } System.out.println(); } } finally { session.close(); } } private static void testDAO() { Session session = getSession(); Transaction transaction = session.getTransaction(); try { // make DAO OVChipkaartDAO ovChipkaartDAO = new OVChipkaartDAOHibernate(session); AdresDAO adresDAO = new AdresDAOHibernate(session); ReizigerDAO reizigerDAO = new ReizigerDAOHibernate(session); ProductDAO productDAO = new ProductDAOHibernate(session); // test DAO testReizigerDAO(reizigerDAO); testAdresDAO(adresDAO, reizigerDAO); testOVChipDAO(ovChipkaartDAO, reizigerDAO); testProductDAO(productDAO, reizigerDAO); } catch (Exception e){ e.printStackTrace(); System.out.println("ROLLBACK!!!"); transaction.rollback(); } finally { session.close(); } } private static void testReizigerDAO(ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testReizigerDAO----------"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17")); List<Reiziger> reizigers= rdao.findAll(); System.out.println("findAll gives:"); for (Reiziger r : reizigers) { System.out.println(r); } System.out.println("\nfindByGbdatum gives:"); for (Reiziger r : rdao.findByGbdatum("2002-12-03")) { System.out.println(r); } // test save System.out.println("\nsave before: " + reizigers.size()); rdao.save(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); System.out.println("\nupdate before: " + rdao.findById(100)); reiziger.setVoorletters("jag"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + reizigers.size()); rdao.delete(reiziger); reizigers = rdao.findAll(); System.out.println("after: " + reizigers.size()); } private static void testAdresDAO(AdresDAO adao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testAdresDAO----------"); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100,"j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); List<Adres> adresList = adao.findAll(); System.out.println("\nfindAll gives:"); for (Adres a : adresList) { System.out.println(a); } // test save System.out.println("\nsave before: " + adresList.size()); rdao.save(reiziger); adresList = adao.findAll(); System.out.println("after: " + adresList.size()); System.out.println("\nfindById gives: " + adao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + adao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); adres.setHuisnummer("3B"); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + adresList.size()); rdao.delete(reiziger); adresList = adao.findAll(); System.out.println("delete after: " + adresList.size()); } private static void testOVChipDAO(OVChipkaartDAO odao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testOVChipkaartDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); reiziger.addOVChipkaart(ovChipkaart); List<OVChipkaart> kaartList = odao.findAll(); System.out.println("\nfindAll gives:"); for (OVChipkaart o : kaartList) { System.out.println(o); } // test save System.out.println("\nsave before: " + kaartList.size()); rdao.save(reiziger); kaartList = odao.findAll(); System.out.println("after: " + kaartList.size()); System.out.println("\nfindById gives: " + odao.findById(reiziger.getId())); System.out.println("\nfindByReiziger gives: " + odao.findByReiziger(reiziger)); // test update System.out.println("\nupdate before: " + rdao.findById(100)); ovChipkaart.setSaldo(69); reiziger.addOVChipkaart(ovChipkaart2); ovChipkaart2.setReiziger(reiziger); rdao.update(reiziger); System.out.println("update after: " + rdao.findById(100)); // test delete System.out.println("\ndelete before: " + kaartList.size()); rdao.delete(reiziger); kaartList = odao.findAll(); System.out.println("delete after: " + kaartList.size()); } private static void testProductDAO(ProductDAO pdao, ReizigerDAO rdao) throws SQLException { System.out.println("\n----------testProductDAO----------"); OVChipkaart ovChipkaart = new OVChipkaart(100, Date.valueOf("2004-04-17"), 1, 100); OVChipkaart ovChipkaart2 = new OVChipkaart(101, Date.valueOf("2004-04-17"), 1, 100); Adres adres = new Adres(100, "1234LK", "3A", "brugweg", "utrecht"); Reiziger reiziger = new Reiziger(100, "j", null, "wieman", Date.valueOf("2004-04-17"), adres); Product product = new Product(100,"test","test",100); adres.setReiziger(reiziger); ovChipkaart.setReiziger(reiziger); ovChipkaart2.setReiziger(reiziger); product.addOvChip(ovChipkaart); rdao.save(reiziger); List<Product> productList = pdao.findAll(); System.out.println("\nfindAll gives:"); for (Product p : productList) { System.out.println(p); } // test save System.out.println("\nsave before: " + productList.size()); pdao.save(product); productList = pdao.findAll(); System.out.println("after: " + productList.size()); System.out.println("\nfindById gives: " + pdao.findById(product.getProductNummer())); System.out.println("\nfindByOVChipkaart gives: " + pdao.findByOvChipkaart(ovChipkaart)); // test update System.out.println("\nupdate before: " + pdao.findById(product.getProductNummer())); product.addOvChip(ovChipkaart2); product.setBeschrijving("tset"); pdao.update(product); System.out.println("update after: " + pdao.findById(product.getProductNummer())); // test delete System.out.println("\ndelete before: " + productList.size()); pdao.delete(product); productList = pdao.findAll(); System.out.println("delete after: " + productList.size()); rdao.delete(reiziger); } }
True
2,433
24
2,765
24
2,799
26
2,765
24
3,265
26
false
false
false
false
false
true
4,062
28143_2
package com.rhcloud.github_pspletinckx.kunstplus; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; public class HomeScreenFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; private String QRresource; private ListView advList; private ContentFragmentCallbacks mCallback; String[] titles = { "In My Head-Carll Cneut \n"+ "ma-vr, 16u - 20u - | Afstand: 1Km", "Joris Ghekiere - S.M.A.K. \n"+ "Vandaag, 16u - 20u | Afstand: 200m ", "Christian Falsnaes - Kiosk\n" + "", "Joris Ghekiere - S.M.A.K. \n"+ "Vandaag, 16u - 20u | Afstand: 200m ", "Jef Geys - S.M.A.K.", "Larry Sultan - S.M.A.K.", "Tabula Rasa - Museum Dr. Guislain" } ; Integer[] imageId = { R.drawable.carllcneut480, R.drawable.jorisghekiere480, R.drawable.christian_falsnaes_thumbnail_eartnow, R.drawable.img_ghekiere_12, R.drawable.img_jefgeys_affiche_datum, R.drawable.img_larry_sultan_serie_pictures_from_home_empty_pool_1991, R.drawable.ronny_delrue_lost_memory_2006_fotoprint }; String[] urls = { "http://sintpietersabdij.stad.gent/nl/content/carll-cneut-my-head#content",//content to skip header "http://www.smak.be/tentoonstelling.php?la=nl&y=&tid=&t=&id=627", //non responive web "One", "http://www.smak.be/tentoonstelling.php?la=nl&y=&tid=&t=&id=627", "Three", "Four", "Five" }; public HomeScreenFragment() { } public static HomeScreenFragment newInstance(int sectionNumber) { //factory?? HomeScreenFragment fragment = new HomeScreenFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_homescreen, container, false); AdvListAdaptor adaptor = new AdvListAdaptor(getActivity(), titles,imageId); advList = (ListView)rootView.findViewById(R.id.advList); advList.setAdapter(adaptor); advList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d("Clicked",""+id); //mCallback.openContentWindow(urls[(int)id]); //Heb ik nog niet kunnen doen werken, ga ik vervangen door intent displayUrl(urls[(int)id]); } }); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((AppMainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } private void voorbeeldqrview(){ //QRresource = "http://github-pspletinckx.rhcloud.com"; QRresource = "http://github-pspletinckx.rhcloud.com/kunstPlus/QR/123456789ABCDEF/"; Intent intent = new Intent(getActivity(),QRObjectActivity.class); intent.putExtra("LoadResource",QRresource); startActivity(intent); } private void displayUrl(String url){ if(url!=null) { Intent intent = new Intent(getActivity(), QRObjectActivity.class); intent.putExtra("LoadResource", url); startActivity(intent); } } private void toonqrscan(){ Intent intent = new Intent(getActivity(),QRScanActivity.class); startActivity(intent); } public void voorbeeldContentFragment(){ } }
pspletinckx/kunstPlus
app/src/main/java/com/rhcloud/github_pspletinckx/kunstplus/HomeScreenFragment.java
1,337
//mCallback.openContentWindow(urls[(int)id]); //Heb ik nog niet kunnen doen werken, ga ik vervangen door intent
line_comment
nl
package com.rhcloud.github_pspletinckx.kunstplus; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; public class HomeScreenFragment extends Fragment { private static final String ARG_SECTION_NUMBER = "section_number"; private String QRresource; private ListView advList; private ContentFragmentCallbacks mCallback; String[] titles = { "In My Head-Carll Cneut \n"+ "ma-vr, 16u - 20u - | Afstand: 1Km", "Joris Ghekiere - S.M.A.K. \n"+ "Vandaag, 16u - 20u | Afstand: 200m ", "Christian Falsnaes - Kiosk\n" + "", "Joris Ghekiere - S.M.A.K. \n"+ "Vandaag, 16u - 20u | Afstand: 200m ", "Jef Geys - S.M.A.K.", "Larry Sultan - S.M.A.K.", "Tabula Rasa - Museum Dr. Guislain" } ; Integer[] imageId = { R.drawable.carllcneut480, R.drawable.jorisghekiere480, R.drawable.christian_falsnaes_thumbnail_eartnow, R.drawable.img_ghekiere_12, R.drawable.img_jefgeys_affiche_datum, R.drawable.img_larry_sultan_serie_pictures_from_home_empty_pool_1991, R.drawable.ronny_delrue_lost_memory_2006_fotoprint }; String[] urls = { "http://sintpietersabdij.stad.gent/nl/content/carll-cneut-my-head#content",//content to skip header "http://www.smak.be/tentoonstelling.php?la=nl&y=&tid=&t=&id=627", //non responive web "One", "http://www.smak.be/tentoonstelling.php?la=nl&y=&tid=&t=&id=627", "Three", "Four", "Five" }; public HomeScreenFragment() { } public static HomeScreenFragment newInstance(int sectionNumber) { //factory?? HomeScreenFragment fragment = new HomeScreenFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, sectionNumber); fragment.setArguments(args); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_homescreen, container, false); AdvListAdaptor adaptor = new AdvListAdaptor(getActivity(), titles,imageId); advList = (ListView)rootView.findViewById(R.id.advList); advList.setAdapter(adaptor); advList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d("Clicked",""+id); //mCallback.openContentWindow(urls[(int)id]); //Heb<SUF> displayUrl(urls[(int)id]); } }); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); ((AppMainActivity) activity).onSectionAttached( getArguments().getInt(ARG_SECTION_NUMBER)); } private void voorbeeldqrview(){ //QRresource = "http://github-pspletinckx.rhcloud.com"; QRresource = "http://github-pspletinckx.rhcloud.com/kunstPlus/QR/123456789ABCDEF/"; Intent intent = new Intent(getActivity(),QRObjectActivity.class); intent.putExtra("LoadResource",QRresource); startActivity(intent); } private void displayUrl(String url){ if(url!=null) { Intent intent = new Intent(getActivity(), QRObjectActivity.class); intent.putExtra("LoadResource", url); startActivity(intent); } } private void toonqrscan(){ Intent intent = new Intent(getActivity(),QRScanActivity.class); startActivity(intent); } public void voorbeeldContentFragment(){ } }
False
995
29
1,174
36
1,183
28
1,174
36
1,316
33
false
false
false
false
false
true
4,021
58922_2
package elaborate.editor.resources.orm.wrappers; /* * #%L * elab4-backend * ======= * Copyright (C) 2011 - 2015 Huygens ING * ======= * 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/gpl-3.0.html>. * #L% */ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import elaborate.editor.model.orm.Transcription; import elaborate.editor.model.orm.service.ProjectService; import elaborate.editor.model.orm.service.ProjectService.AnnotationData; public class TranscriptionWrapperTest { @Before public void setUp() throws Exception {} @After public void tearDown() throws Exception {} @Test public void testTranscriptionWrapper() throws Exception { String textLayer = "textlayer"; String title = "title"; String body = "<body><ab id=\"9085822\"/>sdgdgdgsdgsdfg<ae id=\"9085822\"/></body>"; Transcription transcription = mockTranscription(textLayer, title, body); Map<Integer, AnnotationData> annotationDataMap = ImmutableMap.of(9085822, new AnnotationData().setType("type")); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, annotationDataMap); // assertThat( tw.title).isEqualTo(title); assertThat(tw.getTextLayer()).isEqualTo(textLayer); String expected = "<span data-marker=\"begin\" data-id=\"9085822\" data-type=\"type\"></span>sdgdgdgsdgsdfg<sup data-marker=\"end\" data-id=\"9085822\">1</sup>"; assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testTranscriptionWrapperWithBadXHtmlInput() throws Exception { String textLayer = "textlayer"; String title = "title"; String body = "<body><span style=\"font-size:11.0pt;line-height:115%; font-family:\"Verdana\",\"sans-serif\";mso-fareast-font-family:Calibri;mso-fareast-theme-font: minor-latin;mso-bidi-font-family:\"Times New Roman\";mso-bidi-theme-font:minor-bidi; mso-ansi-language:NL;mso-fareast-language:EN-US;mso-bidi-language:AR-SA\">Hoezo mag ik niet copy-pasten vanuit Word? Maar ik wil het!</span></body>"; Transcription transcription = mockTranscription(textLayer, title, body); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); // assertThat( tw.title).isEqualTo(title); assertThat(tw.getTextLayer()).isEqualTo(textLayer); String expected = "Hoezo mag ik niet copy-pasten vanuit Word? Maar ik wil het!"; assertThat(tw.getBody()).isEqualTo(expected); } private Transcription mockTranscription(String textLayer, String title, String body) { Transcription transcription = mock(Transcription.class); when(transcription.getTextLayer()).thenReturn(textLayer); when(transcription.getTitle()).thenReturn(title); when(transcription.getBody()).thenReturn(body); return transcription; } @Test public void testConvertBodyWithEmptyTagsForOutput() throws Exception { String in = "<body>bla <i></i> bla <strong></strong> bla</body>"; String expected = "bla bla bla"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertBodyForOutput() throws Exception { String in = "<body>"// + " "// + "<ab id=\"9085822\"/>"// + "bla "// + "<ab id=\"9085821\"/>"// + "die"// + "<ae id=\"9085822\"/>"// + " bla"// + "<ae id=\"9085821\"/>"// + "\nhello world "// + "</body>"; String expected = "<span data-marker=\"begin\" data-id=\"9085822\" data-type=\"type2\"></span>"// + "bla "// + "<span data-marker=\"begin\" data-id=\"9085821\" data-type=\"type1\"></span>"// + "die"// + "<sup data-marker=\"end\" data-id=\"9085822\">1</sup>"// + " bla"// + "<sup data-marker=\"end\" data-id=\"9085821\">2</sup>"// + "<br>hello world"; Transcription transcription = mockTranscription("textLayer", "title", in); Map<Integer, AnnotationData> annotationDataMap = ImmutableMap.<Integer, ProjectService.AnnotationData> builder()// .put(9085821, new AnnotationData().setType("type1"))// .put(9085822, new AnnotationData().setType("type2"))// .build(); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, annotationDataMap); assertThat(tw.getBody()).isEqualTo(expected); List<Integer> annotationNumbers = tw.annotationNumbers; assertThat(annotationNumbers.size()).isEqualTo(2); assertThat(annotationNumbers.get(0)).isEqualTo(Integer.valueOf(9085822)); assertThat(annotationNumbers.get(1)).isEqualTo(Integer.valueOf(9085821)); } @Test public void testConvertBodyForOutput_with_superfluous_newlines_at_the_end() throws Exception { String in = "<body>lorem epsum doleres whatever\n \n\n\n</body>"; String expected = "lorem epsum doleres whatever"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertBodyForOutput_with_superfluous_whitespace_at_the_end() throws Exception { String in = "<body>body\n \n </body>"; String expected = "body"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertBodyForOutput_with_shift_space() throws Exception { String in = "<body>header\n  paragraph 1\n  paragraph 2   \n paragraph 3</body>"; String expected = "header<br>&nbsp;&nbsp;paragraph 1<br>&nbsp;&nbsp;paragraph 2&nbsp;&nbsp;&nbsp;<br> paragraph 3"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertFromInput() throws Exception { String in = "<span data-marker=\"begin\" data-id=\"9085822\">bla die bla</span><sup data-marker=\"end\" data-id=\"9085822\">1</sup><br>hello world"; String expected = "<body><ab id=\"9085822\"/>bla die bla<ae id=\"9085822\"/>\nhello world</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputWithBadChar() throws Exception { String in = "the smiling ones danced like blooming girls, I presumed boldly to rank _x001A_the former"; String expected = "<body>the smiling ones danced like blooming girls, I presumed boldly to rank the former</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputWithBreaks() throws Exception { String in = "hop<br>on<br>pop"; String expected = "<body>hop\non\npop</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputRemovesXMLComments() throws Exception { String in = "bla <!-- ignore comments --> bla"; String expected = "<body>bla bla</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputConvertsEmToI() throws Exception { String in = "<em style=\"white-space: normal;\">Casteleijn</em>"; String expected = "<body><i>Casteleijn</i></body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputConvertsStrongToB() throws Exception { String in = "<strong style=\"white-space: normal;\">TGIF</strong>"; String expected = "<body><b>TGIF</b></body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputRemovesMostWordTags() throws Exception { String in = "<p class=\"MsoNormal\" style=\"margin-right:29.9pt;text-align:justify\">"// + "I <i style=\"mso-bidi-font-style:normal\">HEART</i>"// + " <b style=\"mso-bidi-font-weight:normal\">WORD!!</b>"// + "</p>"; String expected = "<body>I <i>HEART</i> <b>WORD!!</b></body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } // @Test // public void testConvertFromInputRemovesMostWordTags1() throws Exception { // String in = "<br>(zie ook 253r (regel 7) hier staat voluit geschreven onse Raitsvrend<i>en</i> (misschien hier ook Raitsvrend<i>e</i> ?,"// // + "maar vrint zou tot de sterke flextie moeten behoren dus moeten eindigen op -en?))<br>KG:&nbsp; Samen graag nog even hebben over de"// // + " meervoudvorm.<br><br><br>34: oirer -&gt; oiren [?]<br>sendebode: m. acc. pl. (Zwakke flextie?) het zou dan oire moeten worden. Is"// // + " hier misschien de letter 'r' afgekort?<br>KG: als boven. <br><br><p class=\"MsoNormal\">‘raitsvrenden’: volgens Van Loey,"// // + " <i style=\"mso-bidi-font-style: normal\">Mndld Spraakkunst </i>I § 19.2 kan het bij ‘vrient’ (en ‘viant’)<br>allebei -&gt; dan"// // + " beslist de paleografie</p><p class=\"MsoNormal\"><br></p><p class=\"MsoNormal\">260v \"onse vrende\" voluit geschreven<br></p><br>"// // + "<br><br><br><br>-------------------------------------------------------------------------<br>Translation<br>- Wijk ( bij Duurstede)?"// // + "<br><br>"; // String expected = "<body></body>"; // assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); // } @Test public void testSuperscriptIsHandledWell() throws Exception { TranscriptionWrapper tw = new TranscriptionWrapper(); tw.setBody("<sup>super</sup> normaal <sub>sub</sub><br><sup>super</sup> normaal <sub>sub<br></sub><sup>super</sup> normaal <sub>sub</sub><br>"); String expected = "<body><sup>super</sup> normaal <sub>sub</sub>\n<sup>super</sup> normaal <sub>sub\n</sub><sup>super</sup> normaal <sub>sub</sub>\n</body>"; assertThat(tw.getBodyForDb()).isEqualTo(expected); } @Test public void testAnnotationMarkerIsHandledWell() throws Exception { TranscriptionWrapper tw = new TranscriptionWrapper(); tw.setBody("<sup>super</sup> "// + "<span data-id=\"9075405\" data-marker=\"begin\"></span>"// + "normaal <sub>"// + "<sup data-id=\"9075405\" data-marker=\"end\">1</sup>"// + "sub</sub><br><sup>super</sup> normaal <sub>sub<br></sub><sup>super</sup> normaal <sub>sub</sub><br>"); String expected = "<body><sup>super</sup> "// + "<ab id=\"9075405\"/>"// + "normaal <sub>"// + "<ae id=\"9075405\"/>"// + "sub</sub>\n<sup>super</sup> normaal <sub>sub\n</sub><sup>super</sup> normaal <sub>sub</sub>\n</body>"; assertThat(tw.getBodyForDb()).isEqualTo(expected); } // }
pombredanne/elaborate4-backend
elab4-backend/src/test/java/elaborate/editor/resources/orm/wrappers/TranscriptionWrapperTest.java
3,760
// String in = "<br>(zie ook 253r (regel 7) hier staat voluit geschreven onse Raitsvrend<i>en</i> (misschien hier ook Raitsvrend<i>e</i> ?,"//
line_comment
nl
package elaborate.editor.resources.orm.wrappers; /* * #%L * elab4-backend * ======= * Copyright (C) 2011 - 2015 Huygens ING * ======= * 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/gpl-3.0.html>. * #L% */ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.List; import java.util.Map; import org.junit.After; import org.junit.Before; import org.junit.Test; import com.google.common.collect.ImmutableMap; import elaborate.editor.model.orm.Transcription; import elaborate.editor.model.orm.service.ProjectService; import elaborate.editor.model.orm.service.ProjectService.AnnotationData; public class TranscriptionWrapperTest { @Before public void setUp() throws Exception {} @After public void tearDown() throws Exception {} @Test public void testTranscriptionWrapper() throws Exception { String textLayer = "textlayer"; String title = "title"; String body = "<body><ab id=\"9085822\"/>sdgdgdgsdgsdfg<ae id=\"9085822\"/></body>"; Transcription transcription = mockTranscription(textLayer, title, body); Map<Integer, AnnotationData> annotationDataMap = ImmutableMap.of(9085822, new AnnotationData().setType("type")); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, annotationDataMap); // assertThat( tw.title).isEqualTo(title); assertThat(tw.getTextLayer()).isEqualTo(textLayer); String expected = "<span data-marker=\"begin\" data-id=\"9085822\" data-type=\"type\"></span>sdgdgdgsdgsdfg<sup data-marker=\"end\" data-id=\"9085822\">1</sup>"; assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testTranscriptionWrapperWithBadXHtmlInput() throws Exception { String textLayer = "textlayer"; String title = "title"; String body = "<body><span style=\"font-size:11.0pt;line-height:115%; font-family:\"Verdana\",\"sans-serif\";mso-fareast-font-family:Calibri;mso-fareast-theme-font: minor-latin;mso-bidi-font-family:\"Times New Roman\";mso-bidi-theme-font:minor-bidi; mso-ansi-language:NL;mso-fareast-language:EN-US;mso-bidi-language:AR-SA\">Hoezo mag ik niet copy-pasten vanuit Word? Maar ik wil het!</span></body>"; Transcription transcription = mockTranscription(textLayer, title, body); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); // assertThat( tw.title).isEqualTo(title); assertThat(tw.getTextLayer()).isEqualTo(textLayer); String expected = "Hoezo mag ik niet copy-pasten vanuit Word? Maar ik wil het!"; assertThat(tw.getBody()).isEqualTo(expected); } private Transcription mockTranscription(String textLayer, String title, String body) { Transcription transcription = mock(Transcription.class); when(transcription.getTextLayer()).thenReturn(textLayer); when(transcription.getTitle()).thenReturn(title); when(transcription.getBody()).thenReturn(body); return transcription; } @Test public void testConvertBodyWithEmptyTagsForOutput() throws Exception { String in = "<body>bla <i></i> bla <strong></strong> bla</body>"; String expected = "bla bla bla"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertBodyForOutput() throws Exception { String in = "<body>"// + " "// + "<ab id=\"9085822\"/>"// + "bla "// + "<ab id=\"9085821\"/>"// + "die"// + "<ae id=\"9085822\"/>"// + " bla"// + "<ae id=\"9085821\"/>"// + "\nhello world "// + "</body>"; String expected = "<span data-marker=\"begin\" data-id=\"9085822\" data-type=\"type2\"></span>"// + "bla "// + "<span data-marker=\"begin\" data-id=\"9085821\" data-type=\"type1\"></span>"// + "die"// + "<sup data-marker=\"end\" data-id=\"9085822\">1</sup>"// + " bla"// + "<sup data-marker=\"end\" data-id=\"9085821\">2</sup>"// + "<br>hello world"; Transcription transcription = mockTranscription("textLayer", "title", in); Map<Integer, AnnotationData> annotationDataMap = ImmutableMap.<Integer, ProjectService.AnnotationData> builder()// .put(9085821, new AnnotationData().setType("type1"))// .put(9085822, new AnnotationData().setType("type2"))// .build(); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, annotationDataMap); assertThat(tw.getBody()).isEqualTo(expected); List<Integer> annotationNumbers = tw.annotationNumbers; assertThat(annotationNumbers.size()).isEqualTo(2); assertThat(annotationNumbers.get(0)).isEqualTo(Integer.valueOf(9085822)); assertThat(annotationNumbers.get(1)).isEqualTo(Integer.valueOf(9085821)); } @Test public void testConvertBodyForOutput_with_superfluous_newlines_at_the_end() throws Exception { String in = "<body>lorem epsum doleres whatever\n \n\n\n</body>"; String expected = "lorem epsum doleres whatever"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertBodyForOutput_with_superfluous_whitespace_at_the_end() throws Exception { String in = "<body>body\n \n </body>"; String expected = "body"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertBodyForOutput_with_shift_space() throws Exception { String in = "<body>header\n  paragraph 1\n  paragraph 2   \n paragraph 3</body>"; String expected = "header<br>&nbsp;&nbsp;paragraph 1<br>&nbsp;&nbsp;paragraph 2&nbsp;&nbsp;&nbsp;<br> paragraph 3"; Transcription transcription = mockTranscription("textLayer", "title", in); TranscriptionWrapper tw = new TranscriptionWrapper(transcription, null); assertThat(tw.getBody()).isEqualTo(expected); } @Test public void testConvertFromInput() throws Exception { String in = "<span data-marker=\"begin\" data-id=\"9085822\">bla die bla</span><sup data-marker=\"end\" data-id=\"9085822\">1</sup><br>hello world"; String expected = "<body><ab id=\"9085822\"/>bla die bla<ae id=\"9085822\"/>\nhello world</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputWithBadChar() throws Exception { String in = "the smiling ones danced like blooming girls, I presumed boldly to rank _x001A_the former"; String expected = "<body>the smiling ones danced like blooming girls, I presumed boldly to rank the former</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputWithBreaks() throws Exception { String in = "hop<br>on<br>pop"; String expected = "<body>hop\non\npop</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputRemovesXMLComments() throws Exception { String in = "bla <!-- ignore comments --> bla"; String expected = "<body>bla bla</body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputConvertsEmToI() throws Exception { String in = "<em style=\"white-space: normal;\">Casteleijn</em>"; String expected = "<body><i>Casteleijn</i></body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputConvertsStrongToB() throws Exception { String in = "<strong style=\"white-space: normal;\">TGIF</strong>"; String expected = "<body><b>TGIF</b></body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } @Test public void testConvertFromInputRemovesMostWordTags() throws Exception { String in = "<p class=\"MsoNormal\" style=\"margin-right:29.9pt;text-align:justify\">"// + "I <i style=\"mso-bidi-font-style:normal\">HEART</i>"// + " <b style=\"mso-bidi-font-weight:normal\">WORD!!</b>"// + "</p>"; String expected = "<body>I <i>HEART</i> <b>WORD!!</b></body>"; assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); } // @Test // public void testConvertFromInputRemovesMostWordTags1() throws Exception { // String in<SUF> // + "maar vrint zou tot de sterke flextie moeten behoren dus moeten eindigen op -en?))<br>KG:&nbsp; Samen graag nog even hebben over de"// // + " meervoudvorm.<br><br><br>34: oirer -&gt; oiren [?]<br>sendebode: m. acc. pl. (Zwakke flextie?) het zou dan oire moeten worden. Is"// // + " hier misschien de letter 'r' afgekort?<br>KG: als boven. <br><br><p class=\"MsoNormal\">‘raitsvrenden’: volgens Van Loey,"// // + " <i style=\"mso-bidi-font-style: normal\">Mndld Spraakkunst </i>I § 19.2 kan het bij ‘vrient’ (en ‘viant’)<br>allebei -&gt; dan"// // + " beslist de paleografie</p><p class=\"MsoNormal\"><br></p><p class=\"MsoNormal\">260v \"onse vrende\" voluit geschreven<br></p><br>"// // + "<br><br><br><br>-------------------------------------------------------------------------<br>Translation<br>- Wijk ( bij Duurstede)?"// // + "<br><br>"; // String expected = "<body></body>"; // assertThat(TranscriptionWrapper.convertFromInput(in)).isEqualTo(expected); // } @Test public void testSuperscriptIsHandledWell() throws Exception { TranscriptionWrapper tw = new TranscriptionWrapper(); tw.setBody("<sup>super</sup> normaal <sub>sub</sub><br><sup>super</sup> normaal <sub>sub<br></sub><sup>super</sup> normaal <sub>sub</sub><br>"); String expected = "<body><sup>super</sup> normaal <sub>sub</sub>\n<sup>super</sup> normaal <sub>sub\n</sub><sup>super</sup> normaal <sub>sub</sub>\n</body>"; assertThat(tw.getBodyForDb()).isEqualTo(expected); } @Test public void testAnnotationMarkerIsHandledWell() throws Exception { TranscriptionWrapper tw = new TranscriptionWrapper(); tw.setBody("<sup>super</sup> "// + "<span data-id=\"9075405\" data-marker=\"begin\"></span>"// + "normaal <sub>"// + "<sup data-id=\"9075405\" data-marker=\"end\">1</sup>"// + "sub</sub><br><sup>super</sup> normaal <sub>sub<br></sub><sup>super</sup> normaal <sub>sub</sub><br>"); String expected = "<body><sup>super</sup> "// + "<ab id=\"9075405\"/>"// + "normaal <sub>"// + "<ae id=\"9075405\"/>"// + "sub</sub>\n<sup>super</sup> normaal <sub>sub\n</sub><sup>super</sup> normaal <sub>sub</sub>\n</body>"; assertThat(tw.getBodyForDb()).isEqualTo(expected); } // }
False
3,177
57
3,659
64
3,354
48
3,659
64
4,047
59
false
false
false
false
false
true
4,370
95539_4
package com.spotinst.sdkjava.model; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Created by aharontwizer on 8/24/15. */ public class Elastigroup { //region Members @JsonIgnore private Set<String> isSet; private String id; private String name; private String description; private String region; private ElastigroupCapacityConfiguration capacity; private ElastigroupStrategyConfiguration strategy; private ElastigroupComputeConfiguration compute; private ElastigroupScalingConfiguration scaling; private ElastigroupThirdPartiesIntegrationConfiguration thirdPartiesIntegration; private ElastigroupSchedulingConfiguration scheduling; private Date createdAt; private Date updatedAt; //endregion //region Constructor private Elastigroup() { isSet = new HashSet<>(); } //endregion //region Getters & Setters public ElastigroupThirdPartiesIntegrationConfiguration getThirdPartiesIntegration() { return thirdPartiesIntegration; } public void setThirdPartiesIntegration(ElastigroupThirdPartiesIntegrationConfiguration thirdPartiesIntegration) { isSet.add("thirdPartiesIntegration"); this.thirdPartiesIntegration = thirdPartiesIntegration; } public Set<String> getIsSet() { return isSet; } public void setIsSet(Set<String> isSet) { this.isSet = isSet; } public String getId() { return id; } public void setId(String id) { isSet.add("id"); this.id = id; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { isSet.add("createdAt"); this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { isSet.add("updatedAt"); this.updatedAt = updatedAt; } public String getName() { return name; } public void setName(String name) { isSet.add("name"); this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { isSet.add("description"); this.description = description; } public ElastigroupCapacityConfiguration getCapacity() { return capacity; } public void setCapacity(ElastigroupCapacityConfiguration capacity) { isSet.add("capacity"); this.capacity = capacity; } public ElastigroupStrategyConfiguration getStrategy() { return strategy; } public void setStrategy(ElastigroupStrategyConfiguration strategy) { isSet.add("strategy"); this.strategy = strategy; } public ElastigroupComputeConfiguration getCompute() { return compute; } public void setCompute(ElastigroupComputeConfiguration compute) { isSet.add("compute"); this.compute = compute; } public String getRegion() { return region; } public void setRegion(String region) { isSet.add("region"); this.region = region; } public ElastigroupScalingConfiguration getScaling() { return scaling; } public void setScaling(ElastigroupScalingConfiguration scaling) { isSet.add("scaling"); this.scaling = scaling; } public ElastigroupSchedulingConfiguration getScheduling() { return scheduling; } public void setScheduling(ElastigroupSchedulingConfiguration scheduling) { isSet.add("scheduling"); this.scheduling = scheduling; } //endregion //region Builder class public static class Builder { //region Members private Elastigroup elastigroup; //endregion private Builder() { this.elastigroup = new Elastigroup(); } public static Builder get() { return new Builder(); } //region Build methods protected Builder setId(final String elastigroupId) { elastigroup.setId(elastigroupId); return this; } public Builder setThirdPartiesIntegration(final ElastigroupThirdPartiesIntegrationConfiguration thirdPartiesIntegration) { elastigroup.setThirdPartiesIntegration(thirdPartiesIntegration); return this; } public Builder setScheduling(final ElastigroupSchedulingConfiguration scheduling){ elastigroup.setScheduling(scheduling); return this; } public Builder setName(final String name) { elastigroup.setName(name); return this; } public Builder setDescription(final String description) { elastigroup.setDescription(description); return this; } public Builder setRegion(final String region) { elastigroup.setRegion(region); return this; } public Builder setCapacity(final ElastigroupCapacityConfiguration capacity) { elastigroup.setCapacity(capacity); return this; } public Builder setStrategy(final ElastigroupStrategyConfiguration strategy) { elastigroup.setStrategy(strategy); return this; } public Builder setCompute(final ElastigroupComputeConfiguration compute) { elastigroup.setCompute(compute); return this; } public Builder setScaling(final ElastigroupScalingConfiguration elastigroupScalingConfiguration) { elastigroup.setScaling(elastigroupScalingConfiguration); return this; } public Elastigroup build() { // Validations return elastigroup; } //endregion } //endregion //region isSet methods // Is thirdPartiesIntegration Set boolean method @JsonIgnore public boolean isThirdPartiesIntegrationSet() { return isSet.contains("thirdPartiesIntegration"); } // Is id Set boolean method @JsonIgnore public boolean isIdSet() { return isSet.contains("id"); } // Is name Set boolean method @JsonIgnore public boolean isNameSet() { return isSet.contains("name"); } // Is description Set boolean method @JsonIgnore public boolean isDescriptionSet() { return isSet.contains("description"); } // Is region Set boolean method @JsonIgnore public boolean isRegionSet() { return isSet.contains("region"); } // Is capacity Set boolean method @JsonIgnore public boolean isCapacitySet() { return isSet.contains("capacity"); } // Is strategy Set boolean method @JsonIgnore public boolean isStrategySet() { return isSet.contains("strategy"); } // Is compute Set boolean method @JsonIgnore public boolean isComputeSet() { return isSet.contains("compute"); } // Is scaling Set boolean method @JsonIgnore public boolean isScalingSet() { return isSet.contains("scaling"); } // Is createdAt Set boolean method @JsonIgnore public boolean isCreatedAtSet() { return isSet.contains("createdAt"); } // Is updatedAt Set boolean method @JsonIgnore public boolean isUpdatedAtSet() { return isSet.contains("updatedAt"); } // Is scheduling Set boolean method @JsonIgnore public boolean isSchedulingSet() { return isSet.contains("scheduling"); } //endregion }
spotinst/spotinst-sdk-java
src/main/java/com/spotinst/sdkjava/model/Elastigroup.java
2,117
//region isSet methods
line_comment
nl
package com.spotinst.sdkjava.model; import com.fasterxml.jackson.annotation.JsonIgnore; import java.util.Date; import java.util.HashSet; import java.util.Set; /** * Created by aharontwizer on 8/24/15. */ public class Elastigroup { //region Members @JsonIgnore private Set<String> isSet; private String id; private String name; private String description; private String region; private ElastigroupCapacityConfiguration capacity; private ElastigroupStrategyConfiguration strategy; private ElastigroupComputeConfiguration compute; private ElastigroupScalingConfiguration scaling; private ElastigroupThirdPartiesIntegrationConfiguration thirdPartiesIntegration; private ElastigroupSchedulingConfiguration scheduling; private Date createdAt; private Date updatedAt; //endregion //region Constructor private Elastigroup() { isSet = new HashSet<>(); } //endregion //region Getters & Setters public ElastigroupThirdPartiesIntegrationConfiguration getThirdPartiesIntegration() { return thirdPartiesIntegration; } public void setThirdPartiesIntegration(ElastigroupThirdPartiesIntegrationConfiguration thirdPartiesIntegration) { isSet.add("thirdPartiesIntegration"); this.thirdPartiesIntegration = thirdPartiesIntegration; } public Set<String> getIsSet() { return isSet; } public void setIsSet(Set<String> isSet) { this.isSet = isSet; } public String getId() { return id; } public void setId(String id) { isSet.add("id"); this.id = id; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { isSet.add("createdAt"); this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { isSet.add("updatedAt"); this.updatedAt = updatedAt; } public String getName() { return name; } public void setName(String name) { isSet.add("name"); this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { isSet.add("description"); this.description = description; } public ElastigroupCapacityConfiguration getCapacity() { return capacity; } public void setCapacity(ElastigroupCapacityConfiguration capacity) { isSet.add("capacity"); this.capacity = capacity; } public ElastigroupStrategyConfiguration getStrategy() { return strategy; } public void setStrategy(ElastigroupStrategyConfiguration strategy) { isSet.add("strategy"); this.strategy = strategy; } public ElastigroupComputeConfiguration getCompute() { return compute; } public void setCompute(ElastigroupComputeConfiguration compute) { isSet.add("compute"); this.compute = compute; } public String getRegion() { return region; } public void setRegion(String region) { isSet.add("region"); this.region = region; } public ElastigroupScalingConfiguration getScaling() { return scaling; } public void setScaling(ElastigroupScalingConfiguration scaling) { isSet.add("scaling"); this.scaling = scaling; } public ElastigroupSchedulingConfiguration getScheduling() { return scheduling; } public void setScheduling(ElastigroupSchedulingConfiguration scheduling) { isSet.add("scheduling"); this.scheduling = scheduling; } //endregion //region Builder class public static class Builder { //region Members private Elastigroup elastigroup; //endregion private Builder() { this.elastigroup = new Elastigroup(); } public static Builder get() { return new Builder(); } //region Build methods protected Builder setId(final String elastigroupId) { elastigroup.setId(elastigroupId); return this; } public Builder setThirdPartiesIntegration(final ElastigroupThirdPartiesIntegrationConfiguration thirdPartiesIntegration) { elastigroup.setThirdPartiesIntegration(thirdPartiesIntegration); return this; } public Builder setScheduling(final ElastigroupSchedulingConfiguration scheduling){ elastigroup.setScheduling(scheduling); return this; } public Builder setName(final String name) { elastigroup.setName(name); return this; } public Builder setDescription(final String description) { elastigroup.setDescription(description); return this; } public Builder setRegion(final String region) { elastigroup.setRegion(region); return this; } public Builder setCapacity(final ElastigroupCapacityConfiguration capacity) { elastigroup.setCapacity(capacity); return this; } public Builder setStrategy(final ElastigroupStrategyConfiguration strategy) { elastigroup.setStrategy(strategy); return this; } public Builder setCompute(final ElastigroupComputeConfiguration compute) { elastigroup.setCompute(compute); return this; } public Builder setScaling(final ElastigroupScalingConfiguration elastigroupScalingConfiguration) { elastigroup.setScaling(elastigroupScalingConfiguration); return this; } public Elastigroup build() { // Validations return elastigroup; } //endregion } //endregion //region isSet<SUF> // Is thirdPartiesIntegration Set boolean method @JsonIgnore public boolean isThirdPartiesIntegrationSet() { return isSet.contains("thirdPartiesIntegration"); } // Is id Set boolean method @JsonIgnore public boolean isIdSet() { return isSet.contains("id"); } // Is name Set boolean method @JsonIgnore public boolean isNameSet() { return isSet.contains("name"); } // Is description Set boolean method @JsonIgnore public boolean isDescriptionSet() { return isSet.contains("description"); } // Is region Set boolean method @JsonIgnore public boolean isRegionSet() { return isSet.contains("region"); } // Is capacity Set boolean method @JsonIgnore public boolean isCapacitySet() { return isSet.contains("capacity"); } // Is strategy Set boolean method @JsonIgnore public boolean isStrategySet() { return isSet.contains("strategy"); } // Is compute Set boolean method @JsonIgnore public boolean isComputeSet() { return isSet.contains("compute"); } // Is scaling Set boolean method @JsonIgnore public boolean isScalingSet() { return isSet.contains("scaling"); } // Is createdAt Set boolean method @JsonIgnore public boolean isCreatedAtSet() { return isSet.contains("createdAt"); } // Is updatedAt Set boolean method @JsonIgnore public boolean isUpdatedAtSet() { return isSet.contains("updatedAt"); } // Is scheduling Set boolean method @JsonIgnore public boolean isSchedulingSet() { return isSet.contains("scheduling"); } //endregion }
False
1,540
5
1,621
4
1,798
4
1,621
4
2,144
5
false
false
false
false
false
true
3
87789_8
package mongodbtest; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; /** * * @author Alex */ // Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt public class MongoDBTest<T>{ public static void main(String[] args) throws UnknownHostException { DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database DBCollection colEmployee = db.getCollection("Employee");//table List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny")); List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu")); List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester")); List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21)); // Forloop dient als een generator die gebruik maakt van een random method ///////////////////////////////////////////////// //// Generate random database info ///// ///////////////////////////////////////////////// for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'" + ",'building_name':'H-Gebouw'" + ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25}," + "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}]," + "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99 +"', 'worked_hours':"+ getRandomItem(listHours) +"}]," + "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}"; DBObject dbObject = (DBObject)JSON.parse(json);//parser colEmployee.insert(dbObject);// insert in database } BasicDBObject fields = new BasicDBObject(); fields.put("e_bsn", 1);//get only 1 field BasicDBObject uWQuery = new BasicDBObject(); uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking BasicDBObject nWQuery = new BasicDBObject(); nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal BasicDBObject oWQuery = new BasicDBObject(); oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork BasicDBObject pidQuery = new BasicDBObject(); pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in project BasicDBObject hourQuery = new BasicDBObject(); hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork BasicDBObject nameQuery = new BasicDBObject(); nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS while (cursorDocJSON.hasNext()) { System.out.println(cursorDocJSON.next()); } colEmployee.remove(new BasicDBObject()); } static Random rand = new Random(); static <T> T getRandomItem(List<T> list) { return list.get(rand.nextInt(list.size())); } }
0NightBot0/DevDatabase
assignment 2/MongoDB/src/mongodbtest/MongoDBTest.java
1,285
//work in project
line_comment
nl
package mongodbtest; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; /** * * @author Alex */ // Er is geen mapreduce, lambda functies verwerken in java was te tijd rovend naar het uitvinden van hoe mongoDB werkt public class MongoDBTest<T>{ public static void main(String[] args) throws UnknownHostException { DB db = (new MongoClient("localhost",27017)).getDB("Hro");//database DBCollection colEmployee = db.getCollection("Employee");//table List<String> listName = new ArrayList<>(Arrays.asList("Peter","Jay","Mike","Sally","Michel","Bob","Jenny")); List<String> listSurname = new ArrayList<>(Arrays.asList("Ra","Grey","Uks","Bla","Woo","Foo","Lu")); List<String> listOccupation = new ArrayList<>(Arrays.asList("Analyst","Developer","Tester")); List<Integer> listHours = new ArrayList<>(Arrays.asList(4,5,6,19,20,21)); // Forloop dient als een generator die gebruik maakt van een random method ///////////////////////////////////////////////// //// Generate random database info ///// ///////////////////////////////////////////////// for(int i = 11000; i < 21000;i++){ // creëren hiermee bsn nummers van 5 cijfers String json = "{'e_bsn': '" + Integer.toString(i) + "', 'Name':'" + getRandomItem(listName) +"','Surname':'" + getRandomItem(listSurname) +"'" + ",'building_name':'H-Gebouw'" + ",'address':[{'country': 'Nederland','Postal_code':'3201TL','City':'Spijkenisse','Street':'Wagenmaker','house_nr':25}," + "{'country': 'Nederland','Postal_code':'3201RR','City':'Spijkenisse','Street':'Slaanbreek','house_nr':126}]," + "'Position_project': [{'p_id': 'P" + Integer.toString(i%100) + "','position_project':'"+ getRandomItem(listOccupation) // modulo zorgt voor projecten P0 t/m P99 +"', 'worked_hours':"+ getRandomItem(listHours) +"}]," + "'degree_employee': [{'Course':'Informatica','School':'HogeSchool Rotterdam','Level':'Bachelorr'}]}"; DBObject dbObject = (DBObject)JSON.parse(json);//parser colEmployee.insert(dbObject);// insert in database } BasicDBObject fields = new BasicDBObject(); fields.put("e_bsn", 1);//get only 1 field BasicDBObject uWQuery = new BasicDBObject(); uWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", -1).append("$lt", 5));//underworking BasicDBObject nWQuery = new BasicDBObject(); nWQuery.put("Position_project.worked_hours", new BasicDBObject("$gte", 5).append("$lte", 20));//working normal BasicDBObject oWQuery = new BasicDBObject(); oWQuery.put("Position_project.worked_hours", new BasicDBObject("$gt", 20));//overwork BasicDBObject pidQuery = new BasicDBObject(); pidQuery.put("Position_project.p_id", new BasicDBObject("$eq", "P20"));//work in<SUF> BasicDBObject hourQuery = new BasicDBObject(); hourQuery.put("Position_project.worked_hours", new BasicDBObject("$eq", 20));//overwork BasicDBObject nameQuery = new BasicDBObject(); nameQuery.put("e_bsn", new BasicDBObject("$eq", "11200"));//find e_bsn DBCursor cursorDocJSON = colEmployee.find(nameQuery,fields); //get documents USE the QUERY and the FIELDS while (cursorDocJSON.hasNext()) { System.out.println(cursorDocJSON.next()); } colEmployee.remove(new BasicDBObject()); } static Random rand = new Random(); static <T> T getRandomItem(List<T> list) { return list.get(rand.nextInt(list.size())); } }
False
970
5
1,123
5
1,098
5
1,123
5
1,271
5
false
false
false
false
false
true
4,352
124319_13
package ch.so.agi.ilivalidator.service; import java.io.File; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import ch.ehi.basics.settings.Settings; import ch.interlis.iom_j.itf.ItfReader; import ch.interlis.iom_j.xtf.XtfReader; import ch.interlis.iox.IoxEvent; import ch.interlis.iox.IoxException; import ch.interlis.iox.IoxReader; import ch.interlis.iox_j.EndTransferEvent; import ch.interlis.iox_j.StartBasketEvent; import ch.so.agi.ilivalidator.Utils; import org.apache.commons.io.FilenameUtils; import org.interlis2.validator.Validator; import org.jobrunr.jobs.annotations.Job; @Service public class IlivalidatorService { private final Logger log = LoggerFactory.getLogger(this.getClass()); private static final String ILI_SUBDIRECTORY = "ili"; private static final String INI_SUBDIRECTORY = "ini"; private StorageService storageService; @Value("${app.docBase}") private String docBase; @Value("${app.configDirectoryName}") private String configDirectoryName; @Value("${app.workDirectory}") private String workDirectory; @Value("${app.folderPrefix}") private String folderPrefix; @Value("${app.preferredIliRepo}") private String preferredIliRepo; public IlivalidatorService(StorageService storageService) { this.storageService = storageService; } /** * This method validates an INTERLIS transfer file with * <a href="https://github.com/claeis/ilivalidator">ilivalidator library</a>. * * @param transferFiles * @param modelFiles * @param configFiles * @throws IoxException If an error occurred when trying to figure out model * name. * @throws IOException If config file cannot be read or copied to file system. * @return boolean True, if transfer file is valid. False, if errors were found. */ @Job(name = "Ilivalidator", retries=0) public synchronized boolean validate(Path[] transferFiles, Path[] modelFiles, Path[] configFiles, String theme) throws IoxException, IOException { // Wenn wir nicht das "local"-Filesystem verwenden, müssen die Daten zuerst lokal // verfügbar gemacht werden, weil ilivalidator nur mit "File" und nicht mit "Path" umgehen kann. Path tmpDirectory = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), folderPrefix); List<String> transferFileNames = new ArrayList<>(); List<String> modelFileNames = new ArrayList<>(); List<String> configFileNames = new ArrayList<>(); Path logFile; String logFileName; Path jobDirectoryPath = null; // Original-Jobdirectory-Pfad. Entspricht der Job-Id. Wird beim "Hochladen"/Speichern des lokalen Logfiles gebraucht. if (storageService instanceof LocalStorageService) { for (Path transferFile : transferFiles) { if (jobDirectoryPath == null) { jobDirectoryPath = transferFile.getParent().getFileName(); } transferFileNames.add(transferFile.toFile().getAbsolutePath()); } for (Path modelFile : modelFiles) { modelFileNames.add(modelFile.toFile().getAbsolutePath()); } for (Path configFile : configFiles) { configFileNames.add(configFile.toFile().getAbsolutePath()); } } else { for (Path transferFile : transferFiles) { if (jobDirectoryPath == null) { jobDirectoryPath = transferFile.getParent().getFileName(); } Path localCopy = storageService.load(transferFile, tmpDirectory); transferFileNames.add(localCopy.toFile().getAbsolutePath()); } for (Path modelFile : modelFiles) { Path localCopy = storageService.load(modelFile, tmpDirectory); modelFileNames.add(localCopy.toFile().getAbsolutePath()); } for (Path configFile : configFiles) { Path localCopy = storageService.load(configFile, tmpDirectory); configFileNames.add(localCopy.toFile().getAbsolutePath()); } } // Weil das Verzeichnis nicht nur aus der JobId besteht, sondern ein Prefix besitzt, // muss man dieses wieder entfernen, um den Logfile-Namen zu erhalten (der nur aus JobId) // bestehen soll. logFile = Paths.get(new File(transferFileNames.get(0)).getParent(), jobDirectoryPath.toString().substring(folderPrefix.length()) + ".log"); logFileName = logFile.toFile().getAbsolutePath(); Settings settings = new Settings(); settings.setValue(Validator.SETTING_LOGFILE, logFileName); settings.setValue(Validator.SETTING_XTFLOG, logFileName + ".xtf"); settings.setValue(Validator.SETTING_CSVLOG, logFileName + ".csv"); String settingIlidirs = Validator.SETTING_DEFAULT_ILIDIRS; // Es wird immer der config/ili-Ordner (d.h. dort wo die mit der Anwendung // mitgelieferten Modelle gespeichert sind) als // zusätzliches Repo verwendet. // Weil allenfalls mit der Transferdatei hochgeladene Modelle im gleichen // Verzeichnis wie die Transferdateien liegen, // muss dieses Verzeichnis nicht zusätzlich behandelt werden. Es wird in // Validator.SETTING_DEFAULT_ILIDIRS // bereits berücksichtigt. File builtinIliFiles = Paths.get(docBase, configDirectoryName, ILI_SUBDIRECTORY).toFile(); settingIlidirs = builtinIliFiles.getAbsolutePath() + ";" + preferredIliRepo + ";" + settingIlidirs; settings.setValue(Validator.SETTING_ILIDIRS, settingIlidirs); log.debug("Setting ilidirs: {}", settingIlidirs); // Falls man SETTING_ALL_OBJECTS_ACCESSIBLE ausschalten will, muss dies mit einem Config-File // gemacht werden. settings.setValue(Validator.SETTING_ALL_OBJECTS_ACCESSIBLE, Validator.TRUE); // Falls eine ini-Datei mitgeliefert wird, wird diese verwendet. Sonst wird im // config/ini-Ordner (bei den mit der // Anwendung mitgelieferten) Config-Dateien geschaut, ob eine passende vorhanden // ist. // "Passend" heisst: Weil nun mehrere XTF-Dateien mitgeliefert werden können, // ist es nicht mehr ganz eindeutig. // Es werden alle Modellnamen aus den XTF-Dateien eruiert und dann wird der // erste Config-Datei-Match verwendet. if (configFileNames.size() > 0) { // Dateien ohne "-meta" sind normale ini-Dateien. for (String fileName : configFileNames) { if (!fileName.contains("-meta")) { settings.setValue(Validator.SETTING_CONFIGFILE, fileName); break; } } // Dateien mit "-meta" sind config ini-Dateien. for (String fileName : configFileNames) { if (fileName.contains("-meta")) { settings.setValue(Validator.SETTING_META_CONFIGFILE, fileName); break; } } // Option muss explizit auf NULL gesetzt werden, dann macht ilivalidator nichts // resp. es wird der Wert aus der ini-Datei verwendet. // Siehe Quellcode ilivalidator. // Ggf. noch heikel, da m.E. das auf der Konsole nicht funktionert. Man // kann nicht --allObjectsAccessible verwenden und mit einem config-File // überschreiben. settings.setValue(Validator.SETTING_ALL_OBJECTS_ACCESSIBLE, null); log.debug("Uploaded config file used: {}", configFileNames.get(0)); } else if (theme != null && !theme.isBlank()) { Map<String,String> themes = Utils.themes(); String themeConfig = themes.get(theme); if (themeConfig.startsWith("ilidata:")) { settings.setValue(Validator.SETTING_META_CONFIGFILE, themeConfig); } else { File metaConfigFile = Paths .get(docBase, configDirectoryName, INI_SUBDIRECTORY, theme.toLowerCase() + "-meta.ini") .toFile(); if (metaConfigFile.exists()) { settings.setValue(Validator.SETTING_META_CONFIGFILE, metaConfigFile.getAbsolutePath()); log.debug("Meta config file by theme found in config directory: {}", metaConfigFile.getAbsolutePath()); } else { log.warn("Meta config file by theme NOT found in config directory: {}", metaConfigFile.getAbsolutePath()); } } } else { for (String transferFileName : transferFileNames) { String modelName = getModelNameFromTransferFile(transferFileName); File configFile = Paths.get(docBase, configDirectoryName, INI_SUBDIRECTORY, modelName.toLowerCase() + ".ini").toFile(); if (configFile.exists()) { settings.setValue(Validator.SETTING_CONFIGFILE, configFile.getAbsolutePath()); log.debug("Config file by model name found in config directory: {}", configFile.getAbsolutePath()); break; } } } log.info("Validation start"); boolean valid = Validator.runValidation(transferFileNames.toArray(new String[0]), settings); log.info("Validation end"); // Die lokalen Dateien löschen und das Logfile hochladen. if (!(storageService instanceof LocalStorageService)) { for (String transferFileName : transferFileNames) { Files.delete(Paths.get(transferFileName)); } { // Auch wenn ich ilivalidator ohne Jobrunr aufrufe (und somit der Path ein S3Path ist), // funktioniert das Kopieren nicht: // java.lang.NullPointerException: Cannot invoke "org.carlspring.cloud.storage.s3fs.S3FileStore.name()" because the return value of "org.carlspring.cloud.storage.s3fs.S3Path.getFileStore()" is null storageService.store(logFile, Paths.get(jobDirectoryPath.toString(), logFile.getFileName().toString())); Files.delete(logFile); } for (String modelFileName : modelFileNames) { Files.delete(Paths.get(modelFileName)); } for (String configFileName : configFileNames) { Files.delete(Paths.get(configFileName)); } } return valid; } /* * Figure out INTERLIS model name from INTERLIS transfer file. Works with ili1 * and ili2. */ private String getModelNameFromTransferFile(String transferFileName) throws IoxException { String model = null; String ext = FilenameUtils.getExtension(transferFileName); IoxReader ioxReader = null; try { File transferFile = new File(transferFileName); if (ext.equalsIgnoreCase("itf")) { ioxReader = new ItfReader(transferFile); } else { ioxReader = new XtfReader(transferFile); } IoxEvent event; StartBasketEvent be = null; do { event = ioxReader.read(); if (event instanceof StartBasketEvent) { be = (StartBasketEvent) event; break; } } while (!(event instanceof EndTransferEvent)); ioxReader.close(); ioxReader = null; if (be == null) { throw new IllegalArgumentException("no baskets in transfer-file"); } String namev[] = be.getType().split("\\."); model = namev[0]; } catch (IoxException e) { log.error(e.getMessage()); e.printStackTrace(); throw new IoxException("could not parse file: " + new File(transferFileName).getName()); } finally { if (ioxReader != null) { try { ioxReader.close(); } catch (IoxException e) { log.error(e.getMessage()); e.printStackTrace(); throw new IoxException( "could not close interlise transfer file: " + new File(transferFileName).getName()); } ioxReader = null; } } return model; } }
sogis/ilivalidatorws
ilivalidatorws-server/src/main/java/ch/so/agi/ilivalidator/service/IlivalidatorService.java
3,606
// gemacht werden.
line_comment
nl
package ch.so.agi.ilivalidator.service; import java.io.File; import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import ch.ehi.basics.settings.Settings; import ch.interlis.iom_j.itf.ItfReader; import ch.interlis.iom_j.xtf.XtfReader; import ch.interlis.iox.IoxEvent; import ch.interlis.iox.IoxException; import ch.interlis.iox.IoxReader; import ch.interlis.iox_j.EndTransferEvent; import ch.interlis.iox_j.StartBasketEvent; import ch.so.agi.ilivalidator.Utils; import org.apache.commons.io.FilenameUtils; import org.interlis2.validator.Validator; import org.jobrunr.jobs.annotations.Job; @Service public class IlivalidatorService { private final Logger log = LoggerFactory.getLogger(this.getClass()); private static final String ILI_SUBDIRECTORY = "ili"; private static final String INI_SUBDIRECTORY = "ini"; private StorageService storageService; @Value("${app.docBase}") private String docBase; @Value("${app.configDirectoryName}") private String configDirectoryName; @Value("${app.workDirectory}") private String workDirectory; @Value("${app.folderPrefix}") private String folderPrefix; @Value("${app.preferredIliRepo}") private String preferredIliRepo; public IlivalidatorService(StorageService storageService) { this.storageService = storageService; } /** * This method validates an INTERLIS transfer file with * <a href="https://github.com/claeis/ilivalidator">ilivalidator library</a>. * * @param transferFiles * @param modelFiles * @param configFiles * @throws IoxException If an error occurred when trying to figure out model * name. * @throws IOException If config file cannot be read or copied to file system. * @return boolean True, if transfer file is valid. False, if errors were found. */ @Job(name = "Ilivalidator", retries=0) public synchronized boolean validate(Path[] transferFiles, Path[] modelFiles, Path[] configFiles, String theme) throws IoxException, IOException { // Wenn wir nicht das "local"-Filesystem verwenden, müssen die Daten zuerst lokal // verfügbar gemacht werden, weil ilivalidator nur mit "File" und nicht mit "Path" umgehen kann. Path tmpDirectory = Files.createTempDirectory(Paths.get(System.getProperty("java.io.tmpdir")), folderPrefix); List<String> transferFileNames = new ArrayList<>(); List<String> modelFileNames = new ArrayList<>(); List<String> configFileNames = new ArrayList<>(); Path logFile; String logFileName; Path jobDirectoryPath = null; // Original-Jobdirectory-Pfad. Entspricht der Job-Id. Wird beim "Hochladen"/Speichern des lokalen Logfiles gebraucht. if (storageService instanceof LocalStorageService) { for (Path transferFile : transferFiles) { if (jobDirectoryPath == null) { jobDirectoryPath = transferFile.getParent().getFileName(); } transferFileNames.add(transferFile.toFile().getAbsolutePath()); } for (Path modelFile : modelFiles) { modelFileNames.add(modelFile.toFile().getAbsolutePath()); } for (Path configFile : configFiles) { configFileNames.add(configFile.toFile().getAbsolutePath()); } } else { for (Path transferFile : transferFiles) { if (jobDirectoryPath == null) { jobDirectoryPath = transferFile.getParent().getFileName(); } Path localCopy = storageService.load(transferFile, tmpDirectory); transferFileNames.add(localCopy.toFile().getAbsolutePath()); } for (Path modelFile : modelFiles) { Path localCopy = storageService.load(modelFile, tmpDirectory); modelFileNames.add(localCopy.toFile().getAbsolutePath()); } for (Path configFile : configFiles) { Path localCopy = storageService.load(configFile, tmpDirectory); configFileNames.add(localCopy.toFile().getAbsolutePath()); } } // Weil das Verzeichnis nicht nur aus der JobId besteht, sondern ein Prefix besitzt, // muss man dieses wieder entfernen, um den Logfile-Namen zu erhalten (der nur aus JobId) // bestehen soll. logFile = Paths.get(new File(transferFileNames.get(0)).getParent(), jobDirectoryPath.toString().substring(folderPrefix.length()) + ".log"); logFileName = logFile.toFile().getAbsolutePath(); Settings settings = new Settings(); settings.setValue(Validator.SETTING_LOGFILE, logFileName); settings.setValue(Validator.SETTING_XTFLOG, logFileName + ".xtf"); settings.setValue(Validator.SETTING_CSVLOG, logFileName + ".csv"); String settingIlidirs = Validator.SETTING_DEFAULT_ILIDIRS; // Es wird immer der config/ili-Ordner (d.h. dort wo die mit der Anwendung // mitgelieferten Modelle gespeichert sind) als // zusätzliches Repo verwendet. // Weil allenfalls mit der Transferdatei hochgeladene Modelle im gleichen // Verzeichnis wie die Transferdateien liegen, // muss dieses Verzeichnis nicht zusätzlich behandelt werden. Es wird in // Validator.SETTING_DEFAULT_ILIDIRS // bereits berücksichtigt. File builtinIliFiles = Paths.get(docBase, configDirectoryName, ILI_SUBDIRECTORY).toFile(); settingIlidirs = builtinIliFiles.getAbsolutePath() + ";" + preferredIliRepo + ";" + settingIlidirs; settings.setValue(Validator.SETTING_ILIDIRS, settingIlidirs); log.debug("Setting ilidirs: {}", settingIlidirs); // Falls man SETTING_ALL_OBJECTS_ACCESSIBLE ausschalten will, muss dies mit einem Config-File // gemacht werden.<SUF> settings.setValue(Validator.SETTING_ALL_OBJECTS_ACCESSIBLE, Validator.TRUE); // Falls eine ini-Datei mitgeliefert wird, wird diese verwendet. Sonst wird im // config/ini-Ordner (bei den mit der // Anwendung mitgelieferten) Config-Dateien geschaut, ob eine passende vorhanden // ist. // "Passend" heisst: Weil nun mehrere XTF-Dateien mitgeliefert werden können, // ist es nicht mehr ganz eindeutig. // Es werden alle Modellnamen aus den XTF-Dateien eruiert und dann wird der // erste Config-Datei-Match verwendet. if (configFileNames.size() > 0) { // Dateien ohne "-meta" sind normale ini-Dateien. for (String fileName : configFileNames) { if (!fileName.contains("-meta")) { settings.setValue(Validator.SETTING_CONFIGFILE, fileName); break; } } // Dateien mit "-meta" sind config ini-Dateien. for (String fileName : configFileNames) { if (fileName.contains("-meta")) { settings.setValue(Validator.SETTING_META_CONFIGFILE, fileName); break; } } // Option muss explizit auf NULL gesetzt werden, dann macht ilivalidator nichts // resp. es wird der Wert aus der ini-Datei verwendet. // Siehe Quellcode ilivalidator. // Ggf. noch heikel, da m.E. das auf der Konsole nicht funktionert. Man // kann nicht --allObjectsAccessible verwenden und mit einem config-File // überschreiben. settings.setValue(Validator.SETTING_ALL_OBJECTS_ACCESSIBLE, null); log.debug("Uploaded config file used: {}", configFileNames.get(0)); } else if (theme != null && !theme.isBlank()) { Map<String,String> themes = Utils.themes(); String themeConfig = themes.get(theme); if (themeConfig.startsWith("ilidata:")) { settings.setValue(Validator.SETTING_META_CONFIGFILE, themeConfig); } else { File metaConfigFile = Paths .get(docBase, configDirectoryName, INI_SUBDIRECTORY, theme.toLowerCase() + "-meta.ini") .toFile(); if (metaConfigFile.exists()) { settings.setValue(Validator.SETTING_META_CONFIGFILE, metaConfigFile.getAbsolutePath()); log.debug("Meta config file by theme found in config directory: {}", metaConfigFile.getAbsolutePath()); } else { log.warn("Meta config file by theme NOT found in config directory: {}", metaConfigFile.getAbsolutePath()); } } } else { for (String transferFileName : transferFileNames) { String modelName = getModelNameFromTransferFile(transferFileName); File configFile = Paths.get(docBase, configDirectoryName, INI_SUBDIRECTORY, modelName.toLowerCase() + ".ini").toFile(); if (configFile.exists()) { settings.setValue(Validator.SETTING_CONFIGFILE, configFile.getAbsolutePath()); log.debug("Config file by model name found in config directory: {}", configFile.getAbsolutePath()); break; } } } log.info("Validation start"); boolean valid = Validator.runValidation(transferFileNames.toArray(new String[0]), settings); log.info("Validation end"); // Die lokalen Dateien löschen und das Logfile hochladen. if (!(storageService instanceof LocalStorageService)) { for (String transferFileName : transferFileNames) { Files.delete(Paths.get(transferFileName)); } { // Auch wenn ich ilivalidator ohne Jobrunr aufrufe (und somit der Path ein S3Path ist), // funktioniert das Kopieren nicht: // java.lang.NullPointerException: Cannot invoke "org.carlspring.cloud.storage.s3fs.S3FileStore.name()" because the return value of "org.carlspring.cloud.storage.s3fs.S3Path.getFileStore()" is null storageService.store(logFile, Paths.get(jobDirectoryPath.toString(), logFile.getFileName().toString())); Files.delete(logFile); } for (String modelFileName : modelFileNames) { Files.delete(Paths.get(modelFileName)); } for (String configFileName : configFileNames) { Files.delete(Paths.get(configFileName)); } } return valid; } /* * Figure out INTERLIS model name from INTERLIS transfer file. Works with ili1 * and ili2. */ private String getModelNameFromTransferFile(String transferFileName) throws IoxException { String model = null; String ext = FilenameUtils.getExtension(transferFileName); IoxReader ioxReader = null; try { File transferFile = new File(transferFileName); if (ext.equalsIgnoreCase("itf")) { ioxReader = new ItfReader(transferFile); } else { ioxReader = new XtfReader(transferFile); } IoxEvent event; StartBasketEvent be = null; do { event = ioxReader.read(); if (event instanceof StartBasketEvent) { be = (StartBasketEvent) event; break; } } while (!(event instanceof EndTransferEvent)); ioxReader.close(); ioxReader = null; if (be == null) { throw new IllegalArgumentException("no baskets in transfer-file"); } String namev[] = be.getType().split("\\."); model = namev[0]; } catch (IoxException e) { log.error(e.getMessage()); e.printStackTrace(); throw new IoxException("could not parse file: " + new File(transferFileName).getName()); } finally { if (ioxReader != null) { try { ioxReader.close(); } catch (IoxException e) { log.error(e.getMessage()); e.printStackTrace(); throw new IoxException( "could not close interlise transfer file: " + new File(transferFileName).getName()); } ioxReader = null; } } return model; } }
False
2,699
5
3,021
7
3,097
5
3,021
7
3,528
6
false
false
false
false
false
true
2,719
115147_1
/* 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.flowable.bpmn.model; /** * @author Tijs Rademakers */ public abstract class Task extends Activity { }
flowable/flowable-engine
modules/flowable-bpmn-model/src/main/java/org/flowable/bpmn/model/Task.java
174
/** * @author Tijs Rademakers */
block_comment
nl
/* 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.flowable.bpmn.model; /** * @author Tijs Rademakers<SUF>*/ public abstract class Task extends Activity { }
False
149
11
169
13
168
11
169
13
196
13
false
false
false
false
false
true
7
208429_0
package net.bipro.namespace.datentypen; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ST_Wasserfahrzeugtyp. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ST_Wasserfahrzeugtyp"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="01"/&gt; * &lt;enumeration value="02"/&gt; * &lt;enumeration value="03"/&gt; * &lt;enumeration value="04"/&gt; * &lt;enumeration value="05"/&gt; * &lt;enumeration value="06"/&gt; * &lt;enumeration value="07"/&gt; * &lt;enumeration value="08"/&gt; * &lt;enumeration value="09"/&gt; * &lt;enumeration value="10"/&gt; * &lt;enumeration value="11"/&gt; * &lt;enumeration value="12"/&gt; * &lt;enumeration value="13"/&gt; * &lt;enumeration value="14"/&gt; * &lt;enumeration value="15"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */ @XmlType(name = "ST_Wasserfahrzeugtyp") @XmlEnum @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-04-19T05:38:04+02:00", comments = "JAXB RI v2.3.2") public enum STWasserfahrzeugtyp { /** * Motorboote und Motorsegler (Ein Motorboot ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug. * Motorsegelschiffe, meistens kurz als Motorsegler oder Fifty-Fifty bezeichnet, sind Yachten, die sowohl mit Segeln als auch unter Motor zufriedenstellend angetrieben werden.) * */ @XmlEnumValue("01") MOTORBOOTE_MOTORSEGLER("01"), /** * Motor-Wasserfahrzeug (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches z.B. als Fahrgastschiffe und Fährboote der Binnen Schifffahrt, Wattfahrt und kleinen Küstenfahrt genutzt wird.) * */ @XmlEnumValue("02") MOTOR_WASSERFAHRZEUG("02"), /** * Dampf- oder Motorgüterschiff (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches vorrangig zum Gütertransport genutzt wird. Nicht dazu gehören Tankschiffe.) * */ @XmlEnumValue("03") DAMPF_MOTORGUETERSCHIFF("03"), /** * Tankschiff (Ein Tankschiff, oder kurz Tanker, ist ein Schiff zum Transport von flüssigen Stoffen, wie Wasser, Rohöl, Ölen, Kraftstoffen, Flüssiggas oder petrochemischen Erzeugnissen.) * */ @XmlEnumValue("04") TANKSCHIFF("04"), /** * Schlepper (Schlepper, auch Schleppschiffe genannt,sind Schiffe mit leistungsstarker Antriebsanlage, die zum Ziehen und Schieben anderer Schiffe oder großer schwimmfähiger Objekte eingesetzt werden.) * */ @XmlEnumValue("05") SCHLEPPER("05"), /** * Schleppkahn (Ein Schleppkahn (oder auch Schute) ist ein Schiff ohne eigenen Antrieb, mit dem Frachtgut auf Flüssen und Kanälen transportiert werden.) * */ @XmlEnumValue("06") SCHLEPPERKAHN("06"), /** * Schubboot (Als Schubboot, umgangssprachlich auch Schuber / Schieber, bezeichnet man ein schiebendes Schiff in der Binnenschifffahrt, welches selbst keine Ladung befördert und ein oder mehrere Schubleichter schiebt. * Die sog. Schubleichter gehören zu der gleichen Klasse/Ausprägung wie Schubboote.) * */ @XmlEnumValue("07") SCHUBBOOT("07"), /** * Fischereifahrzeug für Binnenschifffahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Binnengewässern spezialisiert sind.) * */ @XmlEnumValue("08") FISCHEREIFAHRZEUG_BINNENSCHIFFFAHRT("08"), /** * Fischereifahrzeug für Wattfahrt oder kleine Küstenfahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Watt- oder Küstenfahrt spezialisiert sind.) * */ @XmlEnumValue("09") FISCHEREIFAHRZEUG_WATTFAHRT("09"), /** * Spezialschiffe mit eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche einen eigenen Antrieb besitzen.) * */ @XmlEnumValue("10") SPEZIALSCHIFFE_EIGENER_ANTRIEB("10"), /** * Spezialschiffe ohne eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche keinen eigenen Antrieb besitzen.) * */ @XmlEnumValue("11") SPEZIALSCHIFFE_OHNE_EIGENEN_ANTRIEB("11"), /** * Segelboot oder -jacht (Ein Segelboot ist ein Sportboot, das in erster Linie durch Windkraft betrieben wird. Vom Segelschiff unterscheidet es sich durch seine geringere Größe. * Der Begriff Segelyacht (auch Segeljacht) bezeichnet ein Segelschiff, das hauptsächlich für Freizeit- oder Sportaktivitäten verwendet wird oder gelegentlich auch repräsentativen Zwecken dient.) * */ @XmlEnumValue("12") SEGELBOOT_JACHT("12"), /** * Jetboot (Wassermotorräder, auch bekannt als Jet-Ski oder Jet-Boot, sind relativ kleine, aus glasfaserverstärktem Kunststoff bestehende Wasserfahrzeuge ohne Bordwand. Man unterscheidet Steher für eine Person von Sitzern, Modellen mit Sitzbank, für zwei bis vier Personen. Im Wettkampfbetrieb werden diese beiden Grundmodelle als Ski und Runabout bezeichnet.) * */ @XmlEnumValue("13") JETBOOT("13"), /** * Ruderboot (Ruderboote sind Wasserfahrzeuge, die mit Hilfe von Riemen oder Skulls bewegt werden. * */ @XmlEnumValue("14") RUDERBOOT("14"), /** * Surfbrett (Ein Surfbrett ist ein aus einem schwimmfähigen Material hergestelltes Brett, das als Sportgerät zum Wellenreiten oder zum Windsurfen dient.) * */ @XmlEnumValue("15") SURFBRETT("15"); private final String value; STWasserfahrzeugtyp(String v) { value = v; } public String value() { return value; } public static STWasserfahrzeugtyp fromValue(String v) { for (STWasserfahrzeugtyp c: STWasserfahrzeugtyp.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
0xE282B0/test-bipro
norm426-jaxb-270-template/target/generated-sources/bipro/net/bipro/namespace/datentypen/STWasserfahrzeugtyp.java
2,279
/** * <p>Java class for ST_Wasserfahrzeugtyp. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ST_Wasserfahrzeugtyp"&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"&gt; * &lt;enumeration value="01"/&gt; * &lt;enumeration value="02"/&gt; * &lt;enumeration value="03"/&gt; * &lt;enumeration value="04"/&gt; * &lt;enumeration value="05"/&gt; * &lt;enumeration value="06"/&gt; * &lt;enumeration value="07"/&gt; * &lt;enumeration value="08"/&gt; * &lt;enumeration value="09"/&gt; * &lt;enumeration value="10"/&gt; * &lt;enumeration value="11"/&gt; * &lt;enumeration value="12"/&gt; * &lt;enumeration value="13"/&gt; * &lt;enumeration value="14"/&gt; * &lt;enumeration value="15"/&gt; * &lt;/restriction&gt; * &lt;/simpleType&gt; * </pre> * */
block_comment
nl
package net.bipro.namespace.datentypen; import javax.annotation.Generated; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for<SUF>*/ @XmlType(name = "ST_Wasserfahrzeugtyp") @XmlEnum @Generated(value = "com.sun.tools.xjc.Driver", date = "2021-04-19T05:38:04+02:00", comments = "JAXB RI v2.3.2") public enum STWasserfahrzeugtyp { /** * Motorboote und Motorsegler (Ein Motorboot ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug. * Motorsegelschiffe, meistens kurz als Motorsegler oder Fifty-Fifty bezeichnet, sind Yachten, die sowohl mit Segeln als auch unter Motor zufriedenstellend angetrieben werden.) * */ @XmlEnumValue("01") MOTORBOOTE_MOTORSEGLER("01"), /** * Motor-Wasserfahrzeug (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches z.B. als Fahrgastschiffe und Fährboote der Binnen Schifffahrt, Wattfahrt und kleinen Küstenfahrt genutzt wird.) * */ @XmlEnumValue("02") MOTOR_WASSERFAHRZEUG("02"), /** * Dampf- oder Motorgüterschiff (Ein Motor-Wasserfahrzeug ist ein von einem oder mehreren Verbrennungsmotoren oder Elektromotoren angetriebenes Wasserfahrzeug, welches vorrangig zum Gütertransport genutzt wird. Nicht dazu gehören Tankschiffe.) * */ @XmlEnumValue("03") DAMPF_MOTORGUETERSCHIFF("03"), /** * Tankschiff (Ein Tankschiff, oder kurz Tanker, ist ein Schiff zum Transport von flüssigen Stoffen, wie Wasser, Rohöl, Ölen, Kraftstoffen, Flüssiggas oder petrochemischen Erzeugnissen.) * */ @XmlEnumValue("04") TANKSCHIFF("04"), /** * Schlepper (Schlepper, auch Schleppschiffe genannt,sind Schiffe mit leistungsstarker Antriebsanlage, die zum Ziehen und Schieben anderer Schiffe oder großer schwimmfähiger Objekte eingesetzt werden.) * */ @XmlEnumValue("05") SCHLEPPER("05"), /** * Schleppkahn (Ein Schleppkahn (oder auch Schute) ist ein Schiff ohne eigenen Antrieb, mit dem Frachtgut auf Flüssen und Kanälen transportiert werden.) * */ @XmlEnumValue("06") SCHLEPPERKAHN("06"), /** * Schubboot (Als Schubboot, umgangssprachlich auch Schuber / Schieber, bezeichnet man ein schiebendes Schiff in der Binnenschifffahrt, welches selbst keine Ladung befördert und ein oder mehrere Schubleichter schiebt. * Die sog. Schubleichter gehören zu der gleichen Klasse/Ausprägung wie Schubboote.) * */ @XmlEnumValue("07") SCHUBBOOT("07"), /** * Fischereifahrzeug für Binnenschifffahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Binnengewässern spezialisiert sind.) * */ @XmlEnumValue("08") FISCHEREIFAHRZEUG_BINNENSCHIFFFAHRT("08"), /** * Fischereifahrzeug für Wattfahrt oder kleine Küstenfahrt (Als Fischereifahrzeuge werden alle (Wasser-)Fahrzeuge bezeichnet, die auf den Fang von Wassertieren in Watt- oder Küstenfahrt spezialisiert sind.) * */ @XmlEnumValue("09") FISCHEREIFAHRZEUG_WATTFAHRT("09"), /** * Spezialschiffe mit eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche einen eigenen Antrieb besitzen.) * */ @XmlEnumValue("10") SPEZIALSCHIFFE_EIGENER_ANTRIEB("10"), /** * Spezialschiffe ohne eigenen Antrieb (Hierunter werden alle nicht klassifizierbaren Schiffe spezieller Funktion und/oder Ausführung gezählt, welche keinen eigenen Antrieb besitzen.) * */ @XmlEnumValue("11") SPEZIALSCHIFFE_OHNE_EIGENEN_ANTRIEB("11"), /** * Segelboot oder -jacht (Ein Segelboot ist ein Sportboot, das in erster Linie durch Windkraft betrieben wird. Vom Segelschiff unterscheidet es sich durch seine geringere Größe. * Der Begriff Segelyacht (auch Segeljacht) bezeichnet ein Segelschiff, das hauptsächlich für Freizeit- oder Sportaktivitäten verwendet wird oder gelegentlich auch repräsentativen Zwecken dient.) * */ @XmlEnumValue("12") SEGELBOOT_JACHT("12"), /** * Jetboot (Wassermotorräder, auch bekannt als Jet-Ski oder Jet-Boot, sind relativ kleine, aus glasfaserverstärktem Kunststoff bestehende Wasserfahrzeuge ohne Bordwand. Man unterscheidet Steher für eine Person von Sitzern, Modellen mit Sitzbank, für zwei bis vier Personen. Im Wettkampfbetrieb werden diese beiden Grundmodelle als Ski und Runabout bezeichnet.) * */ @XmlEnumValue("13") JETBOOT("13"), /** * Ruderboot (Ruderboote sind Wasserfahrzeuge, die mit Hilfe von Riemen oder Skulls bewegt werden. * */ @XmlEnumValue("14") RUDERBOOT("14"), /** * Surfbrett (Ein Surfbrett ist ein aus einem schwimmfähigen Material hergestelltes Brett, das als Sportgerät zum Wellenreiten oder zum Windsurfen dient.) * */ @XmlEnumValue("15") SURFBRETT("15"); private final String value; STWasserfahrzeugtyp(String v) { value = v; } public String value() { return value; } public static STWasserfahrzeugtyp fromValue(String v) { for (STWasserfahrzeugtyp c: STWasserfahrzeugtyp.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
False
1,989
333
2,201
351
1,914
345
2,201
351
2,269
389
true
true
true
true
true
false
1,525
154510_6
package com.sri.csl.pvs; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.sri.csl.pvs.declarations.PVSTheory; public class PVSJsonWrapper implements PVSExecutionManager.PVSRespondListener { protected static String ID = "id"; protected static String METHOD = "method"; protected static String PARAMETERS = "params"; protected static String RESULT = "result"; protected static String ERROR = "error"; protected static String RAWCOMMAND = "rawcommand"; protected static String PVSJSONLISPCOMMAND = "pvs-json"; protected static String PVSJSONPROVERCOMMAND = "pvs-prove"; protected static Logger log = Logger.getLogger(PVSJsonWrapper.class.getName()); protected Calendar cal = Calendar.getInstance(); protected ArrayList<JSONObject> responds = new ArrayList<JSONObject>(); private static PVSJsonWrapper instance = null; private PVSJsonWrapper() { super(); } public static void init() { if ( instance == null ) { instance = new PVSJsonWrapper(); } } public static PVSJsonWrapper INST() { return instance; } protected String createID() { return "message_id_" + cal.getTimeInMillis(); } synchronized public void addToJSONQueue(JSONObject obj) { responds.add(obj); } public static ArrayList<PVSTheory> getTheories(JSONObject obj) { ArrayList<PVSTheory> theories = new ArrayList<PVSTheory>(); String _THEORIES = "theories"; if ( obj.has(_THEORIES) ) { JSONArray jTheories; try { jTheories = obj.getJSONArray(_THEORIES); for (int i=0; i<jTheories.length(); i++) { PVSTheory theory = new PVSTheory(jTheories.getJSONObject(i), false); theories.add(theory); } } catch (JSONException e) { log.log(Level.SEVERE, "Problem parsing the theory: {0}", e.getMessage()); e.printStackTrace(); } } log.log(Level.INFO, "Theories: {0}", theories); return theories; } public Object sendRawCommand(String message) throws PVSException { return sendCommand(RAWCOMMAND, message); } public Object sendCommand(String command, Object... parameters) throws PVSException { HashMap<String, Object> map = new HashMap<String, Object>(); String id = createID(); map.put(ID, id); map.put(METHOD, command); try { JSONArray jParams = new JSONArray(parameters); map.put(PARAMETERS, jParams); } catch (JSONException e) { throw new PVSException(e.getMessage()); } JSONObject obj = new JSONObject(map); Object result = sendJSON(id, obj); log.log(Level.INFO, "JSON Result is: {0}", result); return result; } private Object sendJSON(String id, JSONObject obj) throws PVSException { String jsonCommand = null; switch ( PVSExecutionManager.INST().getPVSMode() ) { case LISP: jsonCommand = PVSJSONLISPCOMMAND; break; case PROVER: jsonCommand = PVSJSONLISPCOMMAND; break; } String modifiedObj = obj.toString().replace("\\", "\\\\").replace("\"", "\\\""); String pvsJSON = String.format("(%s \"%s\")", jsonCommand, modifiedObj); log.log(Level.INFO, "Sending JSON message: {0}", pvsJSON); PVSExecutionManager.INST().writeToPVS(pvsJSON); int MAX = 30; for (int i=0; i<50*MAX; i++) { synchronized( responds ) { for (JSONObject respond: responds) { try { String rid = respond.getString(ID); if ( id.equals(rid) ) { responds.remove(respond); if ( respond.has(ERROR) ) { throw new PVSException(respond.getString(ERROR)); } else { Object res = respond.get(RESULT); // if ( res instanceof JSONObject ) { // HashMap<String, Object> map = new HashMap<String, Object>(); // JSONObject objRes = (JSONObject)res; // Iterator<?> it = objRes.keys(); // while ( it.hasNext() ) { // String key = it.next().toString(); // Object value = objRes.get(key); // map.put(key, value); // } // res = map; // } else if ( res instanceof JSONArray ) { // ArrayList<Object> list = new ArrayList<Object>(); // JSONArray arr = (JSONArray)res; // for (int t=0; t<arr.length(); t++) { // list.add(arr.get(t)); // } // res = list; // } return res; } } } catch (Exception e) { throw new PVSException(e.getMessage()); } } } try { Thread.sleep(20); } catch (InterruptedException e) { throw new PVSException(e.getMessage()); } } String errM = "No response from PVS after " + MAX + " seconds"; log.warning(errM); throw new PVSException(errM); } @Override public void onMessageReceived(String message) { } @Override public void onMessageReceived(JSONObject message) { log.log(Level.INFO, "JSON message received: {0}", message); responds.add(message); } @Override public void onPromptReceived(List<String> previousLines, String prompt) { } }
SRI-CSL/PVS
eclipse/plugin/src/main/java/com/sri/csl/pvs/PVSJsonWrapper.java
1,731
// Object value = objRes.get(key);
line_comment
nl
package com.sri.csl.pvs; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.sri.csl.pvs.declarations.PVSTheory; public class PVSJsonWrapper implements PVSExecutionManager.PVSRespondListener { protected static String ID = "id"; protected static String METHOD = "method"; protected static String PARAMETERS = "params"; protected static String RESULT = "result"; protected static String ERROR = "error"; protected static String RAWCOMMAND = "rawcommand"; protected static String PVSJSONLISPCOMMAND = "pvs-json"; protected static String PVSJSONPROVERCOMMAND = "pvs-prove"; protected static Logger log = Logger.getLogger(PVSJsonWrapper.class.getName()); protected Calendar cal = Calendar.getInstance(); protected ArrayList<JSONObject> responds = new ArrayList<JSONObject>(); private static PVSJsonWrapper instance = null; private PVSJsonWrapper() { super(); } public static void init() { if ( instance == null ) { instance = new PVSJsonWrapper(); } } public static PVSJsonWrapper INST() { return instance; } protected String createID() { return "message_id_" + cal.getTimeInMillis(); } synchronized public void addToJSONQueue(JSONObject obj) { responds.add(obj); } public static ArrayList<PVSTheory> getTheories(JSONObject obj) { ArrayList<PVSTheory> theories = new ArrayList<PVSTheory>(); String _THEORIES = "theories"; if ( obj.has(_THEORIES) ) { JSONArray jTheories; try { jTheories = obj.getJSONArray(_THEORIES); for (int i=0; i<jTheories.length(); i++) { PVSTheory theory = new PVSTheory(jTheories.getJSONObject(i), false); theories.add(theory); } } catch (JSONException e) { log.log(Level.SEVERE, "Problem parsing the theory: {0}", e.getMessage()); e.printStackTrace(); } } log.log(Level.INFO, "Theories: {0}", theories); return theories; } public Object sendRawCommand(String message) throws PVSException { return sendCommand(RAWCOMMAND, message); } public Object sendCommand(String command, Object... parameters) throws PVSException { HashMap<String, Object> map = new HashMap<String, Object>(); String id = createID(); map.put(ID, id); map.put(METHOD, command); try { JSONArray jParams = new JSONArray(parameters); map.put(PARAMETERS, jParams); } catch (JSONException e) { throw new PVSException(e.getMessage()); } JSONObject obj = new JSONObject(map); Object result = sendJSON(id, obj); log.log(Level.INFO, "JSON Result is: {0}", result); return result; } private Object sendJSON(String id, JSONObject obj) throws PVSException { String jsonCommand = null; switch ( PVSExecutionManager.INST().getPVSMode() ) { case LISP: jsonCommand = PVSJSONLISPCOMMAND; break; case PROVER: jsonCommand = PVSJSONLISPCOMMAND; break; } String modifiedObj = obj.toString().replace("\\", "\\\\").replace("\"", "\\\""); String pvsJSON = String.format("(%s \"%s\")", jsonCommand, modifiedObj); log.log(Level.INFO, "Sending JSON message: {0}", pvsJSON); PVSExecutionManager.INST().writeToPVS(pvsJSON); int MAX = 30; for (int i=0; i<50*MAX; i++) { synchronized( responds ) { for (JSONObject respond: responds) { try { String rid = respond.getString(ID); if ( id.equals(rid) ) { responds.remove(respond); if ( respond.has(ERROR) ) { throw new PVSException(respond.getString(ERROR)); } else { Object res = respond.get(RESULT); // if ( res instanceof JSONObject ) { // HashMap<String, Object> map = new HashMap<String, Object>(); // JSONObject objRes = (JSONObject)res; // Iterator<?> it = objRes.keys(); // while ( it.hasNext() ) { // String key = it.next().toString(); // Object value<SUF> // map.put(key, value); // } // res = map; // } else if ( res instanceof JSONArray ) { // ArrayList<Object> list = new ArrayList<Object>(); // JSONArray arr = (JSONArray)res; // for (int t=0; t<arr.length(); t++) { // list.add(arr.get(t)); // } // res = list; // } return res; } } } catch (Exception e) { throw new PVSException(e.getMessage()); } } } try { Thread.sleep(20); } catch (InterruptedException e) { throw new PVSException(e.getMessage()); } } String errM = "No response from PVS after " + MAX + " seconds"; log.warning(errM); throw new PVSException(errM); } @Override public void onMessageReceived(String message) { } @Override public void onMessageReceived(JSONObject message) { log.log(Level.INFO, "JSON message received: {0}", message); responds.add(message); } @Override public void onPromptReceived(List<String> previousLines, String prompt) { } }
False
1,272
10
1,550
13
1,545
12
1,550
13
2,015
21
false
false
false
false
false
true
403
96517_4
package info.hb.cnn.core; import info.hb.cnn.utils.MathUtils; import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Layer implements Serializable { private static final long serialVersionUID = -5747622503947497069L; private static Logger logger = LoggerFactory.getLogger(Layer.class); private LayerType type; private int outMapNum; private Size mapSize; private Size kernelSize; private Size scaleSize; private double[][][][] kernel; private double[] bias; private double[][][][] outmaps; private double[][][][] errors; private static int recordInBatch = 0; private int classNum = -1; private Layer() { // } public static void prepareForNewBatch() { recordInBatch = 0; } public static void prepareForNewRecord() { recordInBatch++; } public static Layer buildInputLayer(Size mapSize) { Layer layer = new Layer(); layer.type = LayerType.input; layer.outMapNum = 1; layer.setMapSize(mapSize); return layer; } public static Layer buildConvLayer(int outMapNum, Size kernelSize) { Layer layer = new Layer(); layer.type = LayerType.conv; layer.outMapNum = outMapNum; layer.kernelSize = kernelSize; return layer; } public static Layer buildSampLayer(Size scaleSize) { Layer layer = new Layer(); layer.type = LayerType.samp; layer.scaleSize = scaleSize; return layer; } public static Layer buildOutputLayer(int classNum) { Layer layer = new Layer(); layer.classNum = classNum; layer.type = LayerType.output; layer.mapSize = new Size(1, 1); layer.outMapNum = classNum; // int outMapNum = 1; // while ((1 << outMapNum) < classNum) // outMapNum += 1; // layer.outMapNum = outMapNum; logger.info("outMapNum:{}", layer.outMapNum); return layer; } public Size getMapSize() { return mapSize; } public void setMapSize(Size mapSize) { this.mapSize = mapSize; } public LayerType getType() { return type; } public int getOutMapNum() { return outMapNum; } public void setOutMapNum(int outMapNum) { this.outMapNum = outMapNum; } public Size getKernelSize() { return kernelSize; } public Size getScaleSize() { return scaleSize; } enum LayerType { input, output, conv, samp } public static class Size implements Serializable { private static final long serialVersionUID = -209157832162004118L; public final int x; public final int y; public Size(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { StringBuilder s = new StringBuilder("Size(").append(" x = ").append(x).append(" y= ").append(y).append(")"); return s.toString(); } public Size divide(Size scaleSize) { int x = this.x / scaleSize.x; int y = this.y / scaleSize.y; if (x * scaleSize.x != this.x || y * scaleSize.y != this.y) throw new RuntimeException(this + "scalesize:" + scaleSize); return new Size(x, y); } public Size subtract(Size size, int append) { int x = this.x - size.x + append; int y = this.y - size.y + append; return new Size(x, y); } } public void initKernel(int frontMapNum) { // int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y; // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, true); } public void initOutputKerkel(int frontMapNum, Size size) { kernelSize = size; // int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y; // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, false); } public void initBias(int frontMapNum) { this.bias = MathUtils.randomArray(outMapNum); } public void initOutmaps(int batchSize) { outmaps = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setMapValue(int mapNo, int mapX, int mapY, double value) { outmaps[recordInBatch][mapNo][mapX][mapY] = value; } static int count = 0; public void setMapValue(int mapNo, double[][] outMatrix) { // Log.i(type.toString()); // Util.printMatrix(outMatrix); outmaps[recordInBatch][mapNo] = outMatrix; } public double[][] getMap(int index) { return outmaps[recordInBatch][index]; } public double[][] getKernel(int i, int j) { return kernel[i][j]; } public void setError(int mapNo, int mapX, int mapY, double value) { errors[recordInBatch][mapNo][mapX][mapY] = value; } public void setError(int mapNo, double[][] matrix) { // Log.i(type.toString()); // Util.printMatrix(matrix); errors[recordInBatch][mapNo] = matrix; } public double[][] getError(int mapNo) { return errors[recordInBatch][mapNo]; } public double[][][][] getErrors() { return errors; } public void initErros(int batchSize) { errors = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setKernel(int lastMapNo, int mapNo, double[][] kernel) { this.kernel[lastMapNo][mapNo] = kernel; } public double getBias(int mapNo) { return bias[mapNo]; } public void setBias(int mapNo, double value) { bias[mapNo] = value; } public double[][][][] getMaps() { return outmaps; } public double[][] getError(int recordId, int mapNo) { return errors[recordId][mapNo]; } public double[][] getMap(int recordId, int mapNo) { return outmaps[recordId][mapNo]; } public int getClassNum() { return classNum; } public double[][][][] getKernel() { return kernel; } }
DeepCompute/cnn
src/main/java/info/hb/cnn/core/Layer.java
2,096
// int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y;
line_comment
nl
package info.hb.cnn.core; import info.hb.cnn.utils.MathUtils; import java.io.Serializable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Layer implements Serializable { private static final long serialVersionUID = -5747622503947497069L; private static Logger logger = LoggerFactory.getLogger(Layer.class); private LayerType type; private int outMapNum; private Size mapSize; private Size kernelSize; private Size scaleSize; private double[][][][] kernel; private double[] bias; private double[][][][] outmaps; private double[][][][] errors; private static int recordInBatch = 0; private int classNum = -1; private Layer() { // } public static void prepareForNewBatch() { recordInBatch = 0; } public static void prepareForNewRecord() { recordInBatch++; } public static Layer buildInputLayer(Size mapSize) { Layer layer = new Layer(); layer.type = LayerType.input; layer.outMapNum = 1; layer.setMapSize(mapSize); return layer; } public static Layer buildConvLayer(int outMapNum, Size kernelSize) { Layer layer = new Layer(); layer.type = LayerType.conv; layer.outMapNum = outMapNum; layer.kernelSize = kernelSize; return layer; } public static Layer buildSampLayer(Size scaleSize) { Layer layer = new Layer(); layer.type = LayerType.samp; layer.scaleSize = scaleSize; return layer; } public static Layer buildOutputLayer(int classNum) { Layer layer = new Layer(); layer.classNum = classNum; layer.type = LayerType.output; layer.mapSize = new Size(1, 1); layer.outMapNum = classNum; // int outMapNum = 1; // while ((1 << outMapNum) < classNum) // outMapNum += 1; // layer.outMapNum = outMapNum; logger.info("outMapNum:{}", layer.outMapNum); return layer; } public Size getMapSize() { return mapSize; } public void setMapSize(Size mapSize) { this.mapSize = mapSize; } public LayerType getType() { return type; } public int getOutMapNum() { return outMapNum; } public void setOutMapNum(int outMapNum) { this.outMapNum = outMapNum; } public Size getKernelSize() { return kernelSize; } public Size getScaleSize() { return scaleSize; } enum LayerType { input, output, conv, samp } public static class Size implements Serializable { private static final long serialVersionUID = -209157832162004118L; public final int x; public final int y; public Size(int x, int y) { this.x = x; this.y = y; } @Override public String toString() { StringBuilder s = new StringBuilder("Size(").append(" x = ").append(x).append(" y= ").append(y).append(")"); return s.toString(); } public Size divide(Size scaleSize) { int x = this.x / scaleSize.x; int y = this.y / scaleSize.y; if (x * scaleSize.x != this.x || y * scaleSize.y != this.y) throw new RuntimeException(this + "scalesize:" + scaleSize); return new Size(x, y); } public Size subtract(Size size, int append) { int x = this.x - size.x + append; int y = this.y - size.y + append; return new Size(x, y); } } public void initKernel(int frontMapNum) { // int fan_out<SUF> // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, true); } public void initOutputKerkel(int frontMapNum, Size size) { kernelSize = size; // int fan_out = getOutMapNum() * kernelSize.x * kernelSize.y; // int fan_in = frontMapNum * kernelSize.x * kernelSize.y; // double factor = 2 * Math.sqrt(6 / (fan_in + fan_out)); this.kernel = new double[frontMapNum][outMapNum][kernelSize.x][kernelSize.y]; for (int i = 0; i < frontMapNum; i++) for (int j = 0; j < outMapNum; j++) kernel[i][j] = MathUtils.randomMatrix(kernelSize.x, kernelSize.y, false); } public void initBias(int frontMapNum) { this.bias = MathUtils.randomArray(outMapNum); } public void initOutmaps(int batchSize) { outmaps = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setMapValue(int mapNo, int mapX, int mapY, double value) { outmaps[recordInBatch][mapNo][mapX][mapY] = value; } static int count = 0; public void setMapValue(int mapNo, double[][] outMatrix) { // Log.i(type.toString()); // Util.printMatrix(outMatrix); outmaps[recordInBatch][mapNo] = outMatrix; } public double[][] getMap(int index) { return outmaps[recordInBatch][index]; } public double[][] getKernel(int i, int j) { return kernel[i][j]; } public void setError(int mapNo, int mapX, int mapY, double value) { errors[recordInBatch][mapNo][mapX][mapY] = value; } public void setError(int mapNo, double[][] matrix) { // Log.i(type.toString()); // Util.printMatrix(matrix); errors[recordInBatch][mapNo] = matrix; } public double[][] getError(int mapNo) { return errors[recordInBatch][mapNo]; } public double[][][][] getErrors() { return errors; } public void initErros(int batchSize) { errors = new double[batchSize][outMapNum][mapSize.x][mapSize.y]; } public void setKernel(int lastMapNo, int mapNo, double[][] kernel) { this.kernel[lastMapNo][mapNo] = kernel; } public double getBias(int mapNo) { return bias[mapNo]; } public void setBias(int mapNo, double value) { bias[mapNo] = value; } public double[][][][] getMaps() { return outmaps; } public double[][] getError(int recordId, int mapNo) { return errors[recordId][mapNo]; } public double[][] getMap(int recordId, int mapNo) { return outmaps[recordId][mapNo]; } public int getClassNum() { return classNum; } public double[][][][] getKernel() { return kernel; } }
False
1,691
20
2,053
24
2,038
23
2,053
24
2,303
24
false
false
false
false
false
true
4,481
67196_10
/** * 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 java.util.Date; import javax.persistence.Column; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import org.codehaus.jackson.annotate.JsonIgnore; import org.hibernate.search.annotations.Field; /** * In OpenMRS, we distinguish between data and metadata within our data model. Metadata represent * system and descriptive data such as data types &mdash; a relationship type or encounter type. * Metadata are generally referenced by clinical data but don't represent patient-specific data * themselves. This provides a default abstract implementation of the OpenmrsMetadata interface * * @since 1.5 * @see OpenmrsMetadata */ @MappedSuperclass public abstract class BaseOpenmrsMetadata extends BaseOpenmrsObject implements OpenmrsMetadata { //***** Properties ***** @Column(name = "name", nullable = false, length = 255) @Field private String name; @Column(name = "description", length = 255) private String description; @ManyToOne(optional = false) @JoinColumn(name = "creator") private User creator; @Column(name = "date_created", nullable = false) private Date dateCreated; @ManyToOne @JoinColumn(name = "changed_by") private User changedBy; @Column(name = "date_changed") private Date dateChanged; @Column(name = "retired", nullable = false) @Field private Boolean retired = Boolean.FALSE; @Column(name = "date_retired") private Date dateRetired; @ManyToOne @JoinColumn(name = "retired_by") private User retiredBy; @Column(name = "retire_reason", length = 255) private String retireReason; //***** Constructors ***** /** * Default Constructor */ public BaseOpenmrsMetadata() { } //***** Property Access ***** /** * @return the name */ @Override public String getName() { return name; } /** * @param name the name to set */ @Override public void setName(String name) { this.name = name; } /** * @return the description */ @Override public String getDescription() { return description; } /** * @param description the description to set */ @Override public void setDescription(String description) { this.description = description; } /** * @see org.openmrs.OpenmrsMetadata#getCreator() */ @Override public User getCreator() { return creator; } /** * @see org.openmrs.OpenmrsMetadata#setCreator(org.openmrs.User) */ @Override public void setCreator(User creator) { this.creator = creator; } /** * @see org.openmrs.OpenmrsMetadata#getDateCreated() */ @Override public Date getDateCreated() { return dateCreated; } /** * @see org.openmrs.OpenmrsMetadata#setDateCreated(java.util.Date) */ @Override public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } /** * @see org.openmrs.OpenmrsMetadata#getChangedBy() * @deprecated as of version 2.2 */ @Override @Deprecated public User getChangedBy() { return changedBy; } /** * @see org.openmrs.OpenmrsMetadata#setChangedBy(User) * @deprecated as of version 2.2 */ @Override @Deprecated public void setChangedBy(User changedBy) { this.changedBy = changedBy; } /** * @see org.openmrs.OpenmrsMetadata#getDateChanged() * @deprecated as of version 2.2 */ @Override @Deprecated public Date getDateChanged() { return dateChanged; } /** * @see org.openmrs.OpenmrsMetadata#setDateChanged(Date) * @deprecated as of version 2.2 */ @Override @Deprecated public void setDateChanged(Date dateChanged) { this.dateChanged = dateChanged; } /** * @deprecated as of 2.0, use {@link #getRetired()} * @see org.openmrs.Retireable#isRetired() */ @Override @Deprecated @JsonIgnore public Boolean isRetired() { return getRetired(); } /** * This method delegates to {@link #isRetired()}. This is only needed for jstl syntax like * ${fieldType.retired} because the return type is a Boolean object instead of a boolean * primitive type. * * @see org.openmrs.Retireable#isRetired() */ @Override public Boolean getRetired() { return retired; } /** * @see org.openmrs.Retireable#setRetired(java.lang.Boolean) */ @Override public void setRetired(Boolean retired) { this.retired = retired; } /** * @see org.openmrs.Retireable#getDateRetired() */ @Override public Date getDateRetired() { return dateRetired; } /** * @see org.openmrs.Retireable#setDateRetired(java.util.Date) */ @Override public void setDateRetired(Date dateRetired) { this.dateRetired = dateRetired; } /** * @see org.openmrs.Retireable#getRetiredBy() */ @Override public User getRetiredBy() { return retiredBy; } /** * @see org.openmrs.Retireable#setRetiredBy(org.openmrs.User) */ @Override public void setRetiredBy(User retiredBy) { this.retiredBy = retiredBy; } /** * @see org.openmrs.Retireable#getRetireReason() */ @Override public String getRetireReason() { return retireReason; } /** * @see org.openmrs.Retireable#setRetireReason(java.lang.String) */ @Override public void setRetireReason(String retireReason) { this.retireReason = retireReason; } }
thegreyd/openmrs-core
api/src/main/java/org/openmrs/BaseOpenmrsMetadata.java
1,983
/** * @see org.openmrs.OpenmrsMetadata#getDateCreated() */
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 java.util.Date; import javax.persistence.Column; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MappedSuperclass; import org.codehaus.jackson.annotate.JsonIgnore; import org.hibernate.search.annotations.Field; /** * In OpenMRS, we distinguish between data and metadata within our data model. Metadata represent * system and descriptive data such as data types &mdash; a relationship type or encounter type. * Metadata are generally referenced by clinical data but don't represent patient-specific data * themselves. This provides a default abstract implementation of the OpenmrsMetadata interface * * @since 1.5 * @see OpenmrsMetadata */ @MappedSuperclass public abstract class BaseOpenmrsMetadata extends BaseOpenmrsObject implements OpenmrsMetadata { //***** Properties ***** @Column(name = "name", nullable = false, length = 255) @Field private String name; @Column(name = "description", length = 255) private String description; @ManyToOne(optional = false) @JoinColumn(name = "creator") private User creator; @Column(name = "date_created", nullable = false) private Date dateCreated; @ManyToOne @JoinColumn(name = "changed_by") private User changedBy; @Column(name = "date_changed") private Date dateChanged; @Column(name = "retired", nullable = false) @Field private Boolean retired = Boolean.FALSE; @Column(name = "date_retired") private Date dateRetired; @ManyToOne @JoinColumn(name = "retired_by") private User retiredBy; @Column(name = "retire_reason", length = 255) private String retireReason; //***** Constructors ***** /** * Default Constructor */ public BaseOpenmrsMetadata() { } //***** Property Access ***** /** * @return the name */ @Override public String getName() { return name; } /** * @param name the name to set */ @Override public void setName(String name) { this.name = name; } /** * @return the description */ @Override public String getDescription() { return description; } /** * @param description the description to set */ @Override public void setDescription(String description) { this.description = description; } /** * @see org.openmrs.OpenmrsMetadata#getCreator() */ @Override public User getCreator() { return creator; } /** * @see org.openmrs.OpenmrsMetadata#setCreator(org.openmrs.User) */ @Override public void setCreator(User creator) { this.creator = creator; } /** * @see org.openmrs.OpenmrsMetadata#getDateCreated() <SUF>*/ @Override public Date getDateCreated() { return dateCreated; } /** * @see org.openmrs.OpenmrsMetadata#setDateCreated(java.util.Date) */ @Override public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } /** * @see org.openmrs.OpenmrsMetadata#getChangedBy() * @deprecated as of version 2.2 */ @Override @Deprecated public User getChangedBy() { return changedBy; } /** * @see org.openmrs.OpenmrsMetadata#setChangedBy(User) * @deprecated as of version 2.2 */ @Override @Deprecated public void setChangedBy(User changedBy) { this.changedBy = changedBy; } /** * @see org.openmrs.OpenmrsMetadata#getDateChanged() * @deprecated as of version 2.2 */ @Override @Deprecated public Date getDateChanged() { return dateChanged; } /** * @see org.openmrs.OpenmrsMetadata#setDateChanged(Date) * @deprecated as of version 2.2 */ @Override @Deprecated public void setDateChanged(Date dateChanged) { this.dateChanged = dateChanged; } /** * @deprecated as of 2.0, use {@link #getRetired()} * @see org.openmrs.Retireable#isRetired() */ @Override @Deprecated @JsonIgnore public Boolean isRetired() { return getRetired(); } /** * This method delegates to {@link #isRetired()}. This is only needed for jstl syntax like * ${fieldType.retired} because the return type is a Boolean object instead of a boolean * primitive type. * * @see org.openmrs.Retireable#isRetired() */ @Override public Boolean getRetired() { return retired; } /** * @see org.openmrs.Retireable#setRetired(java.lang.Boolean) */ @Override public void setRetired(Boolean retired) { this.retired = retired; } /** * @see org.openmrs.Retireable#getDateRetired() */ @Override public Date getDateRetired() { return dateRetired; } /** * @see org.openmrs.Retireable#setDateRetired(java.util.Date) */ @Override public void setDateRetired(Date dateRetired) { this.dateRetired = dateRetired; } /** * @see org.openmrs.Retireable#getRetiredBy() */ @Override public User getRetiredBy() { return retiredBy; } /** * @see org.openmrs.Retireable#setRetiredBy(org.openmrs.User) */ @Override public void setRetiredBy(User retiredBy) { this.retiredBy = retiredBy; } /** * @see org.openmrs.Retireable#getRetireReason() */ @Override public String getRetireReason() { return retireReason; } /** * @see org.openmrs.Retireable#setRetireReason(java.lang.String) */ @Override public void setRetireReason(String retireReason) { this.retireReason = retireReason; } }
False
1,511
19
1,793
21
1,818
21
1,793
21
2,026
24
false
false
false
false
false
true
50
21118_0
package com.example.midasvg.pilgrim; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { private DrawerLayout nDrawerLayout; private NavigationView navigationView; private ActionBarDrawerToggle nToggle; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Pilgrim </font>")); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646"))); //De button wordt ge-enabled op de Action Bar nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); navigationView = (NavigationView) findViewById(R.id.navView); nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close); nDrawerLayout.addDrawerListener(nToggle); nToggle.syncState(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { UserMenuSelector(item); return false; } }); mAuth = FirebaseAuth.getInstance(); //Button staat nu aan & kan gebruikt worden. //Het is de bedoeling dat de button disabled wordt, tot de speler bij het startpunt komt. final Button startButton = (Button) findViewById(R.id.bttnStart); startButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent(MainActivity.this, GameActivity.class); startActivity(intent); } }); final Button accButton = (Button) findViewById(R.id.imageAcc); accButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intent); } }); } //Nu kan er op de button gedrukt worden @Override public boolean onOptionsItemSelected(MenuItem item){ if (nToggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } private void UserMenuSelector(MenuItem item){ switch (item.getItemId()){ case R.id.nav_collections: Intent intentCollection = new Intent(MainActivity.this, CollectionActivity.class); startActivity(intentCollection); break; case R.id.nav_game: Intent intentGame = new Intent(MainActivity.this, MainActivity.class); startActivity(intentGame); break; case R.id.nav_leaderboard: Intent intentLeaderboard = new Intent(MainActivity.this, LeaderboardActivity.class); startActivity(intentLeaderboard); break; case R.id.nav_profile: Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intentProfile); break; case R.id.nav_guide: Intent intentGuide = new Intent(MainActivity.this, GuideActivity.class); startActivity(intentGuide); break; case R.id.nav_about: Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class); startActivity(intentAbout); break; case R.id.nav_logout: mAuth.signOut(); Toast.makeText(MainActivity.this, "Logging out...", Toast.LENGTH_SHORT).show(); Intent logOut = new Intent(MainActivity.this, LoginActivity.class); startActivity(logOut); break; } } }
AP-IT-GH/CA1819-Pilgrim
src/AndroidApp/app/src/main/java/com/example/midasvg/pilgrim/MainActivity.java
1,268
//De button wordt ge-enabled op de Action Bar
line_comment
nl
package com.example.midasvg.pilgrim; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Html; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { private DrawerLayout nDrawerLayout; private NavigationView navigationView; private ActionBarDrawerToggle nToggle; private FirebaseAuth mAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getSupportActionBar().setTitle(Html.fromHtml("<font color='#ffffff'>Pilgrim </font>")); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#464646"))); //De button<SUF> nDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout); navigationView = (NavigationView) findViewById(R.id.navView); nToggle = new ActionBarDrawerToggle(this, nDrawerLayout, R.string.open, R.string.close); nDrawerLayout.addDrawerListener(nToggle); nToggle.syncState(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { UserMenuSelector(item); return false; } }); mAuth = FirebaseAuth.getInstance(); //Button staat nu aan & kan gebruikt worden. //Het is de bedoeling dat de button disabled wordt, tot de speler bij het startpunt komt. final Button startButton = (Button) findViewById(R.id.bttnStart); startButton.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Intent intent = new Intent(MainActivity.this, GameActivity.class); startActivity(intent); } }); final Button accButton = (Button) findViewById(R.id.imageAcc); accButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intent); } }); } //Nu kan er op de button gedrukt worden @Override public boolean onOptionsItemSelected(MenuItem item){ if (nToggle.onOptionsItemSelected(item)){ return true; } return super.onOptionsItemSelected(item); } private void UserMenuSelector(MenuItem item){ switch (item.getItemId()){ case R.id.nav_collections: Intent intentCollection = new Intent(MainActivity.this, CollectionActivity.class); startActivity(intentCollection); break; case R.id.nav_game: Intent intentGame = new Intent(MainActivity.this, MainActivity.class); startActivity(intentGame); break; case R.id.nav_leaderboard: Intent intentLeaderboard = new Intent(MainActivity.this, LeaderboardActivity.class); startActivity(intentLeaderboard); break; case R.id.nav_profile: Intent intentProfile = new Intent(MainActivity.this, ProfileActivity.class); startActivity(intentProfile); break; case R.id.nav_guide: Intent intentGuide = new Intent(MainActivity.this, GuideActivity.class); startActivity(intentGuide); break; case R.id.nav_about: Intent intentAbout = new Intent(MainActivity.this, AboutActivity.class); startActivity(intentAbout); break; case R.id.nav_logout: mAuth.signOut(); Toast.makeText(MainActivity.this, "Logging out...", Toast.LENGTH_SHORT).show(); Intent logOut = new Intent(MainActivity.this, LoginActivity.class); startActivity(logOut); break; } } }
True
778
10
992
11
1,036
11
994
11
1,149
11
false
false
false
false
false
true
3,142
173913_0
package com.jme3.gde.welcome.rss; /** * * @author Lars Vogel, normenhansen */ import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.List; import javax.swing.text.BadLocationException; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import org.openide.util.Exceptions; public class RssFeedParser { static final String TITLE = "title"; static final String DESCRIPTION = "description"; static final String CHANNEL = "channel"; static final String LANGUAGE = "language"; static final String COPYRIGHT = "copyright"; static final String LINK = "link"; static final String AUTHOR = "author"; static final String ITEM = "item"; static final String PUB_DATE = "pubDate"; static final String GUID = "guid"; private final URL url; private final HTMLEditorKit ekit; private final HTMLDocument doc; public RssFeedParser(String feedUrl) { try { this.url = URI.create(feedUrl).toURL(); ekit = new HTMLEditorKit(); doc = new HTMLDocument(); } catch (Exception e) { throw new RuntimeException(e); } } public HTMLDocument getDocument() { return doc; } public HTMLEditorKit getEditorKit() { return ekit; } public void updateFeed() { Thread t = new Thread(new Runnable() { public void run() { try { final Feed feed = readFeed(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { List<FeedMessage> msgs = feed.getMessages(); try { doc.remove(0, doc.getLength()); ekit.insertHTML(doc, doc.getLength(), "<html>" + "<head>" + "</head>" + "<body>", 0, 0, null); // ekit.insertHTML(doc, doc.getLength(), // "<h1>" // + "Latest News" // + "</h1>", // 0, // 0, // null); for (FeedMessage feedMessage : msgs) { ekit.insertHTML(doc, doc.getLength(), "<h3><a href='" + feedMessage.getLink() + "'>" + feedMessage.getTitle() + "</a></h3>", 0, 0, null); // ekit.insertHTML(doc, doc.getLength(), // "<p>" // + feedMessage.getDescription() // + "</p>", // 0, // 0, // null); ekit.insertHTML(doc, doc.getLength(), "<br/>", 0, 0, null); } ekit.insertHTML(doc, doc.getLength(), "</body>" + "</html>", 0, 0, null); doc.insertString(0, "", null); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } }); t.start(); } @SuppressWarnings("null") public Feed readFeed() { Feed feed = null; try { boolean isFeedHeader = true; // Set header values intial to the empty string String description = ""; String title = ""; String link = ""; String language = ""; String copyright = ""; String author = ""; String pubdate = ""; String guid = ""; // First create a new XMLInputFactory XMLInputFactory inputFactory = XMLInputFactory.newInstance(); // Setup a new eventReader InputStream in = read(); XMLEventReader eventReader = inputFactory.createXMLEventReader(in); // Read the XML document while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(ITEM)) { if (isFeedHeader) { isFeedHeader = false; feed = new Feed(title, link, description, language, copyright, pubdate); } event = eventReader.nextEvent(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(TITLE)) { event = eventReader.nextEvent(); title = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(DESCRIPTION)) { event = eventReader.nextEvent(); if(event.getClass().getName().equals("com.ctc.wstx.evt.CompactStartElement")){ description = event.asStartElement().asCharacters().getData(); }else{ description = event.asCharacters().getData(); } continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(LINK)) { event = eventReader.nextEvent(); //System.out.println("Teh hack: " + event.toString() + event.getClass()); Object chars = event.asCharacters(); if (chars instanceof javax.xml.stream.events.Characters) { javax.xml.stream.events.Characters jchars = (javax.xml.stream.events.Characters) chars; link = jchars.getData(); } else { link = event.asCharacters().getData(); } continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(GUID)) { event = eventReader.nextEvent(); guid = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(LANGUAGE)) { event = eventReader.nextEvent(); language = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(AUTHOR)) { event = eventReader.nextEvent(); author = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(PUB_DATE)) { event = eventReader.nextEvent(); pubdate = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(COPYRIGHT)) { event = eventReader.nextEvent(); copyright = event.asCharacters().getData(); continue; } } else if (event.isEndElement()) { if (event.asEndElement().getName().getLocalPart() != null && event.asEndElement().getName().getLocalPart().equals(ITEM)) { FeedMessage message = new FeedMessage(); message.setAuthor(author); message.setDescription(description); message.setGuid(guid); message.setLink(link); message.setTitle(title); feed.getMessages().add(message); event = eventReader.nextEvent(); continue; } } } } catch (XMLStreamException e) { throw new RuntimeException(e); } return feed; } private InputStream read() { try { return url.openStream(); } catch (IOException e) { throw new RuntimeException(e); } } }
jMonkeyEngine/sdk
jme3-welcome-screen/src/com/jme3/gde/welcome/rss/RssFeedParser.java
2,457
/** * * @author Lars Vogel, normenhansen */
block_comment
nl
package com.jme3.gde.welcome.rss; /** * * @author Lars Vogel,<SUF>*/ import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.List; import javax.swing.text.BadLocationException; import javax.swing.text.html.HTMLDocument; import javax.swing.text.html.HTMLEditorKit; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import org.openide.util.Exceptions; public class RssFeedParser { static final String TITLE = "title"; static final String DESCRIPTION = "description"; static final String CHANNEL = "channel"; static final String LANGUAGE = "language"; static final String COPYRIGHT = "copyright"; static final String LINK = "link"; static final String AUTHOR = "author"; static final String ITEM = "item"; static final String PUB_DATE = "pubDate"; static final String GUID = "guid"; private final URL url; private final HTMLEditorKit ekit; private final HTMLDocument doc; public RssFeedParser(String feedUrl) { try { this.url = URI.create(feedUrl).toURL(); ekit = new HTMLEditorKit(); doc = new HTMLDocument(); } catch (Exception e) { throw new RuntimeException(e); } } public HTMLDocument getDocument() { return doc; } public HTMLEditorKit getEditorKit() { return ekit; } public void updateFeed() { Thread t = new Thread(new Runnable() { public void run() { try { final Feed feed = readFeed(); java.awt.EventQueue.invokeLater(new Runnable() { public void run() { List<FeedMessage> msgs = feed.getMessages(); try { doc.remove(0, doc.getLength()); ekit.insertHTML(doc, doc.getLength(), "<html>" + "<head>" + "</head>" + "<body>", 0, 0, null); // ekit.insertHTML(doc, doc.getLength(), // "<h1>" // + "Latest News" // + "</h1>", // 0, // 0, // null); for (FeedMessage feedMessage : msgs) { ekit.insertHTML(doc, doc.getLength(), "<h3><a href='" + feedMessage.getLink() + "'>" + feedMessage.getTitle() + "</a></h3>", 0, 0, null); // ekit.insertHTML(doc, doc.getLength(), // "<p>" // + feedMessage.getDescription() // + "</p>", // 0, // 0, // null); ekit.insertHTML(doc, doc.getLength(), "<br/>", 0, 0, null); } ekit.insertHTML(doc, doc.getLength(), "</body>" + "</html>", 0, 0, null); doc.insertString(0, "", null); } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } } }); } catch (Exception ex) { Exceptions.printStackTrace(ex); } } }); t.start(); } @SuppressWarnings("null") public Feed readFeed() { Feed feed = null; try { boolean isFeedHeader = true; // Set header values intial to the empty string String description = ""; String title = ""; String link = ""; String language = ""; String copyright = ""; String author = ""; String pubdate = ""; String guid = ""; // First create a new XMLInputFactory XMLInputFactory inputFactory = XMLInputFactory.newInstance(); // Setup a new eventReader InputStream in = read(); XMLEventReader eventReader = inputFactory.createXMLEventReader(in); // Read the XML document while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(ITEM)) { if (isFeedHeader) { isFeedHeader = false; feed = new Feed(title, link, description, language, copyright, pubdate); } event = eventReader.nextEvent(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(TITLE)) { event = eventReader.nextEvent(); title = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(DESCRIPTION)) { event = eventReader.nextEvent(); if(event.getClass().getName().equals("com.ctc.wstx.evt.CompactStartElement")){ description = event.asStartElement().asCharacters().getData(); }else{ description = event.asCharacters().getData(); } continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(LINK)) { event = eventReader.nextEvent(); //System.out.println("Teh hack: " + event.toString() + event.getClass()); Object chars = event.asCharacters(); if (chars instanceof javax.xml.stream.events.Characters) { javax.xml.stream.events.Characters jchars = (javax.xml.stream.events.Characters) chars; link = jchars.getData(); } else { link = event.asCharacters().getData(); } continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(GUID)) { event = eventReader.nextEvent(); guid = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(LANGUAGE)) { event = eventReader.nextEvent(); language = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(AUTHOR)) { event = eventReader.nextEvent(); author = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(PUB_DATE)) { event = eventReader.nextEvent(); pubdate = event.asCharacters().getData(); continue; } if (event.asStartElement().getName().getLocalPart() != null && event.asStartElement().getName().getLocalPart().equals(COPYRIGHT)) { event = eventReader.nextEvent(); copyright = event.asCharacters().getData(); continue; } } else if (event.isEndElement()) { if (event.asEndElement().getName().getLocalPart() != null && event.asEndElement().getName().getLocalPart().equals(ITEM)) { FeedMessage message = new FeedMessage(); message.setAuthor(author); message.setDescription(description); message.setGuid(guid); message.setLink(link); message.setTitle(title); feed.getMessages().add(message); event = eventReader.nextEvent(); continue; } } } } catch (XMLStreamException e) { throw new RuntimeException(e); } return feed; } private InputStream read() { try { return url.openStream(); } catch (IOException e) { throw new RuntimeException(e); } } }
False
1,680
14
1,872
18
2,086
16
1,872
18
2,395
17
false
false
false
false
false
true
3,722
203416_0
package com.dram; import io.smallrye.config.ConfigMapping; import io.smallrye.config.WithName; /** * webhook配置 * * @author dragon * @date 2021/12/29 */ @ConfigMapping(prefix = "webhook") public interface WebhookConfig { /** * 飞书web hook 完整 url * * https://open.feishu.cn/open-apis/bot/v2/hook/aaaaaaa-aaaa-aaaa-aaaa-aaaaaaaa * * @return {@link String} */ @WithName("feishu.uri") String feishuUrl(); }
moxiaolong/feishu-webhook-adapter
src/main/java/com/dram/WebhookConfig.java
167
/** * webhook配置 * * @author dragon * @date 2021/12/29 */
block_comment
nl
package com.dram; import io.smallrye.config.ConfigMapping; import io.smallrye.config.WithName; /** * webhook配置 *<SUF>*/ @ConfigMapping(prefix = "webhook") public interface WebhookConfig { /** * 飞书web hook 完整 url * * https://open.feishu.cn/open-apis/bot/v2/hook/aaaaaaa-aaaa-aaaa-aaaa-aaaaaaaa * * @return {@link String} */ @WithName("feishu.uri") String feishuUrl(); }
False
142
27
161
30
159
29
161
30
183
32
false
false
false
false
false
true
4,273
35783_7
package nl.thuis.sdm.java8; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; public class StreamTest { public static void main(String[] args) { // Tweede commit // Derde commit // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(new FileFilter() { // // @Override // public boolean accept(File f) { // return f.isDirectory(); // } // }); // for (File file : files) { // System.out.println(file.getName()); // } // FileFilter ff = (File f) -> f.isDirectory(); // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(ff); // for (File file : files) { // System.out.println(file.getName()); // } // Commit van GitHub List<String> strings = new ArrayList<>(); strings.add("Een"); strings.add("Twee"); strings.add("Drie"); strings.add("Vier"); strings.add("Vijf"); new StringPrinter().print2(strings, s -> s.length()<4); } }
sdemul/Speeltuin
src/main/java/nl/thuis/sdm/java8/StreamTest.java
347
// Commit van GitHub
line_comment
nl
package nl.thuis.sdm.java8; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.List; public class StreamTest { public static void main(String[] args) { // Tweede commit // Derde commit // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(new FileFilter() { // // @Override // public boolean accept(File f) { // return f.isDirectory(); // } // }); // for (File file : files) { // System.out.println(file.getName()); // } // FileFilter ff = (File f) -> f.isDirectory(); // File[] files = new File("/Users/sjaakdemul/Pictures").listFiles(ff); // for (File file : files) { // System.out.println(file.getName()); // } // Commit van<SUF> List<String> strings = new ArrayList<>(); strings.add("Een"); strings.add("Twee"); strings.add("Drie"); strings.add("Vier"); strings.add("Vijf"); new StringPrinter().print2(strings, s -> s.length()<4); } }
False
272
4
346
4
325
4
346
4
384
5
false
false
false
false
false
true
558
11601_0
package agent; import lejos.nxt.NXTRegulatedMotor; import robotica.SimState; import standard.Agent; public class Customer extends Agent { private long previousTime; private long currentTime; private long timeToWait = 0; private CustomerBehavior behavior; private boolean rotating = false; private NXTRegulatedMotor motor; public Customer(NXTRegulatedMotor motor, String name) { super(name, new SimState("IDLE")); this.behavior = new CustomerBehavior(4); resetTime(); this.motor = motor; motor.resetTachoCount(); } public void reset() { resetTime(); resetRotation(); this.setState(new SimState("IDLE")); this.setChanged(); } @Override public void update() { switch (currentState().name()) { case "IDLE": idle(); break; case "WBESTELLEN": wBestellen(); break; case "WETEN": wEten(); break; case "ETEN": eten(); break; case "WBETALEN": wBetalen(); break; } this.updateState(); notifyObservers(); } private long timePast() { currentTime = System.currentTimeMillis(); long timePast = currentTime - previousTime; previousTime = currentTime; return timePast; } private boolean resetTimeToWait() { if (timeToWait <= 0) { timeToWait = 0; return true; } else return false; } private void resetTime() { currentTime = System.currentTimeMillis(); previousTime = currentTime; timeToWait = 0; } private void idle() { resetRotation(); if (resetTimeToWait()) timeToWait = behavior.idle(); timeToWait -= timePast(); System.out.println("IDLE"); motor.setSpeed(720); motor.rotateTo(0); if (timeToWait < 0) { this.setState(new SimState("WBESTELLEN")); setChanged(); resetTime(); } } private void wBestellen() { resetRotation(); motor.setSpeed(720); motor.rotateTo(90); resetTime(); } private void wEten() { resetRotation(); motor.setSpeed(720); motor.rotateTo(180); resetTime(); } private void eten() { if (resetTimeToWait()) timeToWait = behavior.eten(); timeToWait -= timePast(); System.out.println("ETEN"); if (timeToWait < 0) { this.setState(new SimState("WBETALEN")); setChanged(); resetTime(); } rotating = true; motor.setSpeed(300); motor.forward(); } private void wBetalen() { resetRotation(); motor.setSpeed(720); motor.setSpeed(720); motor.rotateTo(270); } private void resetRotation() { if (rotating) { int lol = motor.getTachoCount() / 360; motor.rotateTo(lol * 360); motor.resetTachoCount(); rotating = false; } } public void processCompletedTask(String task) { System.out.println(task); switch (task) { case "BESTELLING_OPGENOMEN": if (this.currentState().name().equals("WBESTELLEN")) { this.setState(new SimState("WETEN")); this.setChanged(); } break; case "ETEN_BEZORGD": if (this.currentState().name().equals("WETEN")) { this.setState(new SimState("ETEN")); this.setChanged(); } break; case "BETALING_AFGEROND": if (this.currentState().name().equals("WBETALEN")) { motor.rotateTo(0); this.setState(new SimState("STOP")); this.setChanged(); } break; } } } /* * 5 states: * * -idle"IDLE" Niks boven. -Wachten op bestellen: "WBESTELLEN" Rood boven. * -Wachten op eten: "WETEN" Blauw boven. -Eten: "ETEN" Motor draait rond. * -Betalen: "WBETALEN" Zwart boven. */
GSamuel/Robotica-2-2013
Robotica 2 NXT/src/agent/Customer.java
1,308
/* * 5 states: * * -idle"IDLE" Niks boven. -Wachten op bestellen: "WBESTELLEN" Rood boven. * -Wachten op eten: "WETEN" Blauw boven. -Eten: "ETEN" Motor draait rond. * -Betalen: "WBETALEN" Zwart boven. */
block_comment
nl
package agent; import lejos.nxt.NXTRegulatedMotor; import robotica.SimState; import standard.Agent; public class Customer extends Agent { private long previousTime; private long currentTime; private long timeToWait = 0; private CustomerBehavior behavior; private boolean rotating = false; private NXTRegulatedMotor motor; public Customer(NXTRegulatedMotor motor, String name) { super(name, new SimState("IDLE")); this.behavior = new CustomerBehavior(4); resetTime(); this.motor = motor; motor.resetTachoCount(); } public void reset() { resetTime(); resetRotation(); this.setState(new SimState("IDLE")); this.setChanged(); } @Override public void update() { switch (currentState().name()) { case "IDLE": idle(); break; case "WBESTELLEN": wBestellen(); break; case "WETEN": wEten(); break; case "ETEN": eten(); break; case "WBETALEN": wBetalen(); break; } this.updateState(); notifyObservers(); } private long timePast() { currentTime = System.currentTimeMillis(); long timePast = currentTime - previousTime; previousTime = currentTime; return timePast; } private boolean resetTimeToWait() { if (timeToWait <= 0) { timeToWait = 0; return true; } else return false; } private void resetTime() { currentTime = System.currentTimeMillis(); previousTime = currentTime; timeToWait = 0; } private void idle() { resetRotation(); if (resetTimeToWait()) timeToWait = behavior.idle(); timeToWait -= timePast(); System.out.println("IDLE"); motor.setSpeed(720); motor.rotateTo(0); if (timeToWait < 0) { this.setState(new SimState("WBESTELLEN")); setChanged(); resetTime(); } } private void wBestellen() { resetRotation(); motor.setSpeed(720); motor.rotateTo(90); resetTime(); } private void wEten() { resetRotation(); motor.setSpeed(720); motor.rotateTo(180); resetTime(); } private void eten() { if (resetTimeToWait()) timeToWait = behavior.eten(); timeToWait -= timePast(); System.out.println("ETEN"); if (timeToWait < 0) { this.setState(new SimState("WBETALEN")); setChanged(); resetTime(); } rotating = true; motor.setSpeed(300); motor.forward(); } private void wBetalen() { resetRotation(); motor.setSpeed(720); motor.setSpeed(720); motor.rotateTo(270); } private void resetRotation() { if (rotating) { int lol = motor.getTachoCount() / 360; motor.rotateTo(lol * 360); motor.resetTachoCount(); rotating = false; } } public void processCompletedTask(String task) { System.out.println(task); switch (task) { case "BESTELLING_OPGENOMEN": if (this.currentState().name().equals("WBESTELLEN")) { this.setState(new SimState("WETEN")); this.setChanged(); } break; case "ETEN_BEZORGD": if (this.currentState().name().equals("WETEN")) { this.setState(new SimState("ETEN")); this.setChanged(); } break; case "BETALING_AFGEROND": if (this.currentState().name().equals("WBETALEN")) { motor.rotateTo(0); this.setState(new SimState("STOP")); this.setChanged(); } break; } } } /* * 5 states: <SUF>*/
True
1,031
86
1,247
101
1,206
83
1,247
101
1,511
100
false
false
false
false
false
true
726
75735_0
package com.github.idragonfire.DragonAntiPvPLeaver.npclib; import net.minecraft.server.v1_7_R4.EntityPlayer; import net.minecraft.server.v1_7_R4.EnumGamemode; import net.minecraft.server.v1_7_R4.PlayerInteractManager; import net.minecraft.server.v1_7_R4.World; import net.minecraft.server.v1_7_R4.WorldServer; import net.minecraft.util.com.mojang.authlib.GameProfile; import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity; /** * Bukkit: * "https://github.com/Bukkit/CraftBukkit/blob/master/src/main/java/net/minecraft/server/EntityPlayer.java" * caliog: * "https://github.com/caliog/NPCLib/blob/master/com/sharesc/caliog/npclib/NPCEntity.java" * Citiziens: * "https://github.com/CitizensDev/Citizens2/blob/master/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java" * Combat-Tag: * "https://github.com/cheddar262/Combat-Tag/blob/master/CombatTag/com/topcat/npclib/nms/NPCEntity.java" * Top-Cat: * "https://github.com/Top-Cat/NPCLib/blob/master/src/main/java/com/topcat/npclib/nms/NPCEntity.java" * lennis0012: * "https://github.com/lenis0012/NPCFactory/blob/master/src/main/java/com/lenis0012/bukkit/npc/NPCEntity.java" */ public class NPCEntity extends EntityPlayer { public NPCEntity(World world, GameProfile g, PlayerInteractManager itemInWorldManager) { super(world.getServer().getServer(), (WorldServer) world, g, itemInWorldManager); itemInWorldManager.b(EnumGamemode.SURVIVAL); this.playerConnection = new NPCNetHandler( world.getServer().getServer(), this); } public void setBukkitEntity(org.bukkit.entity.Entity entity) { bukkitEntity = (CraftEntity) entity; } }
IDragonfire/DragonAntiPvPLeaver
src/com/github/idragonfire/DragonAntiPvPLeaver/npclib/NPCEntity.java
649
/** * Bukkit: * "https://github.com/Bukkit/CraftBukkit/blob/master/src/main/java/net/minecraft/server/EntityPlayer.java" * caliog: * "https://github.com/caliog/NPCLib/blob/master/com/sharesc/caliog/npclib/NPCEntity.java" * Citiziens: * "https://github.com/CitizensDev/Citizens2/blob/master/src/main/java/net/citizensnpcs/npc/entity/EntityHumanNPC.java" * Combat-Tag: * "https://github.com/cheddar262/Combat-Tag/blob/master/CombatTag/com/topcat/npclib/nms/NPCEntity.java" * Top-Cat: * "https://github.com/Top-Cat/NPCLib/blob/master/src/main/java/com/topcat/npclib/nms/NPCEntity.java" * lennis0012: * "https://github.com/lenis0012/NPCFactory/blob/master/src/main/java/com/lenis0012/bukkit/npc/NPCEntity.java" */
block_comment
nl
package com.github.idragonfire.DragonAntiPvPLeaver.npclib; import net.minecraft.server.v1_7_R4.EntityPlayer; import net.minecraft.server.v1_7_R4.EnumGamemode; import net.minecraft.server.v1_7_R4.PlayerInteractManager; import net.minecraft.server.v1_7_R4.World; import net.minecraft.server.v1_7_R4.WorldServer; import net.minecraft.util.com.mojang.authlib.GameProfile; import org.bukkit.craftbukkit.v1_7_R4.entity.CraftEntity; /** * Bukkit: *<SUF>*/ public class NPCEntity extends EntityPlayer { public NPCEntity(World world, GameProfile g, PlayerInteractManager itemInWorldManager) { super(world.getServer().getServer(), (WorldServer) world, g, itemInWorldManager); itemInWorldManager.b(EnumGamemode.SURVIVAL); this.playerConnection = new NPCNetHandler( world.getServer().getServer(), this); } public void setBukkitEntity(org.bukkit.entity.Entity entity) { bukkitEntity = (CraftEntity) entity; } }
False
465
234
598
298
574
282
598
298
676
324
true
true
true
true
true
false
3,743
52485_8
/** * TINPRO04-3 Les 7-HW // Circular Doubly Linked List, non-generic * 20240217 // m.skelo@hr.nl * */ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class AppCircular { public static void main(String[] args) { // Lees ./input in zoals behandeld in Les 6: File I/O String input = ""; try { input = Files.readString(Paths.get("./input")); } catch ( IOException e ) { e.printStackTrace(); } // Split het bestand op in een array van woorden (String) String splitString[] = input.split(" "); // Stop alle woorden in de LinkedList, achter elkaar. LinkedList list = new LinkedList(); for (String str : splitString) { list.push(str); } // Tests list.print(); list.pop("actually"); list.print(); list.pop(2); list.print(); } } /** * Grote verschil is de toevoeging van de nieuwe field: private Node previous (en bijbehorende get/set-methods). * Dat vergt ingrijpende aanpassingen aan je LinkedList methods. * */ class Node { // Fields: private Node previous; private Node next; private String value; // Constructor(s): public Node(String value) { this.value = value; } // Get/set methods: public Node getNext() { return this.next; } public void setNext(Node next) { this.next = next; } public Node getPrevious() { return this.previous; } public void setPrevious(Node previous) { this.previous = previous; } public String getValue() { return this.value; } // Other methods (n/a) } /** * Merk op dat de enige aanpassing ten opzichte van de "gewone" Doubly Linked List * is dat in alle while-loops de conditie: * (current.getNext() != null) * is vervangen door: * (!current.getNext().equals(this.head)) * */ class LinkedList { // Fields: (Belangrijk: Nieuwe field `Node tail` // Helpt bij het circulair maken van je lijst) private Node head; private Node tail; // Constructors (n/a) // Get/set methods (n/a) // Other methods: public void push(String value) { Node newNode = new Node(value); if (this.head == null && this.tail == null) { this.head = newNode; this.tail = newNode; } else { Node current = this.head; while (!current.getNext().equals(this.head)) { current = current.getNext(); } current.setNext(newNode); current.getNext().setPrevious(current); // Staar hier even naar. this.tail = current.getNext(); // Of: this.tail = newNode } // BONUS: Maak de lijst circulair! // Dit kun je buiten de if/else laten, omdat je dit in beide gevallen hetzelfde zou doen this.tail.setNext(this.head); this.head.setPrevious(this.tail); } public String pop(String value) { Node current = this.head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen, anders kan de GC z'n werk niet doen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } current = current.getNext(); } return "Not found"; } public String pop(int index) { int currentindex = 0; Node current = head; while (currentindex != index && !current.getNext().equals(this.head)) { if (currentindex == index-1) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } currentindex++; current = current.getNext(); } return "Not found"; } public String peek(String value) { Node current = head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { return current.getNext().getValue(); } current = current.getNext(); } return "Not found"; } public void print() { Node current = this.head; do { System.out.print(current.getValue()+" "); current = current.getNext(); } while (!current.equals(this.head)); System.out.println(); } }
mskelo/progdemocode
java3/7-huiswerk/Circular Doubly LL/AppCircular.java
1,562
// Helpt bij het circulair maken van je lijst)
line_comment
nl
/** * TINPRO04-3 Les 7-HW // Circular Doubly Linked List, non-generic * 20240217 // m.skelo@hr.nl * */ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class AppCircular { public static void main(String[] args) { // Lees ./input in zoals behandeld in Les 6: File I/O String input = ""; try { input = Files.readString(Paths.get("./input")); } catch ( IOException e ) { e.printStackTrace(); } // Split het bestand op in een array van woorden (String) String splitString[] = input.split(" "); // Stop alle woorden in de LinkedList, achter elkaar. LinkedList list = new LinkedList(); for (String str : splitString) { list.push(str); } // Tests list.print(); list.pop("actually"); list.print(); list.pop(2); list.print(); } } /** * Grote verschil is de toevoeging van de nieuwe field: private Node previous (en bijbehorende get/set-methods). * Dat vergt ingrijpende aanpassingen aan je LinkedList methods. * */ class Node { // Fields: private Node previous; private Node next; private String value; // Constructor(s): public Node(String value) { this.value = value; } // Get/set methods: public Node getNext() { return this.next; } public void setNext(Node next) { this.next = next; } public Node getPrevious() { return this.previous; } public void setPrevious(Node previous) { this.previous = previous; } public String getValue() { return this.value; } // Other methods (n/a) } /** * Merk op dat de enige aanpassing ten opzichte van de "gewone" Doubly Linked List * is dat in alle while-loops de conditie: * (current.getNext() != null) * is vervangen door: * (!current.getNext().equals(this.head)) * */ class LinkedList { // Fields: (Belangrijk: Nieuwe field `Node tail` // Helpt bij<SUF> private Node head; private Node tail; // Constructors (n/a) // Get/set methods (n/a) // Other methods: public void push(String value) { Node newNode = new Node(value); if (this.head == null && this.tail == null) { this.head = newNode; this.tail = newNode; } else { Node current = this.head; while (!current.getNext().equals(this.head)) { current = current.getNext(); } current.setNext(newNode); current.getNext().setPrevious(current); // Staar hier even naar. this.tail = current.getNext(); // Of: this.tail = newNode } // BONUS: Maak de lijst circulair! // Dit kun je buiten de if/else laten, omdat je dit in beide gevallen hetzelfde zou doen this.tail.setNext(this.head); this.head.setPrevious(this.tail); } public String pop(String value) { Node current = this.head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen, anders kan de GC z'n werk niet doen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } current = current.getNext(); } return "Not found"; } public String pop(int index) { int currentindex = 0; Node current = head; while (currentindex != index && !current.getNext().equals(this.head)) { if (currentindex == index-1) { Node returnNode = current.getNext(); // Verbind de huidige Node aan de eerstvolgende Node na de verwijderde Node // VERGEET NIET de verbinding in beide richtingen goed te leggen current.setNext(current.getNext().getNext()); current.getNext().setPrevious(current); // Snij de verbindingen door in het verwijderde object om het geheugen vrij te maken returnNode.setPrevious(null); returnNode.setNext(null); return returnNode.getValue(); } currentindex++; current = current.getNext(); } return "Not found"; } public String peek(String value) { Node current = head; while (!current.getNext().equals(this.head)) { if (current.getNext().getValue().equals(value)) { return current.getNext().getValue(); } current = current.getNext(); } return "Not found"; } public void print() { Node current = this.head; do { System.out.print(current.getValue()+" "); current = current.getNext(); } while (!current.equals(this.head)); System.out.println(); } }
True
1,196
15
1,377
15
1,418
13
1,377
15
1,572
16
false
false
false
false
false
true
1,703
32735_0
import java.io.*; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.json.simple.*; import org.json.simple.parser.JSONParser; public class JSONHandler { public static String getJSON(String filename) { String jsonText = ""; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); String line; while ((line = bufferedReader.readLine()) != null) { jsonText += line + "\n"; } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return jsonText; } public static void updateJson(HashMap<String, Game> gameMap) { JSONArray gamesList = new JSONArray(); for (Map.Entry<String, Game> entry : gameMap.entrySet()) { Game game = entry.getValue(); // Voor elke game, creëer een nieuw JSONObject en vul het met de game details JSONObject gameDetails = new JSONObject(); gameDetails.put("name", game.getName()); gameDetails.put("genre", game.getGenre()); gameDetails.put("platform", game.getPlatform()); gameDetails.put("price", String.format("%.2f", game.getBasePrice())); gameDetails.put("sale", Integer.toString(game.korting)); gamesList.add(gameDetails); } // Creëer een hoofd JSONObject dat de games lijst bevat JSONObject root = new JSONObject(); root.put("games", gamesList); try (FileWriter file = new FileWriter("GamesDB.json")) { String content = root.toJSONString(); file.write(content); } catch (IOException e) { System.out.println("Er is een fout opgetreden bij het schrijven naar het JSON-bestand."); e.printStackTrace(); } } //create a method that reads a JSON file and prints the contents to the console public static HashMap<String, Game> readJSON(String filename, HashMap<String, Game> gameMap) { JSONParser parser = new JSONParser(); JSONArray games = null; try { Object obj = parser.parse(new FileReader(filename)); if (obj instanceof JSONObject jsonObject) { games = (JSONArray) jsonObject.get("games"); // process games array } else if (obj instanceof JSONArray) { games = (JSONArray) obj; // process games array } else { throw new Exception("Invalid JSON file"); } gameMap = new HashMap<>(); for (Object game : games) { JSONObject gameObj = (JSONObject) game; String name = (String) gameObj.get("name"); String genre = (String) gameObj.get("genre"); String platform = (String) gameObj.get("platform"); double price = Double.parseDouble(((String) gameObj.get("price")).replace(",", ".")); int korting = Integer.parseInt((String) gameObj.get("sale")); Game tempGame = new Game(name, genre, platform, price, korting); gameMap.put(name, tempGame); } } catch (Exception e) { e.printStackTrace(); } return gameMap; } }
Techmaster3000/RetroReviewer
src/JSONHandler.java
873
// Voor elke game, creëer een nieuw JSONObject en vul het met de game details
line_comment
nl
import java.io.*; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.json.simple.*; import org.json.simple.parser.JSONParser; public class JSONHandler { public static String getJSON(String filename) { String jsonText = ""; try { BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); String line; while ((line = bufferedReader.readLine()) != null) { jsonText += line + "\n"; } bufferedReader.close(); } catch (Exception e) { e.printStackTrace(); } return jsonText; } public static void updateJson(HashMap<String, Game> gameMap) { JSONArray gamesList = new JSONArray(); for (Map.Entry<String, Game> entry : gameMap.entrySet()) { Game game = entry.getValue(); // Voor elke<SUF> JSONObject gameDetails = new JSONObject(); gameDetails.put("name", game.getName()); gameDetails.put("genre", game.getGenre()); gameDetails.put("platform", game.getPlatform()); gameDetails.put("price", String.format("%.2f", game.getBasePrice())); gameDetails.put("sale", Integer.toString(game.korting)); gamesList.add(gameDetails); } // Creëer een hoofd JSONObject dat de games lijst bevat JSONObject root = new JSONObject(); root.put("games", gamesList); try (FileWriter file = new FileWriter("GamesDB.json")) { String content = root.toJSONString(); file.write(content); } catch (IOException e) { System.out.println("Er is een fout opgetreden bij het schrijven naar het JSON-bestand."); e.printStackTrace(); } } //create a method that reads a JSON file and prints the contents to the console public static HashMap<String, Game> readJSON(String filename, HashMap<String, Game> gameMap) { JSONParser parser = new JSONParser(); JSONArray games = null; try { Object obj = parser.parse(new FileReader(filename)); if (obj instanceof JSONObject jsonObject) { games = (JSONArray) jsonObject.get("games"); // process games array } else if (obj instanceof JSONArray) { games = (JSONArray) obj; // process games array } else { throw new Exception("Invalid JSON file"); } gameMap = new HashMap<>(); for (Object game : games) { JSONObject gameObj = (JSONObject) game; String name = (String) gameObj.get("name"); String genre = (String) gameObj.get("genre"); String platform = (String) gameObj.get("platform"); double price = Double.parseDouble(((String) gameObj.get("price")).replace(",", ".")); int korting = Integer.parseInt((String) gameObj.get("sale")); Game tempGame = new Game(name, genre, platform, price, korting); gameMap.put(name, tempGame); } } catch (Exception e) { e.printStackTrace(); } return gameMap; } }
True
655
20
730
21
782
18
730
21
853
21
false
false
false
false
false
true
3,810
15099_2
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.bruynhuis.galago.ui.effect; import com.bruynhuis.galago.ui.Widget; /** * This effect can be added to a TouchButton. * When the button is clicked it will scale up and down. * * @author NideBruyn */ public class TouchEffect extends Effect { /** * * @param widget */ public TouchEffect(Widget widget) { super(widget); } @Override protected void doShow() { } @Override protected void doHide() { } @Override protected void doTouchDown() { widget.setScale(0.96f); } @Override protected void doTouchUp() { widget.setScale(1f); } @Override protected void doEnabled(boolean enabled) { } @Override protected void controlUpdate(float tpf) { } @Override protected void doSelected() { } @Override protected void doUnselected() { } }
nickidebruyn/galago
Galago3.0/src/com/bruynhuis/galago/ui/effect/TouchEffect.java
317
/** * * @param widget */
block_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.bruynhuis.galago.ui.effect; import com.bruynhuis.galago.ui.Widget; /** * This effect can be added to a TouchButton. * When the button is clicked it will scale up and down. * * @author NideBruyn */ public class TouchEffect extends Effect { /** * * @param widget <SUF>*/ public TouchEffect(Widget widget) { super(widget); } @Override protected void doShow() { } @Override protected void doHide() { } @Override protected void doTouchDown() { widget.setScale(0.96f); } @Override protected void doTouchUp() { widget.setScale(1f); } @Override protected void doEnabled(boolean enabled) { } @Override protected void controlUpdate(float tpf) { } @Override protected void doSelected() { } @Override protected void doUnselected() { } }
False
255
12
266
10
309
15
266
10
326
15
false
false
false
false
false
true
1,498
111117_2
package nl.hu.bep.setup.game.webservices; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.hu.bep.setup.game.domain.BattleSnake; import nl.hu.bep.setup.game.domain.Game; import nl.hu.bep.setup.game.domain.Snake; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Map; @Path("snake") public class SnakeResource { private String lastMove; //haalt snake op @GET @Produces(MediaType.APPLICATION_JSON) public Response getSnake() { return Response.ok(BattleSnake.getMy_BattleSnake().getSnake()).build(); } //Veranderd snake values @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed("user") public Response changeSnake(SnakeDTO snakeDTO) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); snake.updateSnake(snakeDTO.color, snakeDTO.head, snakeDTO.tail); return Response.ok(snake).build(); } private static class SnakeDTO{ public String color; public String tail; public String head; } //Methode slaat data van game op bij start @POST @Path("start") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startGame(GameDataDtos gameDataDtos) { Game game = new Game(gameDataDtos.gameDTO.id, gameDataDtos.youDTO.name); BattleSnake.getMy_BattleSnake().addGame(game); return Response.ok().build(); } //move method geeft de move terug die de snake moet doen @POST @Path("move") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response move(GameDataDtos gameDataDtos) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); Map<String, String> move = snake.getNextMove(gameDataDtos); game.addMove(move.get("move")); return Response.ok().entity(move).build(); } //Slaat alle data op bij einde game @POST @Path("end") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response endGame(GameDataDtos gameDataDtos) { Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); if (game == null) { return Response.status(Response.Status.NOT_FOUND).build(); } game.setAmountOfMoves(gameDataDtos.turn); game.setEndingSnakeLength(gameDataDtos.youDTO.length); return Response.ok().build(); } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDataDtos { @JsonProperty("game") public GameDTO gameDTO; @JsonProperty("turn") public int turn; @JsonProperty("board") public BoardDTO boardDTO; @JsonProperty("you") public YouDTO youDTO; } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDTO { public String id; } @JsonIgnoreProperties(ignoreUnknown = true) public static class BoardDTO { public int height; public int width; public List<Map<String, Integer>> food; } @JsonIgnoreProperties(ignoreUnknown = true) public static class YouDTO { public String name; public int length; public List<Map<String, Integer>> body; public Map<String, Integer> head; } }
Rubens880/BattleSnake
src/main/java/nl/hu/bep/setup/game/webservices/SnakeResource.java
1,169
//Methode slaat data van game op bij start
line_comment
nl
package nl.hu.bep.setup.game.webservices; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import nl.hu.bep.setup.game.domain.BattleSnake; import nl.hu.bep.setup.game.domain.Game; import nl.hu.bep.setup.game.domain.Snake; import javax.annotation.security.RolesAllowed; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.List; import java.util.Map; @Path("snake") public class SnakeResource { private String lastMove; //haalt snake op @GET @Produces(MediaType.APPLICATION_JSON) public Response getSnake() { return Response.ok(BattleSnake.getMy_BattleSnake().getSnake()).build(); } //Veranderd snake values @PUT @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @RolesAllowed("user") public Response changeSnake(SnakeDTO snakeDTO) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); snake.updateSnake(snakeDTO.color, snakeDTO.head, snakeDTO.tail); return Response.ok(snake).build(); } private static class SnakeDTO{ public String color; public String tail; public String head; } //Methode slaat<SUF> @POST @Path("start") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response startGame(GameDataDtos gameDataDtos) { Game game = new Game(gameDataDtos.gameDTO.id, gameDataDtos.youDTO.name); BattleSnake.getMy_BattleSnake().addGame(game); return Response.ok().build(); } //move method geeft de move terug die de snake moet doen @POST @Path("move") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response move(GameDataDtos gameDataDtos) { Snake snake = BattleSnake.getMy_BattleSnake().getSnake(); Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); Map<String, String> move = snake.getNextMove(gameDataDtos); game.addMove(move.get("move")); return Response.ok().entity(move).build(); } //Slaat alle data op bij einde game @POST @Path("end") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response endGame(GameDataDtos gameDataDtos) { Game game = BattleSnake.getMy_BattleSnake().getGameById(gameDataDtos.gameDTO.id); if (game == null) { return Response.status(Response.Status.NOT_FOUND).build(); } game.setAmountOfMoves(gameDataDtos.turn); game.setEndingSnakeLength(gameDataDtos.youDTO.length); return Response.ok().build(); } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDataDtos { @JsonProperty("game") public GameDTO gameDTO; @JsonProperty("turn") public int turn; @JsonProperty("board") public BoardDTO boardDTO; @JsonProperty("you") public YouDTO youDTO; } @JsonIgnoreProperties(ignoreUnknown = true) public static class GameDTO { public String id; } @JsonIgnoreProperties(ignoreUnknown = true) public static class BoardDTO { public int height; public int width; public List<Map<String, Integer>> food; } @JsonIgnoreProperties(ignoreUnknown = true) public static class YouDTO { public String name; public int length; public List<Map<String, Integer>> body; public Map<String, Integer> head; } }
True
809
12
952
12
994
10
952
12
1,213
12
false
false
false
false
false
true
4,055
140899_5
import java.awt.Graphics; import java.util.LinkedList; import Object.EntityDestroyable; import Object.EntityMapObject; import Object.EntityMovable; /** * Controls the player, damage, shop, removes NPC, and other Entities * */ public class Controller { LinkedList<EntityDestroyable> ed = new LinkedList<EntityDestroyable>(); LinkedList<EntityMovable> em = new LinkedList<EntityMovable>(); LinkedList<EntityMapObject> eWO = new LinkedList<EntityMapObject>(); public EntityDestroyable tempEntDe; public EntityMovable tempEntMov; public EntityMapObject tempEntWO; DungeonCrawlerGame game; private int schaden=-12; public Controller(DungeonCrawlerGame game){ this.game=game; } public void update(Player thisplayer){ //Entity Destroyable for (int i=0;i<ed.size();i++){ tempEntDe = ed.get(i); // System.out.println("Current index for Destroyable"+i); if(tempEntDe!=null){ tempEntDe.update(); // if((tempEntDe.getX()>1100 || tempEntDe.getY()>650 || tempEntDe.getX()<0 || tempEntDe.getY()<0) || Physics.CollisionWithMovable(tempEntDe, game.em)) { if ((tempEntMov = Physics.CollisionWithWhichMovable(tempEntDe, game.em))!=null) { // tempEntMov = Physics.CollisionWithWhichMovable(tempEntDe, game.em); // System.out.println("X: "+tempEntDe.getX()+"Y: "+tempEntDe.getY()); schaden=-12; // if ((tempEntDe.getElementArt()==2)&& (tempEntMov.getElementArt()==1)) {schaden=schaden;} if ((tempEntDe.getElementArt()==2)&& (tempEntMov.getElementArt()==2)) {schaden*=0.5;} if ((tempEntDe.getElementArt()==2)&& (tempEntMov.getElementArt()==3)) {schaden=schaden*2;} if ((tempEntDe.getElementArt()==1)&& (tempEntMov.getElementArt()==2)) {schaden=schaden*2;} if ((tempEntDe.getElementArt()==1)&& (tempEntMov.getElementArt()==1)) {schaden*=0.5;} // if ((tempEntDe.getElementArt()==1)&& (tempEntMov.getElementArt()==3)) {schaden=schaden;} if ((tempEntDe.getElementArt()==3)&& (tempEntMov.getElementArt()==1)) {schaden=schaden*2;} // if ((tempEntDe.getElementArt()==3)&& (tempEntMov.getElementArt()==2)) {schaden=schaden;} if ((tempEntDe.getElementArt()==3)&& (tempEntMov.getElementArt()==3)) {schaden*=0.5;} if (game.mainWindow.gameClient==null) { tempEntDe.changeLifepoints(schaden, 250000000); } if (!tempEntDe.isAlive()) { if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("DESTROYABLE REMOVE "+i); } if (game.mainWindow.gameClient==null) { removeEntity(tempEntDe); } } else { if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("DESTROYABLE LIFE "+i+" "+tempEntDe.getLifepoints()+" "+(int)tempEntDe.getX()+" "+(int)tempEntDe.getY()); } } System.out.println("game.ed.size()="+game.ed.size()); if(game.world.getLevelNumber()==3 && game.ed.size()<1){ // System.out.println("game.ed.size()="+game.ed.size()); game.world.wallquest.clear(); if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("WALLQUEST REMOVE "); } } } } } //Entity Movable // System.out.println("Size of Bullets"+em.size()); for (int i=0;i<em.size();i++){ tempEntMov = em.get(i); if(((tempEntMov.getX()>1100 || tempEntMov.getY()>650 || tempEntMov.getX()<0 || tempEntMov.getY()<0))|| tempEntMov.isHited() ){ if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("MOVABLE REMOVE "+i); } if (game.mainWindow.gameClient==null) { removeEntity(tempEntMov); } } if(tempEntMov!=null) tempEntMov.update(); } //EntityMapObject // System.out.println("Size of eWO "+eWO.size()); thisplayer.setHitShop(false); thisplayer.setHitStory(false); for (int i=0;i<eWO.size();i++){ tempEntWO = eWO.get(i); // System.out.println("Current index for MapObject"+i); if((Physics.CollisionGameObjectList(thisplayer, tempEntWO))){ if (tempEntWO.getLeben()!=0) {thisplayer.changePlayerLifepoints(tempEntWO.getLeben(), 0);} if (tempEntWO.getMana()!=0) {thisplayer.changePlayerManapoints(tempEntWO.getMana());} if (tempEntWO.getGeld()!=0) {thisplayer.changePlayerMoney(tempEntWO.getGeld());} if( tempEntWO.isWeapon()){ thisplayer.setWeapon(true); } if( tempEntWO.isArmor()){ thisplayer.setArmor(true); } if( tempEntWO.isShop()){ thisplayer.setHitShop(true); } if( tempEntWO.isStory()){ thisplayer.setHitStory(true); } if (tempEntWO.isCollectable()) removeEntity(tempEntWO); // System.out.println("COLLISION "+i); //removeEntity(tempEntWO); } if(tempEntWO!=null) tempEntWO.update(); } }//======================END OF Update public void draw(Graphics g){ //Ent. MO for (int i=0;i<eWO.size();i++){ tempEntWO = eWO.get(i); if(tempEntWO!=null) tempEntWO.draw(g); } //Entity Destroyable for (int i=0;i<ed.size();i++){ tempEntDe = ed.get(i); tempEntDe.draw(g); } //Entity Movable for (int i=0;i<em.size();i++){ tempEntMov = em.get(i); tempEntMov.draw(g); } } public void addEntity(EntityDestroyable ent) { ed.add(ent); } public void removeEntity(EntityDestroyable ent){ ed.remove(ent); } public void addEntity(EntityMovable ent) { //EntityMovable em.add(ent); } public void removeEntity(EntityMovable ent){ em.remove(ent); } public void addEntity(EntityMapObject ent) { eWO.add(ent); } public void addEntity(EntityMapObject ent,String special,boolean wert) { if (special == "shop") { ent.setShop(wert); } if (special == "story") { ent.setStory(wert); } if (special == "weapon") { ent.setWeapon(wert); ent.setCollectable(wert); } if (special == "armor") { ent.setArmor(wert); ent.setCollectable(wert); } if (special == "collectable") { ent.setCollectable(wert); } eWO.add(ent); } public void removeEntity(EntityMapObject ent){ eWO.remove(ent); } public LinkedList<EntityDestroyable> getEntDestrList(){ return ed; } public LinkedList<EntityMovable> getEntMovList(){ return em; } public LinkedList<EntityMapObject> getEntMO(){ return eWO; } }
propra13-orga/gruppe81
src/Controller.java
2,529
// if ((tempEntDe.getElementArt()==2)&& (tempEntMov.getElementArt()==1)) {schaden=schaden;}
line_comment
nl
import java.awt.Graphics; import java.util.LinkedList; import Object.EntityDestroyable; import Object.EntityMapObject; import Object.EntityMovable; /** * Controls the player, damage, shop, removes NPC, and other Entities * */ public class Controller { LinkedList<EntityDestroyable> ed = new LinkedList<EntityDestroyable>(); LinkedList<EntityMovable> em = new LinkedList<EntityMovable>(); LinkedList<EntityMapObject> eWO = new LinkedList<EntityMapObject>(); public EntityDestroyable tempEntDe; public EntityMovable tempEntMov; public EntityMapObject tempEntWO; DungeonCrawlerGame game; private int schaden=-12; public Controller(DungeonCrawlerGame game){ this.game=game; } public void update(Player thisplayer){ //Entity Destroyable for (int i=0;i<ed.size();i++){ tempEntDe = ed.get(i); // System.out.println("Current index for Destroyable"+i); if(tempEntDe!=null){ tempEntDe.update(); // if((tempEntDe.getX()>1100 || tempEntDe.getY()>650 || tempEntDe.getX()<0 || tempEntDe.getY()<0) || Physics.CollisionWithMovable(tempEntDe, game.em)) { if ((tempEntMov = Physics.CollisionWithWhichMovable(tempEntDe, game.em))!=null) { // tempEntMov = Physics.CollisionWithWhichMovable(tempEntDe, game.em); // System.out.println("X: "+tempEntDe.getX()+"Y: "+tempEntDe.getY()); schaden=-12; // if ((tempEntDe.getElementArt()==2)&&<SUF> if ((tempEntDe.getElementArt()==2)&& (tempEntMov.getElementArt()==2)) {schaden*=0.5;} if ((tempEntDe.getElementArt()==2)&& (tempEntMov.getElementArt()==3)) {schaden=schaden*2;} if ((tempEntDe.getElementArt()==1)&& (tempEntMov.getElementArt()==2)) {schaden=schaden*2;} if ((tempEntDe.getElementArt()==1)&& (tempEntMov.getElementArt()==1)) {schaden*=0.5;} // if ((tempEntDe.getElementArt()==1)&& (tempEntMov.getElementArt()==3)) {schaden=schaden;} if ((tempEntDe.getElementArt()==3)&& (tempEntMov.getElementArt()==1)) {schaden=schaden*2;} // if ((tempEntDe.getElementArt()==3)&& (tempEntMov.getElementArt()==2)) {schaden=schaden;} if ((tempEntDe.getElementArt()==3)&& (tempEntMov.getElementArt()==3)) {schaden*=0.5;} if (game.mainWindow.gameClient==null) { tempEntDe.changeLifepoints(schaden, 250000000); } if (!tempEntDe.isAlive()) { if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("DESTROYABLE REMOVE "+i); } if (game.mainWindow.gameClient==null) { removeEntity(tempEntDe); } } else { if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("DESTROYABLE LIFE "+i+" "+tempEntDe.getLifepoints()+" "+(int)tempEntDe.getX()+" "+(int)tempEntDe.getY()); } } System.out.println("game.ed.size()="+game.ed.size()); if(game.world.getLevelNumber()==3 && game.ed.size()<1){ // System.out.println("game.ed.size()="+game.ed.size()); game.world.wallquest.clear(); if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("WALLQUEST REMOVE "); } } } } } //Entity Movable // System.out.println("Size of Bullets"+em.size()); for (int i=0;i<em.size();i++){ tempEntMov = em.get(i); if(((tempEntMov.getX()>1100 || tempEntMov.getY()>650 || tempEntMov.getX()<0 || tempEntMov.getY()<0))|| tempEntMov.isHited() ){ if (game.mainWindow.gameServer!=null) { game.mainWindow.gameServer.gameServerThread.serverOut.println("MOVABLE REMOVE "+i); } if (game.mainWindow.gameClient==null) { removeEntity(tempEntMov); } } if(tempEntMov!=null) tempEntMov.update(); } //EntityMapObject // System.out.println("Size of eWO "+eWO.size()); thisplayer.setHitShop(false); thisplayer.setHitStory(false); for (int i=0;i<eWO.size();i++){ tempEntWO = eWO.get(i); // System.out.println("Current index for MapObject"+i); if((Physics.CollisionGameObjectList(thisplayer, tempEntWO))){ if (tempEntWO.getLeben()!=0) {thisplayer.changePlayerLifepoints(tempEntWO.getLeben(), 0);} if (tempEntWO.getMana()!=0) {thisplayer.changePlayerManapoints(tempEntWO.getMana());} if (tempEntWO.getGeld()!=0) {thisplayer.changePlayerMoney(tempEntWO.getGeld());} if( tempEntWO.isWeapon()){ thisplayer.setWeapon(true); } if( tempEntWO.isArmor()){ thisplayer.setArmor(true); } if( tempEntWO.isShop()){ thisplayer.setHitShop(true); } if( tempEntWO.isStory()){ thisplayer.setHitStory(true); } if (tempEntWO.isCollectable()) removeEntity(tempEntWO); // System.out.println("COLLISION "+i); //removeEntity(tempEntWO); } if(tempEntWO!=null) tempEntWO.update(); } }//======================END OF Update public void draw(Graphics g){ //Ent. MO for (int i=0;i<eWO.size();i++){ tempEntWO = eWO.get(i); if(tempEntWO!=null) tempEntWO.draw(g); } //Entity Destroyable for (int i=0;i<ed.size();i++){ tempEntDe = ed.get(i); tempEntDe.draw(g); } //Entity Movable for (int i=0;i<em.size();i++){ tempEntMov = em.get(i); tempEntMov.draw(g); } } public void addEntity(EntityDestroyable ent) { ed.add(ent); } public void removeEntity(EntityDestroyable ent){ ed.remove(ent); } public void addEntity(EntityMovable ent) { //EntityMovable em.add(ent); } public void removeEntity(EntityMovable ent){ em.remove(ent); } public void addEntity(EntityMapObject ent) { eWO.add(ent); } public void addEntity(EntityMapObject ent,String special,boolean wert) { if (special == "shop") { ent.setShop(wert); } if (special == "story") { ent.setStory(wert); } if (special == "weapon") { ent.setWeapon(wert); ent.setCollectable(wert); } if (special == "armor") { ent.setArmor(wert); ent.setCollectable(wert); } if (special == "collectable") { ent.setCollectable(wert); } eWO.add(ent); } public void removeEntity(EntityMapObject ent){ eWO.remove(ent); } public LinkedList<EntityDestroyable> getEntDestrList(){ return ed; } public LinkedList<EntityMovable> getEntMovList(){ return em; } public LinkedList<EntityMapObject> getEntMO(){ return eWO; } }
False
1,836
27
2,216
31
2,227
30
2,216
31
2,898
34
false
false
false
false
false
true
2,336
13934_29
// ============================================================================= // -- Unreal classes ----------------------------------------------------------- // ============================================================================= /** * @hidden * @opt nodefillcolor gray */ class UObject {} /** @opt nodefillcolor gray */ class AAIController extends AController {} /** @opt nodefillcolor gray */ class AActor extends UObject {} /** @opt nodefillcolor gray */ class ACharacter extends APawn {} /** @opt nodefillcolor gray */ class AController extends AActor {} /** @opt nodefillcolor gray */ class AGameModeBase extends AActor {} /** @opt nodefillcolor gray */ class AHUD extends AActor {} /** @opt nodefillcolor gray */ class AInfo extends AActor {} /** @opt nodefillcolor gray */ class APawn extends AActor {} /** @opt nodefillcolor gray */ class APlayerController extends AController {} /** @opt nodefillcolor gray */ class APlayerState extends AInfo {} /** @opt nodefillcolor gray */ class AWheeledVehicle extends APawn {} /** @opt nodefillcolor gray */ class UActorComponent extends UObject {} /** @opt nodefillcolor gray */ class UCameraComponent extends USceneComponent {} /** @opt nodefillcolor gray */ class UGameInstance extends UObject {} /** @opt nodefillcolor gray */ class USceneComponent extends UActorComponent {} // ============================================================================= // -- Agent -------------------------------------------------------------------- // ============================================================================= class UAgentComponent extends USceneComponent {} class UTrafficSignAgentComponent extends UAgentComponent {} class UVehicleAgentComponent extends UAgentComponent {} class UWalkerAgentComponent extends UAgentComponent {} // ============================================================================= // -- Game --------------------------------------------------------------------- // ============================================================================= /** * @has - - - FDataRouter */ class ICarlaGameControllerBase {} /** * @composed - - - ICarlaGameControllerBase * @composed - - - FDataRouter * @composed - - - UCarlaSettings */ class UCarlaGameInstance extends UGameInstance {} // * @has - Player - ACarlaVehicleController /** * @depend - - - UCarlaGameInstance * @composed - - - UTaggerDelegate * @composed - - - ADynamicWeather * @composed - - - AVehicleSpawnerBase * @composed - - - AWalkerSpawnerBase */ class ACarlaGameModeBase extends AGameModeBase {} class ACarlaHUD extends AHUD {} class ACarlaPlayerState extends APlayerState {} /** * @depend - - - UAgentComponent * @depend - - - ACarlaVehicleController * @composed - - - ISensorDataSink */ class FDataRouter {} /** * @composed - - - FMockSensorDataSink */ class MockGameController extends ICarlaGameControllerBase {} class FMockSensorDataSink extends ISensorDataSink {} /** * @depend - - - ATagger */ class UTaggerDelegate extends UObject {} class ATagger /*extends AActor*/ {} // ============================================================================= // -- MapGen ------------------------------------------------------------------- // ============================================================================= // MapGen is ignored here. // ============================================================================= // -- Sensor ------------------------------------------------------------------- // ============================================================================= class ALidar extends ASensor {} class ASceneCaptureCamera extends ASensor {} /** * @depend - - - ISensorDataSink */ class ASensor extends AActor {} class ISensorDataSink {} // ============================================================================= // -- Server ------------------------------------------------------------------- // ============================================================================= /** * @depend - - - CarlaServerAPI */ class FCarlaServer {} /** * @composed - - - FCarlaServer * @has - - - FServerSensorDataSink */ class FServerGameController extends ICarlaGameControllerBase {} /** * @depend - - - FCarlaServer */ class FServerSensorDataSink extends ISensorDataSink {} /** * CarlaServer * Library API * @opt commentname * @opt nodefillcolor #fdf6e3 */ class CarlaServerAPI {} // ============================================================================= // -- Settings ----------------------------------------------------------------- // ============================================================================= class UCameraDescription extends USensorDescription {} /** * @composed - - - USensorDescription */ class UCarlaSettings extends UObject {} class ULidarDescription extends USensorDescription {} class USensorDescription extends UObject {} // ============================================================================= // -- Traffic ------------------------------------------------------------------ // ============================================================================= class ATrafficLightBase extends ATrafficSignBase {} /** * @composed - - - UTrafficSignAgentComponent */ class ATrafficSignBase extends AActor {} // ============================================================================= // -- Util --------------------------------------------------------------------- // ============================================================================= class AActorWithRandomEngine extends AActor {} // ============================================================================= // -- Vehicle ------------------------------------------------------------------ // ============================================================================= /** * @has - - - ACarlaPlayerState * @has - - - ACarlaHUD */ class ACarlaVehicleController extends AWheeledVehicleController {} /** * @composed - - - UVehicleAgentComponent */ class ACarlaWheeledVehicle extends AWheeledVehicle {} /** * @has - - - ACarlaWheeledVehicle */ class AVehicleSpawnerBase extends AActorWithRandomEngine {} /** * @has - - - ACarlaWheeledVehicle */ class AWheeledVehicleAIController extends APlayerController {} /** * @composed - - - UCameraComponent */ class AWheeledVehicleController extends AWheeledVehicleAIController {} // ============================================================================= // -- Walker ------------------------------------------------------------------- // ============================================================================= /** * @has - - - ACharacter */ class AWalkerAIController extends AAIController {} /** * @has - - - ACharacter */ class AWalkerSpawnerBase extends AActorWithRandomEngine {} // ============================================================================= // -- Blueprints --------------------------------------------------------------- // ============================================================================= /** * Carla Game Mode * @opt commentname * @opt nodefillcolor #bfe4ff */ class CarlaGameMode extends ACarlaGameModeBase {} /** * Speed Limit Sign * @opt commentname * @opt nodefillcolor #bfe4ff */ class SpeedLimitSignBlueprint extends ATrafficSignBase {} /** * Traffic Light * @opt commentname * @opt nodefillcolor #bfe4ff */ class TrafficLightBlueprint extends ATrafficLightBase {} /** * Vehicle Blueprints * @opt commentname * @opt nodefillcolor #bfe4ff */ class VehicleBlueprints extends ACarlaWheeledVehicle {} /** * Vehicle Spawner * @opt commentname * @opt nodefillcolor #bfe4ff */ class VehicleSpawnerBlueprint extends AVehicleSpawnerBase {} /** * Walker Blueprints * @opt commentname * @opt nodefillcolor #bfe4ff * @composed - - - UWalkerAgentComponent */ class WalkerBlueprints extends ACharacter {} /** * Walker Spawner * @opt commentname * @opt nodefillcolor #bfe4ff */ class WalkerSpawnerBlueprint extends AWalkerSpawnerBase {}
carla-simulator/carla
Docs/img/carla_plugin_graph.java
1,846
/** * @depend - - - ISensorDataSink */
block_comment
nl
// ============================================================================= // -- Unreal classes ----------------------------------------------------------- // ============================================================================= /** * @hidden * @opt nodefillcolor gray */ class UObject {} /** @opt nodefillcolor gray */ class AAIController extends AController {} /** @opt nodefillcolor gray */ class AActor extends UObject {} /** @opt nodefillcolor gray */ class ACharacter extends APawn {} /** @opt nodefillcolor gray */ class AController extends AActor {} /** @opt nodefillcolor gray */ class AGameModeBase extends AActor {} /** @opt nodefillcolor gray */ class AHUD extends AActor {} /** @opt nodefillcolor gray */ class AInfo extends AActor {} /** @opt nodefillcolor gray */ class APawn extends AActor {} /** @opt nodefillcolor gray */ class APlayerController extends AController {} /** @opt nodefillcolor gray */ class APlayerState extends AInfo {} /** @opt nodefillcolor gray */ class AWheeledVehicle extends APawn {} /** @opt nodefillcolor gray */ class UActorComponent extends UObject {} /** @opt nodefillcolor gray */ class UCameraComponent extends USceneComponent {} /** @opt nodefillcolor gray */ class UGameInstance extends UObject {} /** @opt nodefillcolor gray */ class USceneComponent extends UActorComponent {} // ============================================================================= // -- Agent -------------------------------------------------------------------- // ============================================================================= class UAgentComponent extends USceneComponent {} class UTrafficSignAgentComponent extends UAgentComponent {} class UVehicleAgentComponent extends UAgentComponent {} class UWalkerAgentComponent extends UAgentComponent {} // ============================================================================= // -- Game --------------------------------------------------------------------- // ============================================================================= /** * @has - - - FDataRouter */ class ICarlaGameControllerBase {} /** * @composed - - - ICarlaGameControllerBase * @composed - - - FDataRouter * @composed - - - UCarlaSettings */ class UCarlaGameInstance extends UGameInstance {} // * @has - Player - ACarlaVehicleController /** * @depend - - - UCarlaGameInstance * @composed - - - UTaggerDelegate * @composed - - - ADynamicWeather * @composed - - - AVehicleSpawnerBase * @composed - - - AWalkerSpawnerBase */ class ACarlaGameModeBase extends AGameModeBase {} class ACarlaHUD extends AHUD {} class ACarlaPlayerState extends APlayerState {} /** * @depend - - - UAgentComponent * @depend - - - ACarlaVehicleController * @composed - - - ISensorDataSink */ class FDataRouter {} /** * @composed - - - FMockSensorDataSink */ class MockGameController extends ICarlaGameControllerBase {} class FMockSensorDataSink extends ISensorDataSink {} /** * @depend - - - ATagger */ class UTaggerDelegate extends UObject {} class ATagger /*extends AActor*/ {} // ============================================================================= // -- MapGen ------------------------------------------------------------------- // ============================================================================= // MapGen is ignored here. // ============================================================================= // -- Sensor ------------------------------------------------------------------- // ============================================================================= class ALidar extends ASensor {} class ASceneCaptureCamera extends ASensor {} /** * @depend - -<SUF>*/ class ASensor extends AActor {} class ISensorDataSink {} // ============================================================================= // -- Server ------------------------------------------------------------------- // ============================================================================= /** * @depend - - - CarlaServerAPI */ class FCarlaServer {} /** * @composed - - - FCarlaServer * @has - - - FServerSensorDataSink */ class FServerGameController extends ICarlaGameControllerBase {} /** * @depend - - - FCarlaServer */ class FServerSensorDataSink extends ISensorDataSink {} /** * CarlaServer * Library API * @opt commentname * @opt nodefillcolor #fdf6e3 */ class CarlaServerAPI {} // ============================================================================= // -- Settings ----------------------------------------------------------------- // ============================================================================= class UCameraDescription extends USensorDescription {} /** * @composed - - - USensorDescription */ class UCarlaSettings extends UObject {} class ULidarDescription extends USensorDescription {} class USensorDescription extends UObject {} // ============================================================================= // -- Traffic ------------------------------------------------------------------ // ============================================================================= class ATrafficLightBase extends ATrafficSignBase {} /** * @composed - - - UTrafficSignAgentComponent */ class ATrafficSignBase extends AActor {} // ============================================================================= // -- Util --------------------------------------------------------------------- // ============================================================================= class AActorWithRandomEngine extends AActor {} // ============================================================================= // -- Vehicle ------------------------------------------------------------------ // ============================================================================= /** * @has - - - ACarlaPlayerState * @has - - - ACarlaHUD */ class ACarlaVehicleController extends AWheeledVehicleController {} /** * @composed - - - UVehicleAgentComponent */ class ACarlaWheeledVehicle extends AWheeledVehicle {} /** * @has - - - ACarlaWheeledVehicle */ class AVehicleSpawnerBase extends AActorWithRandomEngine {} /** * @has - - - ACarlaWheeledVehicle */ class AWheeledVehicleAIController extends APlayerController {} /** * @composed - - - UCameraComponent */ class AWheeledVehicleController extends AWheeledVehicleAIController {} // ============================================================================= // -- Walker ------------------------------------------------------------------- // ============================================================================= /** * @has - - - ACharacter */ class AWalkerAIController extends AAIController {} /** * @has - - - ACharacter */ class AWalkerSpawnerBase extends AActorWithRandomEngine {} // ============================================================================= // -- Blueprints --------------------------------------------------------------- // ============================================================================= /** * Carla Game Mode * @opt commentname * @opt nodefillcolor #bfe4ff */ class CarlaGameMode extends ACarlaGameModeBase {} /** * Speed Limit Sign * @opt commentname * @opt nodefillcolor #bfe4ff */ class SpeedLimitSignBlueprint extends ATrafficSignBase {} /** * Traffic Light * @opt commentname * @opt nodefillcolor #bfe4ff */ class TrafficLightBlueprint extends ATrafficLightBase {} /** * Vehicle Blueprints * @opt commentname * @opt nodefillcolor #bfe4ff */ class VehicleBlueprints extends ACarlaWheeledVehicle {} /** * Vehicle Spawner * @opt commentname * @opt nodefillcolor #bfe4ff */ class VehicleSpawnerBlueprint extends AVehicleSpawnerBase {} /** * Walker Blueprints * @opt commentname * @opt nodefillcolor #bfe4ff * @composed - - - UWalkerAgentComponent */ class WalkerBlueprints extends ACharacter {} /** * Walker Spawner * @opt commentname * @opt nodefillcolor #bfe4ff */ class WalkerSpawnerBlueprint extends AWalkerSpawnerBase {}
False
1,422
13
1,613
14
1,697
14
1,613
14
1,961
16
false
false
false
false
false
true
1,071
109965_9
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.dtos.user.UserDto; import nl.novi.techiteasy.dtos.user.UserResponseDto; import nl.novi.techiteasy.exceptions.BadRequestException; import nl.novi.techiteasy.dtos.authority.AuthorityDto; import nl.novi.techiteasy.services.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; @CrossOrigin @RestController @RequestMapping(value = "/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping(value = "") public ResponseEntity<List<UserDto>> getUsers() { List<UserDto> userDtos = userService.getUsers(); return ResponseEntity.ok().body(userDtos); } @GetMapping(value = "/{username}") public ResponseEntity<UserDto> getUser(@PathVariable("username") String username) { UserDto optionalUser = userService.getUser(username); return ResponseEntity.ok().body(optionalUser); } @PostMapping(value = "") public ResponseEntity<UserDto> createKlant(@RequestBody UserDto dto) {; String newUsername = userService.createUser(dto); userService.addAuthority(newUsername, "ROLE_USER"); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{username}") .buildAndExpand(newUsername).toUri(); return ResponseEntity.created(location).build(); } @PutMapping(value = "/{username}") public ResponseEntity<UserDto> updateKlant(@PathVariable("username") String username, @RequestBody UserDto dto) { userService.updateUser(username, dto); return ResponseEntity.noContent().build(); } @DeleteMapping(value = "/{username}") public ResponseEntity<Object> deleteKlant(@PathVariable("username") String username) { userService.deleteUser(username); return ResponseEntity.noContent().build(); } @GetMapping(value = "/{username}/authorities") public ResponseEntity<Object> getUserAuthorities(@PathVariable("username") String username) { return ResponseEntity.ok().body(userService.getAuthorities(username)); } // Vraag in to do: Als Requestbody wordt hier een Map<String, Object> gebruikt om de "authorityName" binnen te halen, dat werkt, maar kun je een betere oplossing bedenken? // Antwoord: Ja, met een DTO. Ik heb deze class AuthorityDto genoemd en ondergebracht in het mapje dtos/authority, @PostMapping(value = "/{username}/authorities") public ResponseEntity<Object> addUserAuthority( @PathVariable("username") String username, @RequestBody AuthorityDto authorityDto) { try { String authorityName = authorityDto.authority; userService.addAuthority(username, authorityName); return ResponseEntity.noContent().build(); } catch (Exception ex) { throw new BadRequestException(); } } // Oude versie: // @PostMapping(value = "/{username}/authorities") // public ResponseEntity<Object> addUserAuthority(@PathVariable("username") String username, @RequestBody Map<String, Object> fields) { // try { // String authorityName = (String) fields.get("authority"); // userService.addAuthority(username, authorityName); // return ResponseEntity.noContent().build(); // } // catch (Exception ex) { // throw new BadRequestException(); // } // } @DeleteMapping(value = "/{username}/authorities/{authority}") public ResponseEntity<Object> deleteUserAuthority(@PathVariable("username") String username, @PathVariable("authority") String authority) { userService.removeAuthority(username, authority); return ResponseEntity.noContent().build(); } // Bonusopdracht // Toepassen van SecurityContextHolder en Authentication classes (zie imports), en methode getUserById toegevoegd. // Ik heb een aparte ResponseDto gemaakt, die een beperkt aantal velden teruggeeft aan de gebruiker. // Ben er niet meer aan toegekomen om dit uit te testen in Postman voor de deadline, maar dit wil ik nog wel gaan doen. Ben wel benieuwd of ik op de goede weg zit. @GetMapping("/{id}") public ResponseEntity<Object> getUserById(@PathVariable("id") String id) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); if (username.equals(id)) { UserDto userDto = userService.getUser(id); UserResponseDto responseDto = new UserResponseDto(userDto.getUsername(), userDto.getEmail(), userDto.getAuthorities()); return ResponseEntity.ok(userDto); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied"); } } }
MarjetBosma/NOVI-backend-springboot-techiteasy
src/main/java/nl/novi/techiteasy/controllers/UserController.java
1,422
// Ben er niet meer aan toegekomen om dit uit te testen in Postman voor de deadline, maar dit wil ik nog wel gaan doen. Ben wel benieuwd of ik op de goede weg zit.
line_comment
nl
package nl.novi.techiteasy.controllers; import nl.novi.techiteasy.dtos.user.UserDto; import nl.novi.techiteasy.dtos.user.UserResponseDto; import nl.novi.techiteasy.exceptions.BadRequestException; import nl.novi.techiteasy.dtos.authority.AuthorityDto; import nl.novi.techiteasy.services.UserService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import java.net.URI; import java.util.List; @CrossOrigin @RestController @RequestMapping(value = "/users") public class UserController { private final UserService userService; public UserController(UserService userService) { this.userService = userService; } @GetMapping(value = "") public ResponseEntity<List<UserDto>> getUsers() { List<UserDto> userDtos = userService.getUsers(); return ResponseEntity.ok().body(userDtos); } @GetMapping(value = "/{username}") public ResponseEntity<UserDto> getUser(@PathVariable("username") String username) { UserDto optionalUser = userService.getUser(username); return ResponseEntity.ok().body(optionalUser); } @PostMapping(value = "") public ResponseEntity<UserDto> createKlant(@RequestBody UserDto dto) {; String newUsername = userService.createUser(dto); userService.addAuthority(newUsername, "ROLE_USER"); URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{username}") .buildAndExpand(newUsername).toUri(); return ResponseEntity.created(location).build(); } @PutMapping(value = "/{username}") public ResponseEntity<UserDto> updateKlant(@PathVariable("username") String username, @RequestBody UserDto dto) { userService.updateUser(username, dto); return ResponseEntity.noContent().build(); } @DeleteMapping(value = "/{username}") public ResponseEntity<Object> deleteKlant(@PathVariable("username") String username) { userService.deleteUser(username); return ResponseEntity.noContent().build(); } @GetMapping(value = "/{username}/authorities") public ResponseEntity<Object> getUserAuthorities(@PathVariable("username") String username) { return ResponseEntity.ok().body(userService.getAuthorities(username)); } // Vraag in to do: Als Requestbody wordt hier een Map<String, Object> gebruikt om de "authorityName" binnen te halen, dat werkt, maar kun je een betere oplossing bedenken? // Antwoord: Ja, met een DTO. Ik heb deze class AuthorityDto genoemd en ondergebracht in het mapje dtos/authority, @PostMapping(value = "/{username}/authorities") public ResponseEntity<Object> addUserAuthority( @PathVariable("username") String username, @RequestBody AuthorityDto authorityDto) { try { String authorityName = authorityDto.authority; userService.addAuthority(username, authorityName); return ResponseEntity.noContent().build(); } catch (Exception ex) { throw new BadRequestException(); } } // Oude versie: // @PostMapping(value = "/{username}/authorities") // public ResponseEntity<Object> addUserAuthority(@PathVariable("username") String username, @RequestBody Map<String, Object> fields) { // try { // String authorityName = (String) fields.get("authority"); // userService.addAuthority(username, authorityName); // return ResponseEntity.noContent().build(); // } // catch (Exception ex) { // throw new BadRequestException(); // } // } @DeleteMapping(value = "/{username}/authorities/{authority}") public ResponseEntity<Object> deleteUserAuthority(@PathVariable("username") String username, @PathVariable("authority") String authority) { userService.removeAuthority(username, authority); return ResponseEntity.noContent().build(); } // Bonusopdracht // Toepassen van SecurityContextHolder en Authentication classes (zie imports), en methode getUserById toegevoegd. // Ik heb een aparte ResponseDto gemaakt, die een beperkt aantal velden teruggeeft aan de gebruiker. // Ben er<SUF> @GetMapping("/{id}") public ResponseEntity<Object> getUserById(@PathVariable("id") String id) { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); String username = authentication.getName(); if (username.equals(id)) { UserDto userDto = userService.getUser(id); UserResponseDto responseDto = new UserResponseDto(userDto.getUsername(), userDto.getEmail(), userDto.getAuthorities()); return ResponseEntity.ok(userDto); } else { return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access denied"); } } }
True
1,026
46
1,220
53
1,190
42
1,220
53
1,445
51
false
false
false
false
false
true
716
30152_0
package com.hyxogen.authenticator; import org.apache.commons.codec.digest.DigestUtils; import org.bukkit.entity.Player; import com.hyxogen.authenticator.challenge.ChallengeHandler; import com.hyxogen.authenticator.user.User; import com.hyxogen.authenticator.user.UserHandler; import com.hyxogen.authenticator.user.UserLogin; import com.hyxogen.authenticator.util.CryptoUtils; import com.hyxogen.authenticator.util.Permissions; public class AuthenticationHandler { public static final int COOLDOWN = 30 * 60; public final ChallengeHandler challengeHandler; public AuthenticationHandler(ChallengeHandler challengeHandler) { this.challengeHandler = challengeHandler; } public boolean needsAuthentication(Player player) { if(!player.hasPermission(Permissions.PERM_AUTH_REQUIRED) && !player.hasPermission(Permissions.PERM_AUTH_ALLOWED)) return false; if(!isReady(player)) return true; long current = System.currentTimeMillis(); User user = UserHandler.getUser(player.getUniqueId()); UserLogin lastLogin = user.lastLogin; //TODO cache result zodat dit niet iedere movement gechecked moet worden. //We zouden ook slowness 100000 kunnen geven zodat ze niet kunnen bewegen //Dit werkt niet voor commands en chat berichten if(player.getAddress().getAddress().getAddress() != lastLogin.address) return true; if(((lastLogin.time - current) / 1000L) > COOLDOWN) return true; return false; } public boolean handleAuth(Player player, String code) { // if(!needsAuthentication(player)) // return true; User user = UserHandler.getUser(player.getUniqueId()); long current = System.currentTimeMillis(); if(CryptoUtils.checkTOTP(user.key, current / 1000L, 1, 6, code)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else if (CryptoUtils.containsKey(DigestUtils.sha1(code), user.backupCodes)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else { return false; } } public boolean isReady(Player player) { User user = UserHandler.getUser(player.getUniqueId()); if(user.lastLogin == null) return false; else return true; } }
Hyxogen/AuthenticatorPlugin
src/com/hyxogen/authenticator/AuthenticationHandler.java
762
//TODO cache result zodat dit niet iedere movement gechecked moet worden.
line_comment
nl
package com.hyxogen.authenticator; import org.apache.commons.codec.digest.DigestUtils; import org.bukkit.entity.Player; import com.hyxogen.authenticator.challenge.ChallengeHandler; import com.hyxogen.authenticator.user.User; import com.hyxogen.authenticator.user.UserHandler; import com.hyxogen.authenticator.user.UserLogin; import com.hyxogen.authenticator.util.CryptoUtils; import com.hyxogen.authenticator.util.Permissions; public class AuthenticationHandler { public static final int COOLDOWN = 30 * 60; public final ChallengeHandler challengeHandler; public AuthenticationHandler(ChallengeHandler challengeHandler) { this.challengeHandler = challengeHandler; } public boolean needsAuthentication(Player player) { if(!player.hasPermission(Permissions.PERM_AUTH_REQUIRED) && !player.hasPermission(Permissions.PERM_AUTH_ALLOWED)) return false; if(!isReady(player)) return true; long current = System.currentTimeMillis(); User user = UserHandler.getUser(player.getUniqueId()); UserLogin lastLogin = user.lastLogin; //TODO cache<SUF> //We zouden ook slowness 100000 kunnen geven zodat ze niet kunnen bewegen //Dit werkt niet voor commands en chat berichten if(player.getAddress().getAddress().getAddress() != lastLogin.address) return true; if(((lastLogin.time - current) / 1000L) > COOLDOWN) return true; return false; } public boolean handleAuth(Player player, String code) { // if(!needsAuthentication(player)) // return true; User user = UserHandler.getUser(player.getUniqueId()); long current = System.currentTimeMillis(); if(CryptoUtils.checkTOTP(user.key, current / 1000L, 1, 6, code)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else if (CryptoUtils.containsKey(DigestUtils.sha1(code), user.backupCodes)) { challengeHandler.finishAll(user); user.lastLogin = new UserLogin(player.getAddress().getAddress().getAddress(), System.currentTimeMillis()); return true; } else { return false; } } public boolean isReady(Player player) { User user = UserHandler.getUser(player.getUniqueId()); if(user.lastLogin == null) return false; else return true; } }
True
554
17
676
18
674
14
676
18
816
20
false
false
false
false
false
true
1,396
15324_6
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_gras.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, 17, -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, 17, -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(); if (BeginLevel.daarIsDeT == true) { addObject (new THUD(), 300, 50); } if (BeginLevel.daarIsDeO == true) { addObject (new OHUD(), 350, 50); } if (BeginLevel.daarIsDeP == true) { addObject (new PHUD(), 400, 50); } if (BeginLevel.daarIsDeJ == true) { addObject (new JHUD(), 450, 50); } if (BeginLevel.daarIsDeE == true) { addObject (new EHUD(), 500, 50); } } @Override public void act() { if (LevelSelector1.heeftT == true && BeginLevel.tIsEr == false){addObject (new THUD(), 300,50); BeginLevel.tIsEr = true; BeginLevel.daarIsDeT = true;} if (LevelSelector1.heeftO == true && BeginLevel.oIsEr == false) {addObject (new OHUD(), 350,50); BeginLevel.oIsEr = true; BeginLevel.daarIsDeO = true;} if (LevelSelector1.heeftP == true &&BeginLevel. pIsEr == false){addObject (new PHUD(), 400,50); BeginLevel.pIsEr = true; BeginLevel.daarIsDeP = true;} if (LevelSelector1.heeftJ == true && BeginLevel.jIsEr == false){addObject (new JHUD(), 450,50); BeginLevel.jIsEr = true; BeginLevel.daarIsDeJ = true;} if (LevelSelector1.heeftE == true && BeginLevel.eIsEr == false){addObject (new EHUD(), 500,50); BeginLevel.eIsEr = true; BeginLevel.daarIsDeE = true; }}}
ROCMondriaanTIN/project-greenfoot-game-TScollin
DemoWorld.java
3,659
// initialiseren van de TileEngine klasse om de map aan de world toe te voegen
line_comment
nl
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_gras.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, 17, -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, 17, -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<SUF> 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(); if (BeginLevel.daarIsDeT == true) { addObject (new THUD(), 300, 50); } if (BeginLevel.daarIsDeO == true) { addObject (new OHUD(), 350, 50); } if (BeginLevel.daarIsDeP == true) { addObject (new PHUD(), 400, 50); } if (BeginLevel.daarIsDeJ == true) { addObject (new JHUD(), 450, 50); } if (BeginLevel.daarIsDeE == true) { addObject (new EHUD(), 500, 50); } } @Override public void act() { if (LevelSelector1.heeftT == true && BeginLevel.tIsEr == false){addObject (new THUD(), 300,50); BeginLevel.tIsEr = true; BeginLevel.daarIsDeT = true;} if (LevelSelector1.heeftO == true && BeginLevel.oIsEr == false) {addObject (new OHUD(), 350,50); BeginLevel.oIsEr = true; BeginLevel.daarIsDeO = true;} if (LevelSelector1.heeftP == true &&BeginLevel. pIsEr == false){addObject (new PHUD(), 400,50); BeginLevel.pIsEr = true; BeginLevel.daarIsDeP = true;} if (LevelSelector1.heeftJ == true && BeginLevel.jIsEr == false){addObject (new JHUD(), 450,50); BeginLevel.jIsEr = true; BeginLevel.daarIsDeJ = true;} if (LevelSelector1.heeftE == true && BeginLevel.eIsEr == false){addObject (new EHUD(), 500,50); BeginLevel.eIsEr = true; BeginLevel.daarIsDeE = true; }}}
True
3,855
20
3,923
21
3,936
18
3,923
21
4,042
21
false
false
false
false
false
true
3,861
185927_6
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.gesturenav; import android.graphics.Bitmap; import android.view.KeyEvent; import android.widget.ListView; import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.gesturenav.NavigationSheetMediator.ItemProperties; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.profiles.ProfileManager; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabbed_mode.TabbedRootUiCoordinator; import org.chromium.chrome.browser.ui.RootUiCoordinator; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.R; import org.chromium.components.browser_ui.bottomsheet.BottomSheetController; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.content_public.browser.NavigationHistory; import org.chromium.content_public.browser.test.mock.MockNavigationController; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.modelutil.MVCListAdapter.ListItem; import org.chromium.ui.test.util.UiRestriction; import org.chromium.url.GURL; import java.util.concurrent.ExecutionException; /** Tests for the gesture navigation sheet. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class NavigationSheetTest { @Rule public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); private static final int INVALID_NAVIGATION_INDEX = -1; private static final int NAVIGATION_INDEX_1 = 1; private static final int NAVIGATION_INDEX_2 = 5; private static final int NAVIGATION_INDEX_3 = 9; private static final int FULL_HISTORY_ENTRY_INDEX = 13; private BottomSheetController mBottomSheetController; @Before public void setUp() throws Exception { mActivityTestRule.startMainActivityOnBlankPage(); mBottomSheetController = mActivityTestRule .getActivity() .getRootUiCoordinatorForTesting() .getBottomSheetController(); } private static class TestNavigationEntry extends NavigationEntry { public TestNavigationEntry( int index, GURL url, GURL virtualUrl, GURL originalUrl, String title, Bitmap favicon, int transition, long timestamp) { super( index, url, virtualUrl, originalUrl, title, favicon, transition, timestamp, /* isInitialEntry= */ false); } } private static class TestNavigationController extends MockNavigationController { private final NavigationHistory mHistory; private int mNavigatedIndex = INVALID_NAVIGATION_INDEX; public TestNavigationController() { mHistory = new NavigationHistory(); mHistory.addEntry( new TestNavigationEntry( NAVIGATION_INDEX_1, new GURL("about:blank"), GURL.emptyGURL(), GURL.emptyGURL(), "About Blank", null, 0, 0)); mHistory.addEntry( new TestNavigationEntry( NAVIGATION_INDEX_2, new GURL(UrlUtils.encodeHtmlDataUri("<html>1</html>")), GURL.emptyGURL(), GURL.emptyGURL(), null, null, 0, 0)); mHistory.addEntry( new TestNavigationEntry( NAVIGATION_INDEX_3, new GURL(UrlConstants.NTP_URL), GURL.emptyGURL(), GURL.emptyGURL(), null, null, 0, 0)); } @Override public NavigationHistory getDirectedNavigationHistory(boolean isForward, int itemLimit) { return mHistory; } @Override public void goToNavigationIndex(int index) { mNavigatedIndex = index; } } private class TestSheetDelegate implements NavigationSheet.Delegate { private static final int MAXIMUM_HISTORY_ITEMS = 8; private final NavigationController mNavigationController; public TestSheetDelegate(NavigationController controller) { mNavigationController = controller; } @Override public NavigationHistory getHistory(boolean forward, boolean isOffTheRecord) { NavigationHistory history = mNavigationController.getDirectedNavigationHistory( forward, MAXIMUM_HISTORY_ITEMS); if (!isOffTheRecord) { history.addEntry( new NavigationEntry( FULL_HISTORY_ENTRY_INDEX, new GURL(UrlConstants.HISTORY_URL), GURL.emptyGURL(), GURL.emptyGURL(), mActivityTestRule .getActivity() .getResources() .getString(R.string.show_full_history), null, 0, 0, /* isInitialEntry= */ false)); } return history; } @Override public void navigateToIndex(int index) { mNavigationController.goToNavigationIndex(index); } } private NavigationSheet getNavigationSheet() { RootUiCoordinator coordinator = mActivityTestRule.getActivity().getRootUiCoordinatorForTesting(); return ((TabbedRootUiCoordinator) coordinator).getNavigationSheetForTesting(); } @Test @MediumTest public void testFaviconFetching() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, false); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread( () -> { for (int i = 0; i < controller.mHistory.getEntryCount(); i++) { ListItem item = (ListItem) listview.getAdapter().getItem(i); Criteria.checkThat( i + "th element", item.model.get(ItemProperties.ICON), Matchers.notNullValue()); } }); } @Test @SmallTest public void testItemSelection() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, false); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread(() -> listview.getChildCount() >= 2); Assert.assertEquals(INVALID_NAVIGATION_INDEX, controller.mNavigatedIndex); ThreadUtils.runOnUiThreadBlocking(() -> listview.getChildAt(1).callOnClick()); CriteriaHelper.pollUiThread(sheet::isHidden); CriteriaHelper.pollUiThread( () -> { Criteria.checkThat(controller.mNavigatedIndex, Matchers.is(NAVIGATION_INDEX_2)); }); } @Test @MediumTest @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) public void testLongPressBackTriggering() { KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); ChromeTabbedActivity activity = mActivityTestRule.getActivity(); TestThreadUtils.runOnUiThreadBlocking( () -> { activity.onKeyDown(KeyEvent.KEYCODE_BACK, event); }); CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting); // Wait for the long press timeout to trigger and show the navigation popup. CriteriaHelper.pollUiThread(() -> getNavigationSheet() != null); } @Test @MediumTest @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) public void testLongPressBackAfterActivityDestroy() { KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); ChromeTabbedActivity activity = mActivityTestRule.getActivity(); TestThreadUtils.runOnUiThreadBlocking( () -> { activity.onKeyDown(KeyEvent.KEYCODE_BACK, event); // Simulate the Activity destruction after a runnable to display navigation // sheet gets delay-posted. activity.getRootUiCoordinatorForTesting().destroyActivityForTesting(); }); // Test should finish without crash. } @Test @SmallTest @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) public void testLongPressBackTriggering_Cancellation() throws ExecutionException { ChromeTabbedActivity activity = mActivityTestRule.getActivity(); TestThreadUtils.runOnUiThreadBlocking( () -> { KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); activity.onKeyDown(KeyEvent.KEYCODE_BACK, event); }); CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting); TestThreadUtils.runOnUiThreadBlocking( () -> { KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK); activity.onKeyUp(KeyEvent.KEYCODE_BACK, event); }); CriteriaHelper.pollUiThread(() -> !activity.hasPendingNavigationRunnableForTesting()); // Ensure no navigation popup is showing. Assert.assertNull(TestThreadUtils.runOnUiThreadBlocking(this::getNavigationSheet)); } @Test @MediumTest public void testFieldsForOffTheRecordProfile() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, true); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread( () -> { boolean doesNewIncognitoTabItemPresent = false; boolean doesShowFullHistoryItemPresent = false; for (int i = 0; i < controller.mHistory.getEntryCount(); i++) { ListItem item = (ListItem) listview.getAdapter().getItem(i); String label = item.model.get(ItemProperties.LABEL); String incognitoNtpText = mActivityTestRule .getActivity() .getResources() .getString(R.string.menu_new_incognito_tab); String fullHistoryText = mActivityTestRule .getActivity() .getResources() .getString(R.string.show_full_history); if (label.equals(incognitoNtpText)) { doesNewIncognitoTabItemPresent = true; } else if (label.equals(fullHistoryText)) { doesShowFullHistoryItemPresent = true; } } Assert.assertTrue(doesNewIncognitoTabItemPresent); Assert.assertFalse(doesShowFullHistoryItemPresent); }); } @Test @MediumTest public void testFieldsForRegularProfile() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, false); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread( () -> { boolean doesNewTabItemPresent = false; boolean doesShowFullHisotryItemPresent = false; for (int i = 0; i < controller.mHistory.getEntryCount(); i++) { ListItem item = (ListItem) listview.getAdapter().getItem(i); String label = item.model.get(ItemProperties.LABEL); String regularNtpText = mActivityTestRule .getActivity() .getResources() .getString(R.string.menu_new_tab); String fullHistoryText = mActivityTestRule .getActivity() .getResources() .getString(R.string.show_full_history); if (label.equals(regularNtpText)) { doesNewTabItemPresent = true; } else if (label.equals(fullHistoryText)) { doesShowFullHisotryItemPresent = true; } } Assert.assertTrue(doesNewTabItemPresent); Assert.assertTrue(doesShowFullHisotryItemPresent); }); } private NavigationSheet showPopup(NavigationController controller, boolean isOffTheRecord) throws ExecutionException { return TestThreadUtils.runOnUiThreadBlocking( () -> { Tab tab = mActivityTestRule.getActivity().getActivityTabProvider().get(); Profile profile = ProfileManager.getLastUsedRegularProfile(); if (isOffTheRecord) { profile = profile.getPrimaryOTRProfile(true); } NavigationSheet navigationSheet = NavigationSheet.create( tab.getContentView(), mActivityTestRule.getActivity(), () -> mBottomSheetController, profile); navigationSheet.setDelegate(new TestSheetDelegate(controller)); navigationSheet.startAndExpand(false, false); return navigationSheet; }); } }
nwjs/chromium.src
chrome/android/javatests/src/org/chromium/chrome/browser/gesturenav/NavigationSheetTest.java
4,214
// sheet gets delay-posted.
line_comment
nl
// Copyright 2019 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.gesturenav; import android.graphics.Bitmap; import android.view.KeyEvent; import android.widget.ListView; import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.CommandLineFlags; import org.chromium.base.test.util.Criteria; import org.chromium.base.test.util.CriteriaHelper; import org.chromium.base.test.util.Restriction; import org.chromium.base.test.util.UrlUtils; import org.chromium.chrome.browser.ChromeTabbedActivity; import org.chromium.chrome.browser.flags.ChromeSwitches; import org.chromium.chrome.browser.gesturenav.NavigationSheetMediator.ItemProperties; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.profiles.ProfileManager; import org.chromium.chrome.browser.tab.Tab; import org.chromium.chrome.browser.tabbed_mode.TabbedRootUiCoordinator; import org.chromium.chrome.browser.ui.RootUiCoordinator; import org.chromium.chrome.test.ChromeJUnit4ClassRunner; import org.chromium.chrome.test.ChromeTabbedActivityTestRule; import org.chromium.chrome.test.R; import org.chromium.components.browser_ui.bottomsheet.BottomSheetController; import org.chromium.components.embedder_support.util.UrlConstants; import org.chromium.content_public.browser.NavigationController; import org.chromium.content_public.browser.NavigationEntry; import org.chromium.content_public.browser.NavigationHistory; import org.chromium.content_public.browser.test.mock.MockNavigationController; import org.chromium.content_public.browser.test.util.TestThreadUtils; import org.chromium.ui.modelutil.MVCListAdapter.ListItem; import org.chromium.ui.test.util.UiRestriction; import org.chromium.url.GURL; import java.util.concurrent.ExecutionException; /** Tests for the gesture navigation sheet. */ @RunWith(ChromeJUnit4ClassRunner.class) @CommandLineFlags.Add({ChromeSwitches.DISABLE_FIRST_RUN_EXPERIENCE}) public class NavigationSheetTest { @Rule public ChromeTabbedActivityTestRule mActivityTestRule = new ChromeTabbedActivityTestRule(); private static final int INVALID_NAVIGATION_INDEX = -1; private static final int NAVIGATION_INDEX_1 = 1; private static final int NAVIGATION_INDEX_2 = 5; private static final int NAVIGATION_INDEX_3 = 9; private static final int FULL_HISTORY_ENTRY_INDEX = 13; private BottomSheetController mBottomSheetController; @Before public void setUp() throws Exception { mActivityTestRule.startMainActivityOnBlankPage(); mBottomSheetController = mActivityTestRule .getActivity() .getRootUiCoordinatorForTesting() .getBottomSheetController(); } private static class TestNavigationEntry extends NavigationEntry { public TestNavigationEntry( int index, GURL url, GURL virtualUrl, GURL originalUrl, String title, Bitmap favicon, int transition, long timestamp) { super( index, url, virtualUrl, originalUrl, title, favicon, transition, timestamp, /* isInitialEntry= */ false); } } private static class TestNavigationController extends MockNavigationController { private final NavigationHistory mHistory; private int mNavigatedIndex = INVALID_NAVIGATION_INDEX; public TestNavigationController() { mHistory = new NavigationHistory(); mHistory.addEntry( new TestNavigationEntry( NAVIGATION_INDEX_1, new GURL("about:blank"), GURL.emptyGURL(), GURL.emptyGURL(), "About Blank", null, 0, 0)); mHistory.addEntry( new TestNavigationEntry( NAVIGATION_INDEX_2, new GURL(UrlUtils.encodeHtmlDataUri("<html>1</html>")), GURL.emptyGURL(), GURL.emptyGURL(), null, null, 0, 0)); mHistory.addEntry( new TestNavigationEntry( NAVIGATION_INDEX_3, new GURL(UrlConstants.NTP_URL), GURL.emptyGURL(), GURL.emptyGURL(), null, null, 0, 0)); } @Override public NavigationHistory getDirectedNavigationHistory(boolean isForward, int itemLimit) { return mHistory; } @Override public void goToNavigationIndex(int index) { mNavigatedIndex = index; } } private class TestSheetDelegate implements NavigationSheet.Delegate { private static final int MAXIMUM_HISTORY_ITEMS = 8; private final NavigationController mNavigationController; public TestSheetDelegate(NavigationController controller) { mNavigationController = controller; } @Override public NavigationHistory getHistory(boolean forward, boolean isOffTheRecord) { NavigationHistory history = mNavigationController.getDirectedNavigationHistory( forward, MAXIMUM_HISTORY_ITEMS); if (!isOffTheRecord) { history.addEntry( new NavigationEntry( FULL_HISTORY_ENTRY_INDEX, new GURL(UrlConstants.HISTORY_URL), GURL.emptyGURL(), GURL.emptyGURL(), mActivityTestRule .getActivity() .getResources() .getString(R.string.show_full_history), null, 0, 0, /* isInitialEntry= */ false)); } return history; } @Override public void navigateToIndex(int index) { mNavigationController.goToNavigationIndex(index); } } private NavigationSheet getNavigationSheet() { RootUiCoordinator coordinator = mActivityTestRule.getActivity().getRootUiCoordinatorForTesting(); return ((TabbedRootUiCoordinator) coordinator).getNavigationSheetForTesting(); } @Test @MediumTest public void testFaviconFetching() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, false); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread( () -> { for (int i = 0; i < controller.mHistory.getEntryCount(); i++) { ListItem item = (ListItem) listview.getAdapter().getItem(i); Criteria.checkThat( i + "th element", item.model.get(ItemProperties.ICON), Matchers.notNullValue()); } }); } @Test @SmallTest public void testItemSelection() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, false); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread(() -> listview.getChildCount() >= 2); Assert.assertEquals(INVALID_NAVIGATION_INDEX, controller.mNavigatedIndex); ThreadUtils.runOnUiThreadBlocking(() -> listview.getChildAt(1).callOnClick()); CriteriaHelper.pollUiThread(sheet::isHidden); CriteriaHelper.pollUiThread( () -> { Criteria.checkThat(controller.mNavigatedIndex, Matchers.is(NAVIGATION_INDEX_2)); }); } @Test @MediumTest @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) public void testLongPressBackTriggering() { KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); ChromeTabbedActivity activity = mActivityTestRule.getActivity(); TestThreadUtils.runOnUiThreadBlocking( () -> { activity.onKeyDown(KeyEvent.KEYCODE_BACK, event); }); CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting); // Wait for the long press timeout to trigger and show the navigation popup. CriteriaHelper.pollUiThread(() -> getNavigationSheet() != null); } @Test @MediumTest @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) public void testLongPressBackAfterActivityDestroy() { KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); ChromeTabbedActivity activity = mActivityTestRule.getActivity(); TestThreadUtils.runOnUiThreadBlocking( () -> { activity.onKeyDown(KeyEvent.KEYCODE_BACK, event); // Simulate the Activity destruction after a runnable to display navigation // sheet gets<SUF> activity.getRootUiCoordinatorForTesting().destroyActivityForTesting(); }); // Test should finish without crash. } @Test @SmallTest @Restriction(UiRestriction.RESTRICTION_TYPE_PHONE) public void testLongPressBackTriggering_Cancellation() throws ExecutionException { ChromeTabbedActivity activity = mActivityTestRule.getActivity(); TestThreadUtils.runOnUiThreadBlocking( () -> { KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK); activity.onKeyDown(KeyEvent.KEYCODE_BACK, event); }); CriteriaHelper.pollUiThread(activity::hasPendingNavigationRunnableForTesting); TestThreadUtils.runOnUiThreadBlocking( () -> { KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK); activity.onKeyUp(KeyEvent.KEYCODE_BACK, event); }); CriteriaHelper.pollUiThread(() -> !activity.hasPendingNavigationRunnableForTesting()); // Ensure no navigation popup is showing. Assert.assertNull(TestThreadUtils.runOnUiThreadBlocking(this::getNavigationSheet)); } @Test @MediumTest public void testFieldsForOffTheRecordProfile() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, true); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread( () -> { boolean doesNewIncognitoTabItemPresent = false; boolean doesShowFullHistoryItemPresent = false; for (int i = 0; i < controller.mHistory.getEntryCount(); i++) { ListItem item = (ListItem) listview.getAdapter().getItem(i); String label = item.model.get(ItemProperties.LABEL); String incognitoNtpText = mActivityTestRule .getActivity() .getResources() .getString(R.string.menu_new_incognito_tab); String fullHistoryText = mActivityTestRule .getActivity() .getResources() .getString(R.string.show_full_history); if (label.equals(incognitoNtpText)) { doesNewIncognitoTabItemPresent = true; } else if (label.equals(fullHistoryText)) { doesShowFullHistoryItemPresent = true; } } Assert.assertTrue(doesNewIncognitoTabItemPresent); Assert.assertFalse(doesShowFullHistoryItemPresent); }); } @Test @MediumTest public void testFieldsForRegularProfile() throws ExecutionException { TestNavigationController controller = new TestNavigationController(); NavigationSheetCoordinator sheet = (NavigationSheetCoordinator) showPopup(controller, false); ListView listview = sheet.getContentView().findViewById(R.id.navigation_entries); CriteriaHelper.pollUiThread( () -> { boolean doesNewTabItemPresent = false; boolean doesShowFullHisotryItemPresent = false; for (int i = 0; i < controller.mHistory.getEntryCount(); i++) { ListItem item = (ListItem) listview.getAdapter().getItem(i); String label = item.model.get(ItemProperties.LABEL); String regularNtpText = mActivityTestRule .getActivity() .getResources() .getString(R.string.menu_new_tab); String fullHistoryText = mActivityTestRule .getActivity() .getResources() .getString(R.string.show_full_history); if (label.equals(regularNtpText)) { doesNewTabItemPresent = true; } else if (label.equals(fullHistoryText)) { doesShowFullHisotryItemPresent = true; } } Assert.assertTrue(doesNewTabItemPresent); Assert.assertTrue(doesShowFullHisotryItemPresent); }); } private NavigationSheet showPopup(NavigationController controller, boolean isOffTheRecord) throws ExecutionException { return TestThreadUtils.runOnUiThreadBlocking( () -> { Tab tab = mActivityTestRule.getActivity().getActivityTabProvider().get(); Profile profile = ProfileManager.getLastUsedRegularProfile(); if (isOffTheRecord) { profile = profile.getPrimaryOTRProfile(true); } NavigationSheet navigationSheet = NavigationSheet.create( tab.getContentView(), mActivityTestRule.getActivity(), () -> mBottomSheetController, profile); navigationSheet.setDelegate(new TestSheetDelegate(controller)); navigationSheet.startAndExpand(false, false); return navigationSheet; }); } }
False
2,722
7
3,124
7
3,352
7
3,124
7
3,974
8
false
false
false
false
false
true
2,037
25160_8
package heap.pairing; import heap.Element; import heap.EmptyHeapException; import heap.Heap; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; public class PairingHeap<T extends Comparable<T>> implements Heap<T> { PairingHeapElement<T> root; public PairingHeap() { root = null; } /** * @param value * De waarde die aan de heap moet toegevoegd worden * @return * Het toegevoegde element */ @Override public PairingHeapElement<T> insert(T value) { PairingHeapElement<T> l = new PairingHeapElement<>(value, this); if (root != null) { // Als de heap al elementen bevat: maak een nieuwe heap met het element en merge root = merge(root, l); } else { // Maak anders l het eerste element van de heap root = l; } // Geef het aangemaakte element terug return l; } /** * @return * Het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public PairingHeapElement<T> findMin() throws EmptyHeapException { if (root != null) { return root; } else { throw new EmptyHeapException(); } } /** * @return * De waarde van het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public T removeMin() throws EmptyHeapException { PairingHeapElement<T> min = findMin(); root = removeSubTree(min); return min.value(); } /** * Verwijderd de wortel van de deelboom met wortel root en geeft de nieuwe * deelboom na deze verwijderbewerking terug * @param root * De wortel van de deelboom * @return * Het resultaat van de verwijderbewerking */ PairingHeapElement<T> removeSubTree(PairingHeapElement<T> root) { // Nieuwe heap PairingHeapElement<T> result; if (root.child != null) { LinkedList<PairingHeapElement<T>> stack = new LinkedList<>(); // Van links naar rechts over kinderen verwijderd el gaan en deze 2 aan 2 mergen, daarna op stack pushen PairingHeapElement<T> curr = root.child; while (curr != null && curr.next != null) { curr.previous = null; curr.next.previous = null; PairingHeapElement<T> volg = curr.next.next; stack.push(merge(curr, curr.next)); curr = volg; } // Als het aantal kinderen oneven is, maak dit het tijdelijk resultaat if (curr != null) { result = curr; result.previous = null; } else { // Maak anders het tijdelijk resultaat het eerste element van de stack result = stack.pop(); } // Zolang stack niet leeg is pop element van stack en merge dit met resultaat while(stack.size() != 0) { PairingHeapElement<T> el1 = stack.pop(); result = merge(el1, result); } } else { result = null; } return result; } /** * Merged heap 1 met heap 2 * @param t1 * Heap 1 * @param t2 * Heap 2 * @return * De top van de nieuwe heap */ PairingHeapElement<T> merge(PairingHeapElement<T> t1, PairingHeapElement<T> t2) { if (t1 == null) { return t2; } else if(t2 == null) { return t1; } // Als t1 kleiner is dan t2 wordt t2 het linkerkind van t1 if (t1.value.compareTo(t2.value) < 0) { t2.previous = t1; t2.next = t1.child; if (t2.next != null) { t2.next.previous = t2; } t1.child = t2; return t1; } else { t1.previous = t2; t1.next = t2.child; if (t1.next != null) { t1.next.previous = t1; } t2.child = t1; return t2; } } }
amohoste/Project-Algorithms-and-Data-Structures-2
heap/pairing/PairingHeap.java
1,300
// Als het aantal kinderen oneven is, maak dit het tijdelijk resultaat
line_comment
nl
package heap.pairing; import heap.Element; import heap.EmptyHeapException; import heap.Heap; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; public class PairingHeap<T extends Comparable<T>> implements Heap<T> { PairingHeapElement<T> root; public PairingHeap() { root = null; } /** * @param value * De waarde die aan de heap moet toegevoegd worden * @return * Het toegevoegde element */ @Override public PairingHeapElement<T> insert(T value) { PairingHeapElement<T> l = new PairingHeapElement<>(value, this); if (root != null) { // Als de heap al elementen bevat: maak een nieuwe heap met het element en merge root = merge(root, l); } else { // Maak anders l het eerste element van de heap root = l; } // Geef het aangemaakte element terug return l; } /** * @return * Het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public PairingHeapElement<T> findMin() throws EmptyHeapException { if (root != null) { return root; } else { throw new EmptyHeapException(); } } /** * @return * De waarde van het kleinste element van de heap * @throws EmptyHeapException * Wanneer de heap leeg is */ @Override public T removeMin() throws EmptyHeapException { PairingHeapElement<T> min = findMin(); root = removeSubTree(min); return min.value(); } /** * Verwijderd de wortel van de deelboom met wortel root en geeft de nieuwe * deelboom na deze verwijderbewerking terug * @param root * De wortel van de deelboom * @return * Het resultaat van de verwijderbewerking */ PairingHeapElement<T> removeSubTree(PairingHeapElement<T> root) { // Nieuwe heap PairingHeapElement<T> result; if (root.child != null) { LinkedList<PairingHeapElement<T>> stack = new LinkedList<>(); // Van links naar rechts over kinderen verwijderd el gaan en deze 2 aan 2 mergen, daarna op stack pushen PairingHeapElement<T> curr = root.child; while (curr != null && curr.next != null) { curr.previous = null; curr.next.previous = null; PairingHeapElement<T> volg = curr.next.next; stack.push(merge(curr, curr.next)); curr = volg; } // Als het<SUF> if (curr != null) { result = curr; result.previous = null; } else { // Maak anders het tijdelijk resultaat het eerste element van de stack result = stack.pop(); } // Zolang stack niet leeg is pop element van stack en merge dit met resultaat while(stack.size() != 0) { PairingHeapElement<T> el1 = stack.pop(); result = merge(el1, result); } } else { result = null; } return result; } /** * Merged heap 1 met heap 2 * @param t1 * Heap 1 * @param t2 * Heap 2 * @return * De top van de nieuwe heap */ PairingHeapElement<T> merge(PairingHeapElement<T> t1, PairingHeapElement<T> t2) { if (t1 == null) { return t2; } else if(t2 == null) { return t1; } // Als t1 kleiner is dan t2 wordt t2 het linkerkind van t1 if (t1.value.compareTo(t2.value) < 0) { t2.previous = t1; t2.next = t1.child; if (t2.next != null) { t2.next.previous = t2; } t1.child = t2; return t1; } else { t1.previous = t2; t1.next = t2.child; if (t1.next != null) { t1.next.previous = t1; } t2.child = t1; return t2; } } }
True
1,056
20
1,134
22
1,156
15
1,134
22
1,314
19
false
false
false
false
false
true
318
110986_3
package org.gwlt.trailapp; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.PopupMenu; import android.widget.Toast; import java.util.ArrayList; /** * Class that represents the Main Activity of the GWLT app. This is the screen that is displayed when the user first opens the app. */ public final class MainActivity extends BaseActivity { private static ArrayList<RegionalMap> regionalMaps; // list of regional maps private Toolbar jAppToolbar; // screen's toolbar private PhotoView jPhotoView; // photo view that holds overall map @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadRegionalMaps(); setUpUIComponents(); } @Override public void setUpUIComponents() { // set screen toolbar jAppToolbar = findViewById(R.id.appToolbar); setSupportActionBar(jAppToolbar); setLearnMoreToolbar(jAppToolbar); // set up photo view with correct image resource jPhotoView = findViewById(R.id.mapPhotoView); jPhotoView.setImageResource(R.drawable.trust_lands); jPhotoView.setMaximumScale(BaseActivity.VIEW_MAX_SCALE); } /** * Creates a new RegionalMap using the provided parameters, adds it to the list of regionalMaps, and then returns it. * @param nameID - ID of string resource of the map name * @param imgID - ID of image resource of the map * @param menuID - ID of the menu resource of the map's list of properties * @return the new RegionalMap that has been created */ private RegionalMap addRegionalMap(int nameID, int imgID, int menuID) { RegionalMap newMap = new RegionalMap(getResources().getString(nameID), imgID, menuID); regionalMaps.add(newMap); return newMap; } /** * This function initializes the map list, creates new regionalMaps, and then adds properties to the new regionalMaps. */ private void loadRegionalMaps() { regionalMaps = new ArrayList<>(); RegionalMap otherProperties = addRegionalMap(R.string.otherProperties,R.drawable.trust_lands,R.menu.other_properties_map_menu); otherProperties.addProperty(this,R.string.bovenzi,R.mipmap.bovenzi,R.string.bovenziLink ); otherProperties.addProperty(this,R.string.nicksWoods,R.mipmap.nicks_woods_g_1,R.string.nicksWoodsLink ); otherProperties.addProperty(this,R.string.coesReservoir,R.mipmap.coes_reservoir,R.string.coesReservoirLink ); otherProperties.addProperty(this,R.string.crowHill,R.mipmap.crow_hill,R.string.crowHillLink ); otherProperties.addProperty(this,R.string.tetasset,R.mipmap.tetasset,R.string.tetassetLink ); otherProperties.addProperty(this,R.string.eastsidetrail,R.mipmap.east_side_trail_map_1,R.string.eastsideLink ); otherProperties.addProperty(this,R.string.broadmeadow,R.mipmap.broadmeadow,R.string.broadLink ); otherProperties.addProperty(this,R.string.sibley,R.mipmap.sibley,R.string.sibleyLink ); otherProperties.addProperty(this,R.string.elmersSeat,R.mipmap.elmers_seat,R.string.elmersLink ); otherProperties.addProperty(this,R.string.pineGlen, R.mipmap.pine_glen, R.string.pineLink); RegionalMap fourTownGreenway = addRegionalMap(R.string.fourTownGreenWayTxt, R.drawable.four_town_greenway_1, R.menu.four_town_greenway_menu); fourTownGreenway.addProperty(this, R.string.asnebumskit, R.mipmap.asnebumskit, R.string.asnebumskitLink); fourTownGreenway.addProperty(this, R.string.cascades, R.mipmap.cascades, R.string.cascadesLink); fourTownGreenway.addProperty(this, R.string.cookPond, R.mipmap.cooks_pond, R.string.cookPondLink); fourTownGreenway.addProperty(this, R.string.donkerCooksBrook, R.mipmap.donker_cooks_brook, R.string.donkerCooksLink); fourTownGreenway.addProperty(this, R.string.kinneywoods, R.mipmap.kinney_woods, R.string.kinneyLink); fourTownGreenway.addProperty(this, R.string.morelandWoods, R.mipmap.moreland_woods, R.string.morelandLink); fourTownGreenway.addProperty(this, R.string.southwickMuir, R.mipmap.southwick_muir, R.string.southwickLink); } /** * Gets the regional map with the provided name * @param name - name of desired regional map * @return the regional map with the provided name */ public static RegionalMap getRegionalMapWithName(String name) { for (RegionalMap map : regionalMaps) { if (map.getRegionName().equals(name)) return map; } return null; } /** * MainActivity must override this method in order to activate the popup menu button on the toolbar * @param menu - menu being added to the toolbar * @return true to activate menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem popupBtn = menu.findItem(R.id.popupMenu); popupBtn.setEnabled(true); popupBtn.setVisible(true); return true; } /** * MainActivity must override this method in order to provide functionality to the popup menu button on the toolbar * @param item - menu item that has been triggered * @return true to allow popup button functionality */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.popupMenu) { PopupMenu mapsMenu = new PopupMenu(this, jAppToolbar); mapsMenu.getMenuInflater().inflate(R.menu.maps_menu, mapsMenu.getMenu()); mapsMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { try { Intent mapIntent = new Intent(MainActivity.this, RegionalMapActivity.class); mapIntent.putExtra(RegionalMap.REGIONAL_MAP_NAME_ID, item.getTitle().toString()); startActivity(mapIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(MainActivity.this, "Regional map screen could not be opened.", Toast.LENGTH_LONG).show(); } return true; } }); mapsMenu.show(); return true; } else { return super.onOptionsItemSelected(item); } } }
ChamiLamelas/TrailApp
app/src/main/java/org/gwlt/trailapp/MainActivity.java
2,025
// set screen toolbar
line_comment
nl
package org.gwlt.trailapp; import android.content.ActivityNotFoundException; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.widget.PopupMenu; import android.widget.Toast; import java.util.ArrayList; /** * Class that represents the Main Activity of the GWLT app. This is the screen that is displayed when the user first opens the app. */ public final class MainActivity extends BaseActivity { private static ArrayList<RegionalMap> regionalMaps; // list of regional maps private Toolbar jAppToolbar; // screen's toolbar private PhotoView jPhotoView; // photo view that holds overall map @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); loadRegionalMaps(); setUpUIComponents(); } @Override public void setUpUIComponents() { // set screen<SUF> jAppToolbar = findViewById(R.id.appToolbar); setSupportActionBar(jAppToolbar); setLearnMoreToolbar(jAppToolbar); // set up photo view with correct image resource jPhotoView = findViewById(R.id.mapPhotoView); jPhotoView.setImageResource(R.drawable.trust_lands); jPhotoView.setMaximumScale(BaseActivity.VIEW_MAX_SCALE); } /** * Creates a new RegionalMap using the provided parameters, adds it to the list of regionalMaps, and then returns it. * @param nameID - ID of string resource of the map name * @param imgID - ID of image resource of the map * @param menuID - ID of the menu resource of the map's list of properties * @return the new RegionalMap that has been created */ private RegionalMap addRegionalMap(int nameID, int imgID, int menuID) { RegionalMap newMap = new RegionalMap(getResources().getString(nameID), imgID, menuID); regionalMaps.add(newMap); return newMap; } /** * This function initializes the map list, creates new regionalMaps, and then adds properties to the new regionalMaps. */ private void loadRegionalMaps() { regionalMaps = new ArrayList<>(); RegionalMap otherProperties = addRegionalMap(R.string.otherProperties,R.drawable.trust_lands,R.menu.other_properties_map_menu); otherProperties.addProperty(this,R.string.bovenzi,R.mipmap.bovenzi,R.string.bovenziLink ); otherProperties.addProperty(this,R.string.nicksWoods,R.mipmap.nicks_woods_g_1,R.string.nicksWoodsLink ); otherProperties.addProperty(this,R.string.coesReservoir,R.mipmap.coes_reservoir,R.string.coesReservoirLink ); otherProperties.addProperty(this,R.string.crowHill,R.mipmap.crow_hill,R.string.crowHillLink ); otherProperties.addProperty(this,R.string.tetasset,R.mipmap.tetasset,R.string.tetassetLink ); otherProperties.addProperty(this,R.string.eastsidetrail,R.mipmap.east_side_trail_map_1,R.string.eastsideLink ); otherProperties.addProperty(this,R.string.broadmeadow,R.mipmap.broadmeadow,R.string.broadLink ); otherProperties.addProperty(this,R.string.sibley,R.mipmap.sibley,R.string.sibleyLink ); otherProperties.addProperty(this,R.string.elmersSeat,R.mipmap.elmers_seat,R.string.elmersLink ); otherProperties.addProperty(this,R.string.pineGlen, R.mipmap.pine_glen, R.string.pineLink); RegionalMap fourTownGreenway = addRegionalMap(R.string.fourTownGreenWayTxt, R.drawable.four_town_greenway_1, R.menu.four_town_greenway_menu); fourTownGreenway.addProperty(this, R.string.asnebumskit, R.mipmap.asnebumskit, R.string.asnebumskitLink); fourTownGreenway.addProperty(this, R.string.cascades, R.mipmap.cascades, R.string.cascadesLink); fourTownGreenway.addProperty(this, R.string.cookPond, R.mipmap.cooks_pond, R.string.cookPondLink); fourTownGreenway.addProperty(this, R.string.donkerCooksBrook, R.mipmap.donker_cooks_brook, R.string.donkerCooksLink); fourTownGreenway.addProperty(this, R.string.kinneywoods, R.mipmap.kinney_woods, R.string.kinneyLink); fourTownGreenway.addProperty(this, R.string.morelandWoods, R.mipmap.moreland_woods, R.string.morelandLink); fourTownGreenway.addProperty(this, R.string.southwickMuir, R.mipmap.southwick_muir, R.string.southwickLink); } /** * Gets the regional map with the provided name * @param name - name of desired regional map * @return the regional map with the provided name */ public static RegionalMap getRegionalMapWithName(String name) { for (RegionalMap map : regionalMaps) { if (map.getRegionName().equals(name)) return map; } return null; } /** * MainActivity must override this method in order to activate the popup menu button on the toolbar * @param menu - menu being added to the toolbar * @return true to activate menu */ @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem popupBtn = menu.findItem(R.id.popupMenu); popupBtn.setEnabled(true); popupBtn.setVisible(true); return true; } /** * MainActivity must override this method in order to provide functionality to the popup menu button on the toolbar * @param item - menu item that has been triggered * @return true to allow popup button functionality */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.popupMenu) { PopupMenu mapsMenu = new PopupMenu(this, jAppToolbar); mapsMenu.getMenuInflater().inflate(R.menu.maps_menu, mapsMenu.getMenu()); mapsMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { try { Intent mapIntent = new Intent(MainActivity.this, RegionalMapActivity.class); mapIntent.putExtra(RegionalMap.REGIONAL_MAP_NAME_ID, item.getTitle().toString()); startActivity(mapIntent); } catch (ActivityNotFoundException ex) { Toast.makeText(MainActivity.this, "Regional map screen could not be opened.", Toast.LENGTH_LONG).show(); } return true; } }); mapsMenu.show(); return true; } else { return super.onOptionsItemSelected(item); } } }
False
1,412
4
1,738
4
1,746
4
1,738
4
1,969
4
false
false
false
false
false
true
3,185
34056_0
package org.ontoware.text2onto.gui; /** * @author Johanna Voelker (jvo@aifb.uni-karlsruhe.de) */ public interface ControllerListener { public final static int ADD = 0; public final static int REMOVE = 1; public final static int COMBINER = 2; public final static int AUXILIARY = 3; public void controllerChanged( int iMessage, String sComplex, Class algorithmClass, Class configClass ); }
jbothma/text2onto
src/org/ontoware/text2onto/gui/ControllerListener.java
139
/** * @author Johanna Voelker (jvo@aifb.uni-karlsruhe.de) */
block_comment
nl
package org.ontoware.text2onto.gui; /** * @author Johanna Voelker<SUF>*/ public interface ControllerListener { public final static int ADD = 0; public final static int REMOVE = 1; public final static int COMBINER = 2; public final static int AUXILIARY = 3; public void controllerChanged( int iMessage, String sComplex, Class algorithmClass, Class configClass ); }
False
105
22
127
30
128
27
127
30
142
29
false
false
false
false
false
true
3,324
98092_5
/* * Copyright 2004 - 2013 Wayne Grant * 2013 - 2024 Kai Kramer * * This file is part of KeyStore Explorer. * * KeyStore Explorer 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. * * KeyStore Explorer 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 KeyStore Explorer. If not, see <http://www.gnu.org/licenses/>. */ package org.kse.crypto.secretkey; public enum SecretKeyType { AES("AES", "AES", 128, 256, 64), ARC4("ARC4", "ARC4", 40, 2048, 8), BLOWFISH("BLOWFISH", "Blowfish", 32, 448, 64), CAMELLIA("CAMELLIA", "Camellia", 128, 256, 64), CHACHA("CHACHA", "ChaCha", 128, 256, 128), CAST5("CAST5", "CAST-128", 40, 128, 8), CAST6("CAST6", "CAST-256", 128, 256, 32), DES("DES", "DES", 64, 64, 1), DESEDE("DESede", "DESEDE", 128, 192, 64), GOST_28147("GOST28147", "GOST 28147-89", 256, 256, 1), GRAIN_V1("Grainv1", "Grain v1", 80, 80, 1), GRAIN_128("Grain128", "Grain-128", 128, 128, 1), HC_128("HC128", "HC-128", 128, 128, 1), HC_256("HC256", "HC-256", 256, 256, 1), HMAC_MD2("HMACMD2", "HMac-MD2", 128, 128, 1), HMAC_MD4("HMACMD4", "HMac-MD4", 128, 128, 1), HMAC_MD5("HMACMD5", "HMac-MD5", 128, 128, 1), HMAC_RIPEMD128("HMACRIPEMD128", "HMac-RipeMD128", 128, 128, 1), HMAC_RIPEMD160("HMACRIPEMD160", "HMac-RipeMD160", 160, 160, 1), HMAC_SHA1("HMACSHA1", "HMac-SHA1", 160, 160, 1), HMAC_SHA224("HMACSHA224", "HMac-SHA224", 224, 224, 1), HMAC_SHA256("HMACSHA256", "HMac-SHA256", 256, 256, 1), HMAC_SHA384("HMACSHA384", "HMac-SHA384", 384, 384, 1), HMAC_SHA512("HMACSHA512", "HMac-SHA512", 512, 512, 1), HMAC_TIGER("HMACTIGER", "HMac-Tiger", 192, 192, 1), NOEKEON("NOEKEON", "NOEKEON", 128, 128, 1), RC2("RC2", "RC2", 8, 128, 8), RC5("RC5", "RC5", 8, 2040, 8), RC6("RC6", "RC6", 128, 256, 64), RIJNDAEL("RIJNDAEL", "Rijndael", 128, 256, 32), SALSA_20("SALSA20", "Salsa20", 128, 256, 128), SERPENT("Serpent", "Serpent", 128, 256, 64), SEED("SEED", "SEED", 128, 128, 1), SKIPJACK("SKIPJACK", "Skipjack", 80, 80, 1), TEA("TEA", "TEA", 128, 128, 1), TWOFISH("Twofish", "Twofish", 128, 256, 64), THREEFISH_256("Threefish-256", "Threefish-256", 256, 256, 1), THREEFISH_512("Threefish-512", "Threefish-512", 512, 512, 1), THREEFISH_1024("Threefish-1024", "Threefish-1024", 1024, 1024, 1), XSALSA_20("XSALSA20", "XSalsa20", 128, 256, 128), XTEA("XTEA", "XTEA", 128, 128, 1); private String jce; private String friendly; private int minSize; private int maxSize; private int stepSize; SecretKeyType(String jce, String friendly, int minSize, int maxSize, int stepSize) { this.jce = jce; this.friendly = friendly; this.minSize = minSize; this.maxSize = maxSize; this.stepSize = stepSize; } /** * Get secret key type JCE name. * * @return JCE name */ public String jce() { return jce; } /** * Get secret key type friendly name. * * @return Friendly name */ public String friendly() { return friendly; } /** * Get key pair minimum size. * * @return Minimum size */ public int minSize() { return minSize; } /** * Get key pair maximum size. * * @return Maximum size */ public int maxSize() { return maxSize; } /** * Get key pair step size. * * @return Step size */ public int stepSize() { return stepSize; } /** * Resolve the supplied JCE name to a matching Secret Key type. * * @param jce JCE name * @return Secret Key type or null if none */ public static SecretKeyType resolveJce(String jce) { for (SecretKeyType secretKeyType : values()) { if (jce.equalsIgnoreCase(secretKeyType.jce())) { return secretKeyType; } } return null; } /** * Returns friendly name. * * @return Friendly name */ @Override public String toString() { return friendly(); } }
kaikramer/keystore-explorer
kse/src/main/java/org/kse/crypto/secretkey/SecretKeyType.java
1,845
/** * Get key pair step size. * * @return Step size */
block_comment
nl
/* * Copyright 2004 - 2013 Wayne Grant * 2013 - 2024 Kai Kramer * * This file is part of KeyStore Explorer. * * KeyStore Explorer 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. * * KeyStore Explorer 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 KeyStore Explorer. If not, see <http://www.gnu.org/licenses/>. */ package org.kse.crypto.secretkey; public enum SecretKeyType { AES("AES", "AES", 128, 256, 64), ARC4("ARC4", "ARC4", 40, 2048, 8), BLOWFISH("BLOWFISH", "Blowfish", 32, 448, 64), CAMELLIA("CAMELLIA", "Camellia", 128, 256, 64), CHACHA("CHACHA", "ChaCha", 128, 256, 128), CAST5("CAST5", "CAST-128", 40, 128, 8), CAST6("CAST6", "CAST-256", 128, 256, 32), DES("DES", "DES", 64, 64, 1), DESEDE("DESede", "DESEDE", 128, 192, 64), GOST_28147("GOST28147", "GOST 28147-89", 256, 256, 1), GRAIN_V1("Grainv1", "Grain v1", 80, 80, 1), GRAIN_128("Grain128", "Grain-128", 128, 128, 1), HC_128("HC128", "HC-128", 128, 128, 1), HC_256("HC256", "HC-256", 256, 256, 1), HMAC_MD2("HMACMD2", "HMac-MD2", 128, 128, 1), HMAC_MD4("HMACMD4", "HMac-MD4", 128, 128, 1), HMAC_MD5("HMACMD5", "HMac-MD5", 128, 128, 1), HMAC_RIPEMD128("HMACRIPEMD128", "HMac-RipeMD128", 128, 128, 1), HMAC_RIPEMD160("HMACRIPEMD160", "HMac-RipeMD160", 160, 160, 1), HMAC_SHA1("HMACSHA1", "HMac-SHA1", 160, 160, 1), HMAC_SHA224("HMACSHA224", "HMac-SHA224", 224, 224, 1), HMAC_SHA256("HMACSHA256", "HMac-SHA256", 256, 256, 1), HMAC_SHA384("HMACSHA384", "HMac-SHA384", 384, 384, 1), HMAC_SHA512("HMACSHA512", "HMac-SHA512", 512, 512, 1), HMAC_TIGER("HMACTIGER", "HMac-Tiger", 192, 192, 1), NOEKEON("NOEKEON", "NOEKEON", 128, 128, 1), RC2("RC2", "RC2", 8, 128, 8), RC5("RC5", "RC5", 8, 2040, 8), RC6("RC6", "RC6", 128, 256, 64), RIJNDAEL("RIJNDAEL", "Rijndael", 128, 256, 32), SALSA_20("SALSA20", "Salsa20", 128, 256, 128), SERPENT("Serpent", "Serpent", 128, 256, 64), SEED("SEED", "SEED", 128, 128, 1), SKIPJACK("SKIPJACK", "Skipjack", 80, 80, 1), TEA("TEA", "TEA", 128, 128, 1), TWOFISH("Twofish", "Twofish", 128, 256, 64), THREEFISH_256("Threefish-256", "Threefish-256", 256, 256, 1), THREEFISH_512("Threefish-512", "Threefish-512", 512, 512, 1), THREEFISH_1024("Threefish-1024", "Threefish-1024", 1024, 1024, 1), XSALSA_20("XSALSA20", "XSalsa20", 128, 256, 128), XTEA("XTEA", "XTEA", 128, 128, 1); private String jce; private String friendly; private int minSize; private int maxSize; private int stepSize; SecretKeyType(String jce, String friendly, int minSize, int maxSize, int stepSize) { this.jce = jce; this.friendly = friendly; this.minSize = minSize; this.maxSize = maxSize; this.stepSize = stepSize; } /** * Get secret key type JCE name. * * @return JCE name */ public String jce() { return jce; } /** * Get secret key type friendly name. * * @return Friendly name */ public String friendly() { return friendly; } /** * Get key pair minimum size. * * @return Minimum size */ public int minSize() { return minSize; } /** * Get key pair maximum size. * * @return Maximum size */ public int maxSize() { return maxSize; } /** * Get key pair<SUF>*/ public int stepSize() { return stepSize; } /** * Resolve the supplied JCE name to a matching Secret Key type. * * @param jce JCE name * @return Secret Key type or null if none */ public static SecretKeyType resolveJce(String jce) { for (SecretKeyType secretKeyType : values()) { if (jce.equalsIgnoreCase(secretKeyType.jce())) { return secretKeyType; } } return null; } /** * Returns friendly name. * * @return Friendly name */ @Override public String toString() { return friendly(); } }
False
1,853
20
1,883
19
1,955
23
1,883
19
2,140
23
false
false
false
false
false
true
427
131322_0
package week4.practicum3; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Hotel { private String naam; private List<Boeking> alleBoekingen = new ArrayList<Boeking>(); private List<KamerType> alleKamerTypen = new ArrayList<KamerType>(); private List<Kamer> alleKamers = new ArrayList<Kamer>(); public Hotel(String nm) { naam = nm; KamerType kt1 = new KamerType("Standaard", 2, 60.00); KamerType kt2 = new KamerType("DeLuxe", 2, 85.00); alleKamerTypen.add(kt1); alleKamerTypen.add(kt2); alleKamers.add(new Kamer(3, kt1)); alleKamers.add(new Kamer(1, kt2)); alleKamers.add(new Kamer(4, kt2)); } public int voegBoekingToe(LocalDate van, LocalDate tot, String nm, String adr, KamerType kt) { Boeking b = new Boeking(van, tot); b.setDeBoeker(new Klant(nm, adr)); Kamer beschikbareKamer = zoekBeschikbareKamer(kt, b.getAankomstDatum(), b.getVertrekDatum()); if (beschikbareKamer != null) { b.wijsKamerToe(beschikbareKamer); if (alleBoekingen.add(b)) { return beschikbareKamer.getKamerNummer(); } } System.out.println(this); return -1; } private Kamer zoekBeschikbareKamer(KamerType gezochteType, LocalDate aankomst, LocalDate vertrek) { Kamer beschikbareKamer = null; for (Kamer kamer : alleKamers) { if (kamer.getHetType().equals(gezochteType)) { if (isBeschikbaar(kamer, aankomst, vertrek)) { beschikbareKamer = kamer; break; } } } return beschikbareKamer; } private boolean isBeschikbaar(Kamer kamer, LocalDate aankomst, LocalDate vertrek) { boolean isBeschikbaar = true; for (Boeking b : alleBoekingen) { if (b.getKamer().equals(kamer)) { //bool overlap = a.start < b.end && b.start < a.end; if (aankomst.isBefore(b.getVertrekDatum()) && b.getAankomstDatum().isBefore(vertrek)) { isBeschikbaar = false; break; } } } return isBeschikbaar; } public List<KamerType> getKamerTypen() { return alleKamerTypen; } public String toString() { StringBuilder result = new StringBuilder("Boekingen van hotel " + naam + ":"); alleBoekingen.forEach(boeking -> result.append("\n\t" + boeking.toString())); return result.toString(); } }
Donneh/Java
src/week4/practicum3/Hotel.java
864
//bool overlap = a.start < b.end && b.start < a.end;
line_comment
nl
package week4.practicum3; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; public class Hotel { private String naam; private List<Boeking> alleBoekingen = new ArrayList<Boeking>(); private List<KamerType> alleKamerTypen = new ArrayList<KamerType>(); private List<Kamer> alleKamers = new ArrayList<Kamer>(); public Hotel(String nm) { naam = nm; KamerType kt1 = new KamerType("Standaard", 2, 60.00); KamerType kt2 = new KamerType("DeLuxe", 2, 85.00); alleKamerTypen.add(kt1); alleKamerTypen.add(kt2); alleKamers.add(new Kamer(3, kt1)); alleKamers.add(new Kamer(1, kt2)); alleKamers.add(new Kamer(4, kt2)); } public int voegBoekingToe(LocalDate van, LocalDate tot, String nm, String adr, KamerType kt) { Boeking b = new Boeking(van, tot); b.setDeBoeker(new Klant(nm, adr)); Kamer beschikbareKamer = zoekBeschikbareKamer(kt, b.getAankomstDatum(), b.getVertrekDatum()); if (beschikbareKamer != null) { b.wijsKamerToe(beschikbareKamer); if (alleBoekingen.add(b)) { return beschikbareKamer.getKamerNummer(); } } System.out.println(this); return -1; } private Kamer zoekBeschikbareKamer(KamerType gezochteType, LocalDate aankomst, LocalDate vertrek) { Kamer beschikbareKamer = null; for (Kamer kamer : alleKamers) { if (kamer.getHetType().equals(gezochteType)) { if (isBeschikbaar(kamer, aankomst, vertrek)) { beschikbareKamer = kamer; break; } } } return beschikbareKamer; } private boolean isBeschikbaar(Kamer kamer, LocalDate aankomst, LocalDate vertrek) { boolean isBeschikbaar = true; for (Boeking b : alleBoekingen) { if (b.getKamer().equals(kamer)) { //bool overlap<SUF> if (aankomst.isBefore(b.getVertrekDatum()) && b.getAankomstDatum().isBefore(vertrek)) { isBeschikbaar = false; break; } } } return isBeschikbaar; } public List<KamerType> getKamerTypen() { return alleKamerTypen; } public String toString() { StringBuilder result = new StringBuilder("Boekingen van hotel " + naam + ":"); alleBoekingen.forEach(boeking -> result.append("\n\t" + boeking.toString())); return result.toString(); } }
False
716
16
857
20
749
20
857
20
958
20
false
false
false
false
false
true
480
79337_10
package si.ijs.kt.clus.heuristic.hierarchical; import si.ijs.kt.clus.data.attweights.ClusAttributeWeights; import si.ijs.kt.clus.data.type.ClusAttrType.AttributeUseType; import si.ijs.kt.clus.heuristic.ClusHeuristic; import si.ijs.kt.clus.main.ClusStatManager; import si.ijs.kt.clus.main.settings.Settings; import si.ijs.kt.clus.main.settings.section.SettingsTree; import si.ijs.kt.clus.statistic.ClusStatistic; public class ClusRuleHeuristicHierarchical extends ClusHeuristic { protected ClusStatManager m_StatManager; public ClusRuleHeuristicHierarchical(ClusStatManager stat_mgr, ClusAttributeWeights prod, Settings sett) { super(sett); m_StatManager = stat_mgr; m_ClusteringWeights = prod; } /** * This heuristic calculates: * ( |S|.Var(S) - |Sr|.Var(Sr) ) . Coverage(r) */ @Override public double calcHeuristic(ClusStatistic c_tstat, ClusStatistic c_pstat, ClusStatistic missing) { double n_pos = c_pstat.getTotalWeight(); if (n_pos - SettingsTree.MINIMAL_WEIGHT < 1e-6) { // (n_pos < Settings.MINIMAL_WEIGHT) return Double.NEGATIVE_INFINITY; } // Calculate |S|.Var(S) - |Sr|.Var(Sr) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(); // Geeft classcastexception (is // blijkbaar een CombStat) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getStatistic(AttributeUseType.Target); // (is altijd // 0...) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(ClusAttrType.ATTR_USE_CLUSTERING); // double totalValue = tstat.getSS(m_TargetWeights); double totalValue = getTrainDataHeurValue(); // optimization of the previous two lines double ruleValue = c_pstat.getSVarS(m_ClusteringWeights); double value = totalValue - ruleValue; // ClusLogger.info("Difference made by rule: " + totalValue + " - " + ruleValue); // Coverage(r) part double train_sum_w = m_StatManager.getTrainSetStat(AttributeUseType.Clustering).getTotalWeight(); double coverage = (n_pos / train_sum_w); double cov_par = m_StatManager.getSettings().getRules().getHeurCoveragePar(); coverage = Math.pow(coverage, cov_par); value = value * coverage; // ClusLogger.info("Totale Heuristiek: " + value + " Coverage: " + coverage); return value; } @Override public String getName() { return "RuleHeuristicHierarchical"; } }
ElsevierSoftwareX/SOFTX-D-23-00369
ClusProject/src/main/java/si/ijs/kt/clus/heuristic/hierarchical/ClusRuleHeuristicHierarchical.java
849
// ClusLogger.info("Totale Heuristiek: " + value + " Coverage: " + coverage);
line_comment
nl
package si.ijs.kt.clus.heuristic.hierarchical; import si.ijs.kt.clus.data.attweights.ClusAttributeWeights; import si.ijs.kt.clus.data.type.ClusAttrType.AttributeUseType; import si.ijs.kt.clus.heuristic.ClusHeuristic; import si.ijs.kt.clus.main.ClusStatManager; import si.ijs.kt.clus.main.settings.Settings; import si.ijs.kt.clus.main.settings.section.SettingsTree; import si.ijs.kt.clus.statistic.ClusStatistic; public class ClusRuleHeuristicHierarchical extends ClusHeuristic { protected ClusStatManager m_StatManager; public ClusRuleHeuristicHierarchical(ClusStatManager stat_mgr, ClusAttributeWeights prod, Settings sett) { super(sett); m_StatManager = stat_mgr; m_ClusteringWeights = prod; } /** * This heuristic calculates: * ( |S|.Var(S) - |Sr|.Var(Sr) ) . Coverage(r) */ @Override public double calcHeuristic(ClusStatistic c_tstat, ClusStatistic c_pstat, ClusStatistic missing) { double n_pos = c_pstat.getTotalWeight(); if (n_pos - SettingsTree.MINIMAL_WEIGHT < 1e-6) { // (n_pos < Settings.MINIMAL_WEIGHT) return Double.NEGATIVE_INFINITY; } // Calculate |S|.Var(S) - |Sr|.Var(Sr) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(); // Geeft classcastexception (is // blijkbaar een CombStat) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getStatistic(AttributeUseType.Target); // (is altijd // 0...) // WHTDStatistic tstat = (WHTDStatistic) m_StatManager.getTrainSetStat(ClusAttrType.ATTR_USE_CLUSTERING); // double totalValue = tstat.getSS(m_TargetWeights); double totalValue = getTrainDataHeurValue(); // optimization of the previous two lines double ruleValue = c_pstat.getSVarS(m_ClusteringWeights); double value = totalValue - ruleValue; // ClusLogger.info("Difference made by rule: " + totalValue + " - " + ruleValue); // Coverage(r) part double train_sum_w = m_StatManager.getTrainSetStat(AttributeUseType.Clustering).getTotalWeight(); double coverage = (n_pos / train_sum_w); double cov_par = m_StatManager.getSettings().getRules().getHeurCoveragePar(); coverage = Math.pow(coverage, cov_par); value = value * coverage; // ClusLogger.info("Totale Heuristiek:<SUF> return value; } @Override public String getName() { return "RuleHeuristicHierarchical"; } }
False
653
24
733
26
761
24
733
26
879
27
false
false
false
false
false
true
2,165
59967_0
package gui; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import domein.Doelstellingscode; import domein.Groepsbewerking; import domein.OefeningController; import domein.Vak; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Control; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.IOException; import java.util.List; public class OefeningMakenPaneelController extends BorderPane { @FXML private Label lblTitel; @FXML private Label lblNaam; @FXML private TextField txfNaam; @FXML private Label lblOpgave; @FXML private JFXButton btnOpgaveButton; @FXML private ImageView img; @FXML private Label lblAntwoord; @FXML private TextField txtAntwoord; @FXML private Label lblFeedback; @FXML private JFXButton btnFeedbackButton; @FXML private Label lblGroepsbewerkingen; @FXML private Label lblVak; @FXML private JFXComboBox<Vak> vakDropDown; @FXML private JFXButton btnVoegOefeningToe; @FXML private JFXButton btnCancel; @FXML private AnchorPane apGroepsbewerking; @FXML private Label lblDoelstellingen; @FXML private AnchorPane apDoelstellingen; @FXML private Label lblTijdslimiet; @FXML private TextField txfTijdslimiet; private ListViewController<Groepsbewerking> lvGroepsbewerking; private ListViewController<Doelstellingscode> lvDoelstellingen; private OefeningController oefeningController; private File opgaveFile; private File feedbackFile; public OefeningMakenPaneelController(OefeningController dc) { this.oefeningController = dc; FXMLLoader loader = new FXMLLoader(getClass().getResource("OefeningMakenPaneel.fxml")); loader.setRoot(this); loader.setController(this); try { loader.load(); } catch (IOException ex) { throw new RuntimeException(ex); } buildGui(); } private void buildGui() { this.setTop(new TopBarController()); lvGroepsbewerking = new ListViewController<>(oefeningController.geefGroepsbewerkingen(), FXCollections.observableArrayList()); lvDoelstellingen = new ListViewController<>(oefeningController.geefDoelstelingscodes(), FXCollections.observableArrayList()); vakDropDown.setItems(oefeningController.geefVakken()); lvDoelstellingen.setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); lvGroepsbewerking.setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); apGroepsbewerking.getChildren().add(lvGroepsbewerking); apDoelstellingen.getChildren().add(lvDoelstellingen); txfTijdslimiet.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (!newValue.matches("\\d*")) { txfTijdslimiet.setText(newValue.replaceAll("[^\\d]", "")); } if (newValue.isEmpty()){ txfTijdslimiet.setText(Integer.toString(0)); } } }); txtAntwoord.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (!newValue.matches("\\d*")) { txtAntwoord.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML void opgaveFileChooser(ActionEvent event) { FileChooser fc = new FileChooser(); fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF file", "*.pdf")); opgaveFile = fc.showOpenDialog(null); } @FXML void feedbackFileChooser(ActionEvent event) { FileChooser fc2 = new FileChooser(); fc2.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF file", "*.pdf")); feedbackFile = fc2.showOpenDialog(null); } @FXML void VoegOefeningToe(ActionEvent event) { String naam = txfNaam.getText(); String antwoord = txtAntwoord.getText(); List<Groepsbewerking> list = lvGroepsbewerking.getLijstRight(); List<Doelstellingscode> listDoelstellingen = lvDoelstellingen.getLijstRight(); Vak vak = vakDropDown.getSelectionModel().getSelectedItem(); //int tijdLimiet = 0; try { int tijdLimiet = Integer.parseInt(txfTijdslimiet.getText()); oefeningController.createOefening(naam, opgaveFile, antwoord, feedbackFile, list, listDoelstellingen, vak, tijdLimiet); Scene s = this.getScene(); s.setRoot(new OefeningSchermController()); } catch (IllegalArgumentException ex) { AlertBox.showAlertError("Fout Oefening Toevoegen", ex.getMessage(), (Stage) this.getScene().getWindow()); } } @FXML void cancel(ActionEvent event) { Scene s = this.getScene(); s.setRoot(new OefeningSchermController(oefeningController)); } }
axeldion/BreakoutBox_Java
java-g03/src/gui/OefeningMakenPaneelController.java
1,803
//int tijdLimiet = 0;
line_comment
nl
package gui; import com.jfoenix.controls.JFXButton; import com.jfoenix.controls.JFXComboBox; import domein.Doelstellingscode; import domein.Groepsbewerking; import domein.OefeningController; import domein.Vak; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Control; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.image.ImageView; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; import javafx.stage.Stage; import java.io.File; import java.io.IOException; import java.util.List; public class OefeningMakenPaneelController extends BorderPane { @FXML private Label lblTitel; @FXML private Label lblNaam; @FXML private TextField txfNaam; @FXML private Label lblOpgave; @FXML private JFXButton btnOpgaveButton; @FXML private ImageView img; @FXML private Label lblAntwoord; @FXML private TextField txtAntwoord; @FXML private Label lblFeedback; @FXML private JFXButton btnFeedbackButton; @FXML private Label lblGroepsbewerkingen; @FXML private Label lblVak; @FXML private JFXComboBox<Vak> vakDropDown; @FXML private JFXButton btnVoegOefeningToe; @FXML private JFXButton btnCancel; @FXML private AnchorPane apGroepsbewerking; @FXML private Label lblDoelstellingen; @FXML private AnchorPane apDoelstellingen; @FXML private Label lblTijdslimiet; @FXML private TextField txfTijdslimiet; private ListViewController<Groepsbewerking> lvGroepsbewerking; private ListViewController<Doelstellingscode> lvDoelstellingen; private OefeningController oefeningController; private File opgaveFile; private File feedbackFile; public OefeningMakenPaneelController(OefeningController dc) { this.oefeningController = dc; FXMLLoader loader = new FXMLLoader(getClass().getResource("OefeningMakenPaneel.fxml")); loader.setRoot(this); loader.setController(this); try { loader.load(); } catch (IOException ex) { throw new RuntimeException(ex); } buildGui(); } private void buildGui() { this.setTop(new TopBarController()); lvGroepsbewerking = new ListViewController<>(oefeningController.geefGroepsbewerkingen(), FXCollections.observableArrayList()); lvDoelstellingen = new ListViewController<>(oefeningController.geefDoelstelingscodes(), FXCollections.observableArrayList()); vakDropDown.setItems(oefeningController.geefVakken()); lvDoelstellingen.setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); lvGroepsbewerking.setPrefSize(Control.USE_COMPUTED_SIZE, Control.USE_COMPUTED_SIZE); apGroepsbewerking.getChildren().add(lvGroepsbewerking); apDoelstellingen.getChildren().add(lvDoelstellingen); txfTijdslimiet.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (!newValue.matches("\\d*")) { txfTijdslimiet.setText(newValue.replaceAll("[^\\d]", "")); } if (newValue.isEmpty()){ txfTijdslimiet.setText(Integer.toString(0)); } } }); txtAntwoord.textProperty().addListener(new ChangeListener<String>() { @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) { if (!newValue.matches("\\d*")) { txtAntwoord.setText(newValue.replaceAll("[^\\d]", "")); } } }); } @FXML void opgaveFileChooser(ActionEvent event) { FileChooser fc = new FileChooser(); fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF file", "*.pdf")); opgaveFile = fc.showOpenDialog(null); } @FXML void feedbackFileChooser(ActionEvent event) { FileChooser fc2 = new FileChooser(); fc2.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF file", "*.pdf")); feedbackFile = fc2.showOpenDialog(null); } @FXML void VoegOefeningToe(ActionEvent event) { String naam = txfNaam.getText(); String antwoord = txtAntwoord.getText(); List<Groepsbewerking> list = lvGroepsbewerking.getLijstRight(); List<Doelstellingscode> listDoelstellingen = lvDoelstellingen.getLijstRight(); Vak vak = vakDropDown.getSelectionModel().getSelectedItem(); //int tijdLimiet<SUF> try { int tijdLimiet = Integer.parseInt(txfTijdslimiet.getText()); oefeningController.createOefening(naam, opgaveFile, antwoord, feedbackFile, list, listDoelstellingen, vak, tijdLimiet); Scene s = this.getScene(); s.setRoot(new OefeningSchermController()); } catch (IllegalArgumentException ex) { AlertBox.showAlertError("Fout Oefening Toevoegen", ex.getMessage(), (Stage) this.getScene().getWindow()); } } @FXML void cancel(ActionEvent event) { Scene s = this.getScene(); s.setRoot(new OefeningSchermController(oefeningController)); } }
False
1,305
9
1,483
11
1,488
9
1,483
11
1,758
10
false
false
false
false
false
true
546
110824_8
package tracks.levelGeneration; import java.util.Random; public class TestLevelGeneration { public static void main(String[] args) { // Available Level Generators String randomLevelGenerator = "tracks.levelGeneration.randomLevelGenerator.LevelGenerator"; String geneticGenerator = "tracks.levelGeneration.geneticLevelGenerator.LevelGenerator"; String constructiveLevelGenerator = "tracks.levelGeneration.constructiveLevelGenerator.LevelGenerator"; String gamesPath = "examples/gridphysics/"; String physicsGamesPath = "examples/contphysics/"; String generateLevelPath = gamesPath; String games[] = new String[] { "aliens", "angelsdemons", "assemblyline", "avoidgeorge", "bait", // 0-4 "beltmanager", "blacksmoke", "boloadventures", "bomber", "bomberman", // 5-9 "boulderchase", "boulderdash", "brainman", "butterflies", "cakybaky", // 10-14 "camelRace", "catapults", "chainreaction", "chase", "chipschallenge", // 15-19 "clusters", "colourescape", "chopper", "cookmepasta", "cops", // 20-24 "crossfire", "defem", "defender", "digdug", "dungeon", // 25-29 "eighthpassenger", "eggomania", "enemycitadel", "escape", "factorymanager", // 30-34 "firecaster", "fireman", "firestorms", "freeway", "frogs", // 35-39 "garbagecollector", "gymkhana", "hungrybirds", "iceandfire", "ikaruga", // 40-44 "infection", "intersection", "islands", "jaws", "killBillVol1", // 45-49 "labyrinth", "labyrinthdual", "lasers", "lasers2", "lemmings", // 50-54 "missilecommand", "modality", "overload", "pacman", "painter", // 55-59 "pokemon", "plants", "plaqueattack", "portals", "raceBet", // 60-64 "raceBet2", "realportals", "realsokoban", "rivers", "roadfighter", // 65-69 "roguelike", "run", "seaquest", "sheriff", "shipwreck", // 70-74 "sokoban", "solarfox", "superman", "surround", "survivezombies", // 75-79 "tercio", "thecitadel", "thesnowman", "waitforbreakfast", "watergame", // 80-84 "waves", "whackamole", "wildgunman", "witnessprotection", "wrapsokoban", // 85-89 "zelda", "zenpuzzle"}; //90, 91 String recordActionsFile = null;// "actions_" + games[gameIdx] + "_lvl" // + levelIdx + "_" + seed + ".txt"; // where to record the actions // executed. null if not to save. // Other settings int seed = new Random().nextInt(); int gameIdx = 11; String recordLevelFile = generateLevelPath + games[gameIdx] + "_glvl.txt"; String game = generateLevelPath + games[gameIdx] + ".txt"; // 1. This starts a game, in a generated level created by a specific level generator if(LevelGenMachine.generateOneLevel(game, constructiveLevelGenerator, recordLevelFile)){ LevelGenMachine.playOneGeneratedLevel(game, recordActionsFile, recordLevelFile, seed); } // 2. This generates numberOfLevels levels. // String levelGenerator = "tracks.levelGeneration." + args[0] + ".LevelGenerator"; // int numberOfLevels = 5; // tracks.levelGeneration.randomLevelGenerator.LevelGenerator.includeBorders = true; // String[] folderName = levelGenerator.split("\\."); // generateLevelPath = "examples/generatedLevels/" + folderName[1] + "/"; // game = gamesPath + args[1] + ".txt"; // for (int i = 0; i < numberOfLevels; i++) { // recordLevelFile = generateLevelPath + args[1] + "_lvl" + i + ".txt"; // LevelGenMachine.generateOneLevel(game, levelGenerator, recordLevelFile); //} } }
GAIGResearch/GVGAI
src/tracks/levelGeneration/TestLevelGeneration.java
1,202
// int numberOfLevels = 5;
line_comment
nl
package tracks.levelGeneration; import java.util.Random; public class TestLevelGeneration { public static void main(String[] args) { // Available Level Generators String randomLevelGenerator = "tracks.levelGeneration.randomLevelGenerator.LevelGenerator"; String geneticGenerator = "tracks.levelGeneration.geneticLevelGenerator.LevelGenerator"; String constructiveLevelGenerator = "tracks.levelGeneration.constructiveLevelGenerator.LevelGenerator"; String gamesPath = "examples/gridphysics/"; String physicsGamesPath = "examples/contphysics/"; String generateLevelPath = gamesPath; String games[] = new String[] { "aliens", "angelsdemons", "assemblyline", "avoidgeorge", "bait", // 0-4 "beltmanager", "blacksmoke", "boloadventures", "bomber", "bomberman", // 5-9 "boulderchase", "boulderdash", "brainman", "butterflies", "cakybaky", // 10-14 "camelRace", "catapults", "chainreaction", "chase", "chipschallenge", // 15-19 "clusters", "colourescape", "chopper", "cookmepasta", "cops", // 20-24 "crossfire", "defem", "defender", "digdug", "dungeon", // 25-29 "eighthpassenger", "eggomania", "enemycitadel", "escape", "factorymanager", // 30-34 "firecaster", "fireman", "firestorms", "freeway", "frogs", // 35-39 "garbagecollector", "gymkhana", "hungrybirds", "iceandfire", "ikaruga", // 40-44 "infection", "intersection", "islands", "jaws", "killBillVol1", // 45-49 "labyrinth", "labyrinthdual", "lasers", "lasers2", "lemmings", // 50-54 "missilecommand", "modality", "overload", "pacman", "painter", // 55-59 "pokemon", "plants", "plaqueattack", "portals", "raceBet", // 60-64 "raceBet2", "realportals", "realsokoban", "rivers", "roadfighter", // 65-69 "roguelike", "run", "seaquest", "sheriff", "shipwreck", // 70-74 "sokoban", "solarfox", "superman", "surround", "survivezombies", // 75-79 "tercio", "thecitadel", "thesnowman", "waitforbreakfast", "watergame", // 80-84 "waves", "whackamole", "wildgunman", "witnessprotection", "wrapsokoban", // 85-89 "zelda", "zenpuzzle"}; //90, 91 String recordActionsFile = null;// "actions_" + games[gameIdx] + "_lvl" // + levelIdx + "_" + seed + ".txt"; // where to record the actions // executed. null if not to save. // Other settings int seed = new Random().nextInt(); int gameIdx = 11; String recordLevelFile = generateLevelPath + games[gameIdx] + "_glvl.txt"; String game = generateLevelPath + games[gameIdx] + ".txt"; // 1. This starts a game, in a generated level created by a specific level generator if(LevelGenMachine.generateOneLevel(game, constructiveLevelGenerator, recordLevelFile)){ LevelGenMachine.playOneGeneratedLevel(game, recordActionsFile, recordLevelFile, seed); } // 2. This generates numberOfLevels levels. // String levelGenerator = "tracks.levelGeneration." + args[0] + ".LevelGenerator"; // int numberOfLevels<SUF> // tracks.levelGeneration.randomLevelGenerator.LevelGenerator.includeBorders = true; // String[] folderName = levelGenerator.split("\\."); // generateLevelPath = "examples/generatedLevels/" + folderName[1] + "/"; // game = gamesPath + args[1] + ".txt"; // for (int i = 0; i < numberOfLevels; i++) { // recordLevelFile = generateLevelPath + args[1] + "_lvl" + i + ".txt"; // LevelGenMachine.generateOneLevel(game, levelGenerator, recordLevelFile); //} } }
False
1,099
8
1,131
8
1,073
8
1,131
8
1,340
10
false
false
false
false
false
true
3,992
73622_1
package bank.bankieren;_x000D_ _x000D_ import centralebank.ICentraleBank;_x000D_ import fontys.observer.Publisher;_x000D_ import fontys.observer.RemotePropertyListener;_x000D_ import fontys.util.*;_x000D_ import java.rmi.RemoteException;_x000D_ _x000D_ /**_x000D_ * @author 871059_x000D_ * _x000D_ */_x000D_ public interface IBank extends Publisher, RemotePropertyListener {_x000D_ /**_x000D_ * creatie van een nieuwe bankrekening; het gegenereerde bankrekeningnummer_x000D_ * is identificerend voor de nieuwe bankrekening; als de klant_x000D_ * geidentificeerd door naam en plaats nog niet bestaat wordt er ook een_x000D_ * nieuwe klant aangemaakt_x000D_ * _x000D_ * @param naam_x000D_ * van de eigenaar van de nieuwe bankrekening_x000D_ * @param plaats_x000D_ * de woonplaats van de eigenaar van de nieuwe bankrekening_x000D_ * @return -1 zodra naam of plaats een lege string of rekeningnummer niet_x000D_ * door centrale kon worden vrijgegeven en anders het nummer van de_x000D_ * gecreeerde bankrekening_x000D_ */_x000D_ int openRekening(String naam, String plaats) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * er wordt bedrag overgemaakt van de bankrekening met nummer bron naar de_x000D_ * bankrekening met nummer bestemming_x000D_ * _x000D_ * @param bron_x000D_ * @param bestemming_x000D_ * ongelijk aan bron_x000D_ * @param bedrag_x000D_ * is groter dan 0_x000D_ * @return <b>true</b> als de overmaking is gelukt, anders <b>false</b>_x000D_ * @throws NumberDoesntExistException_x000D_ * als een van de twee bankrekeningnummers onbekend is_x000D_ */_x000D_ boolean maakOver(int bron, int bestemming, Money bedrag)_x000D_ throws NumberDoesntExistException, RemoteException;_x000D_ _x000D_ /**_x000D_ * @param nr_x000D_ * @return de bankrekening met nummer nr mits bij deze bank bekend, anders null_x000D_ */_x000D_ IRekening getRekening(int nr) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return de naam van deze bank_x000D_ */_x000D_ String getName() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Methode om de centrale bank te wijzigen_x000D_ * @throws RemoteException_x000D_ */_x000D_ void setCentraleBank(ICentraleBank centraleBank) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return Centrale bank die bij de bank hoort_x000D_ * @throws RemoteException_x000D_ */_x000D_ public ICentraleBank getCentraleBank() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void addListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void removeListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ public void muteerCentraal(int reknr, Money money) throws RemoteException;_x000D_ }_x000D_
pieter888/fontys-gso-32
BankierenNoObserver/src/bank/bankieren/IBank.java
876
/**_x000D_ * creatie van een nieuwe bankrekening; het gegenereerde bankrekeningnummer_x000D_ * is identificerend voor de nieuwe bankrekening; als de klant_x000D_ * geidentificeerd door naam en plaats nog niet bestaat wordt er ook een_x000D_ * nieuwe klant aangemaakt_x000D_ * _x000D_ * @param naam_x000D_ * van de eigenaar van de nieuwe bankrekening_x000D_ * @param plaats_x000D_ * de woonplaats van de eigenaar van de nieuwe bankrekening_x000D_ * @return -1 zodra naam of plaats een lege string of rekeningnummer niet_x000D_ * door centrale kon worden vrijgegeven en anders het nummer van de_x000D_ * gecreeerde bankrekening_x000D_ */
block_comment
nl
package bank.bankieren;_x000D_ _x000D_ import centralebank.ICentraleBank;_x000D_ import fontys.observer.Publisher;_x000D_ import fontys.observer.RemotePropertyListener;_x000D_ import fontys.util.*;_x000D_ import java.rmi.RemoteException;_x000D_ _x000D_ /**_x000D_ * @author 871059_x000D_ * _x000D_ */_x000D_ public interface IBank extends Publisher, RemotePropertyListener {_x000D_ /**_x000D_ * creatie van een<SUF>*/_x000D_ int openRekening(String naam, String plaats) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * er wordt bedrag overgemaakt van de bankrekening met nummer bron naar de_x000D_ * bankrekening met nummer bestemming_x000D_ * _x000D_ * @param bron_x000D_ * @param bestemming_x000D_ * ongelijk aan bron_x000D_ * @param bedrag_x000D_ * is groter dan 0_x000D_ * @return <b>true</b> als de overmaking is gelukt, anders <b>false</b>_x000D_ * @throws NumberDoesntExistException_x000D_ * als een van de twee bankrekeningnummers onbekend is_x000D_ */_x000D_ boolean maakOver(int bron, int bestemming, Money bedrag)_x000D_ throws NumberDoesntExistException, RemoteException;_x000D_ _x000D_ /**_x000D_ * @param nr_x000D_ * @return de bankrekening met nummer nr mits bij deze bank bekend, anders null_x000D_ */_x000D_ IRekening getRekening(int nr) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return de naam van deze bank_x000D_ */_x000D_ String getName() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Methode om de centrale bank te wijzigen_x000D_ * @throws RemoteException_x000D_ */_x000D_ void setCentraleBank(ICentraleBank centraleBank) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * @return Centrale bank die bij de bank hoort_x000D_ * @throws RemoteException_x000D_ */_x000D_ public ICentraleBank getCentraleBank() throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void addListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ _x000D_ /**_x000D_ * Voeg listener aan publisher_x000D_ * @param listener_x000D_ * @param property_x000D_ * @throws RemoteException_x000D_ * Als server niet kan worden gevonden_x000D_ */_x000D_ public void removeListener(RemotePropertyListener listener, String property) throws RemoteException;_x000D_ public void muteerCentraal(int reknr, Money money) throws RemoteException;_x000D_ }_x000D_
True
1,212
239
1,359
284
1,311
248
1,358
284
1,433
271
true
true
true
true
true
false
262
43986_1
package nl.bve.rabobank.parser; import java.io.File; import java.io.FileReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; final class TransactionParserXMLStAX implements TransactionParser { private XMLStreamReader xmlSr; TransactionParserXMLStAX(File transactionsFile) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlSr = xmlInputFactory.createXMLStreamReader(new FileReader(transactionsFile)); } @Override public Transaction nextTransaction() { try { // Een while-loop, omdat je misschien niet als eerste xml-element een 'record' tegenkomt. while (xmlSr.hasNext()) { int eventType = xmlSr.next(); if (eventType == XMLEvent.START_ELEMENT && xmlSr.getLocalName().equalsIgnoreCase("record")) { Transaction newTransaction = new Transaction(); // attribute 0, omdat het enige attribute de reference is. Mooier zou zijn om te checken of index 0 inderdaad de reference is. newTransaction.setReference(xmlSr.getAttributeValue(0)); // while-loop om in 1 keer alle gegevens van een transaction in te lezen while (xmlSr.hasNext()) { xmlSr.next(); if (xmlSr.getEventType() == XMLEvent.START_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("description")) newTransaction.setDescription(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("startBalance")) newTransaction.setStartBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("endBalance")) newTransaction.setEndBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("mutation")) newTransaction.setMutation(xmlSr.getElementText()); } if (xmlSr.getEventType() == XMLEvent.END_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("record")) { return newTransaction; } } } } } } catch (XMLStreamException ex) { ex.printStackTrace(); } return null; } }
BvEijkelenburg/RaboParser
src/main/java/nl/bve/rabobank/parser/TransactionParserXMLStAX.java
714
// attribute 0, omdat het enige attribute de reference is. Mooier zou zijn om te checken of index 0 inderdaad de reference is.
line_comment
nl
package nl.bve.rabobank.parser; import java.io.File; import java.io.FileReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.events.XMLEvent; final class TransactionParserXMLStAX implements TransactionParser { private XMLStreamReader xmlSr; TransactionParserXMLStAX(File transactionsFile) throws Exception { XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlSr = xmlInputFactory.createXMLStreamReader(new FileReader(transactionsFile)); } @Override public Transaction nextTransaction() { try { // Een while-loop, omdat je misschien niet als eerste xml-element een 'record' tegenkomt. while (xmlSr.hasNext()) { int eventType = xmlSr.next(); if (eventType == XMLEvent.START_ELEMENT && xmlSr.getLocalName().equalsIgnoreCase("record")) { Transaction newTransaction = new Transaction(); // attribute 0,<SUF> newTransaction.setReference(xmlSr.getAttributeValue(0)); // while-loop om in 1 keer alle gegevens van een transaction in te lezen while (xmlSr.hasNext()) { xmlSr.next(); if (xmlSr.getEventType() == XMLEvent.START_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("description")) newTransaction.setDescription(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("startBalance")) newTransaction.setStartBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("endBalance")) newTransaction.setEndBalance(xmlSr.getElementText()); if (xmlSr.getLocalName().equalsIgnoreCase("mutation")) newTransaction.setMutation(xmlSr.getElementText()); } if (xmlSr.getEventType() == XMLEvent.END_ELEMENT) { if (xmlSr.getLocalName().equalsIgnoreCase("record")) { return newTransaction; } } } } } } catch (XMLStreamException ex) { ex.printStackTrace(); } return null; } }
True
491
34
604
38
607
30
604
38
779
36
false
false
false
false
false
true
4,380
84667_11
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Rossmann */ public class InfoDialog extends javax.swing.JDialog { /** * Creates new form InfoDialog */ public InfoDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); jButton1.requestFocus(); } InfoDialog() { } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(204, 255, 255)); jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(51, 51, 255), 4, true)); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/undo.png"))); // NOI18N jButton1.setText("zurück"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextPane1.setText("Die Software wird in der GNU Lizenz weitergegeben.\n\nDie Software darf für beliebige Zwecke verwendet werden. \nEs besteht keinerlei Einschränkung wer und wofür dieser die Software einsetzt.\n\nDer Anwender darf den Quellcode studieren um herauszufinden, wie sie funktioniert. \nDer Quellcode ist unter https://github.com/srossmann/JAS400Browser.git zu finden.\n\nDie Software darf uneingeschränkt an andere weitergegeben werden.\n\nDer Nutzer darf die Software verändern und verbessern und diese Änderungen veröffentlichen.\n\nDer Urheber der Software wird nicht für Schäden in Anspruch genommen, die durch den Einsatz seiner Software entstehen. \nEs wird keine Garantie für den korrekten Einsatz gegeben.\n\nEs muss immer ein Hinweis auf den Urheber der Software angebracht werden. \nDies schließt auch die evtl. kommerzielle Verwendung der Software ein.\n\nUrheber:\nSigmar Roßmann\nmail : sigmar.rossmann@maker-nrw.de\nWeb : www.maker-nrw.de"); jScrollPane1.setViewportView(jTextPane1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 255, Short.MAX_VALUE) .addComponent(jButton1)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ // public static void main(String args[]) { // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> // // /* Create and display the dialog */ // java.awt.EventQueue.invokeLater(new Runnable() { // public void run() { // InfoDialog dialog = new InfoDialog(new javax.swing.JFrame(), true); // dialog.addWindowListener(new java.awt.event.WindowAdapter() { // @Override // public void windowClosing(java.awt.event.WindowEvent e) { // System.exit(0); // } // }); // dialog.setVisible(true); // } // }); // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextPane jTextPane1; // End of variables declaration//GEN-END:variables }
srossmann/JAS400Browser
src/InfoDialog.java
2,225
// * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
line_comment
nl
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Rossmann */ public class InfoDialog extends javax.swing.JDialog { /** * Creates new form InfoDialog */ public InfoDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); jButton1.requestFocus(); } InfoDialog() { } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextPane1 = new javax.swing.JTextPane(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setUndecorated(true); jPanel1.setBackground(new java.awt.Color(204, 255, 255)); jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(51, 51, 255), 4, true)); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icon/undo.png"))); // NOI18N jButton1.setText("zurück"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTextPane1.setText("Die Software wird in der GNU Lizenz weitergegeben.\n\nDie Software darf für beliebige Zwecke verwendet werden. \nEs besteht keinerlei Einschränkung wer und wofür dieser die Software einsetzt.\n\nDer Anwender darf den Quellcode studieren um herauszufinden, wie sie funktioniert. \nDer Quellcode ist unter https://github.com/srossmann/JAS400Browser.git zu finden.\n\nDie Software darf uneingeschränkt an andere weitergegeben werden.\n\nDer Nutzer darf die Software verändern und verbessern und diese Änderungen veröffentlichen.\n\nDer Urheber der Software wird nicht für Schäden in Anspruch genommen, die durch den Einsatz seiner Software entstehen. \nEs wird keine Garantie für den korrekten Einsatz gegeben.\n\nEs muss immer ein Hinweis auf den Urheber der Software angebracht werden. \nDies schließt auch die evtl. kommerzielle Verwendung der Software ein.\n\nUrheber:\nSigmar Roßmann\nmail : sigmar.rossmann@maker-nrw.de\nWeb : www.maker-nrw.de"); jScrollPane1.setViewportView(jTextPane1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(0, 255, Short.MAX_VALUE) .addComponent(jButton1)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ // public static void main(String args[]) { // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details<SUF> // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(InfoDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> // // /* Create and display the dialog */ // java.awt.EventQueue.invokeLater(new Runnable() { // public void run() { // InfoDialog dialog = new InfoDialog(new javax.swing.JFrame(), true); // dialog.addWindowListener(new java.awt.event.WindowAdapter() { // @Override // public void windowClosing(java.awt.event.WindowEvent e) { // System.exit(0); // } // }); // dialog.setVisible(true); // } // }); // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextPane jTextPane1; // End of variables declaration//GEN-END:variables }
False
1,450
25
1,874
31
1,818
31
1,874
31
2,167
31
false
false
false
false
false
true
4,512
106314_4
package com.oracle.javaee7.samples.batch.simple; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.JobExecution; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.util.Properties; @Named @Dependent public class JobReceiverBean { // private static final String JOBNAME = "PayrollJob"; // // public void startbatch(String movements, String insertDate) // { // if (movements == null || insertDate == null) // { // return; // } // // ////////////////////// TODO FIX //////////////////////////////////// // //movements="/home/tijs/Downloads/verpl_systeem/verplaatsingen_20110209_small.xml"; // //movements="/home/tijs/Dropbox/S6Project/PTS ESD/SUMO-OSM files/generated files Tijs/movement_vehicle_gen_t0.xml"; // Properties props = new Properties(); // props.setProperty("inputfile", movements); // props.setProperty("basedate", insertDate); // //insertDate // //////////////////////////////////////////////////////////////////// // try // { // JobOperator jobOperator = BatchRuntime.getJobOperator(); // // for (String job : jobOperator.getJobNames()) // { // System.out.println("EXISTING JOB: " + job); // } // // System.out.println("Starting batch via servlet"); // long executionID = jobOperator.start(JOBNAME, props); // // Thread.sleep(300); // // System.out.println("Job with ID " + executionID + " started"); // JobExecution jobExec = jobOperator.getJobExecution(executionID); // String status = jobExec.getBatchStatus().toString(); // System.out.println("Job status: " + status); // } // catch (Exception ex) // { // ex.printStackTrace(); // } // } }
tijsmaas/ROAD
MovementMapper/src/main/java/com/oracle/javaee7/samples/batch/simple/JobReceiverBean.java
537
// //movements="/home/tijs/Dropbox/S6Project/PTS ESD/SUMO-OSM files/generated files Tijs/movement_vehicle_gen_t0.xml";
line_comment
nl
package com.oracle.javaee7.samples.batch.simple; import javax.batch.operations.JobOperator; import javax.batch.runtime.BatchRuntime; import javax.batch.runtime.JobExecution; import javax.enterprise.context.Dependent; import javax.inject.Named; import java.util.Properties; @Named @Dependent public class JobReceiverBean { // private static final String JOBNAME = "PayrollJob"; // // public void startbatch(String movements, String insertDate) // { // if (movements == null || insertDate == null) // { // return; // } // // ////////////////////// TODO FIX //////////////////////////////////// // //movements="/home/tijs/Downloads/verpl_systeem/verplaatsingen_20110209_small.xml"; // //movements="/home/tijs/Dropbox/S6Project/PTS ESD/SUMO-OSM<SUF> // Properties props = new Properties(); // props.setProperty("inputfile", movements); // props.setProperty("basedate", insertDate); // //insertDate // //////////////////////////////////////////////////////////////////// // try // { // JobOperator jobOperator = BatchRuntime.getJobOperator(); // // for (String job : jobOperator.getJobNames()) // { // System.out.println("EXISTING JOB: " + job); // } // // System.out.println("Starting batch via servlet"); // long executionID = jobOperator.start(JOBNAME, props); // // Thread.sleep(300); // // System.out.println("Job with ID " + executionID + " started"); // JobExecution jobExec = jobOperator.getJobExecution(executionID); // String status = jobExec.getBatchStatus().toString(); // System.out.println("Job status: " + status); // } // catch (Exception ex) // { // ex.printStackTrace(); // } // } }
False
417
39
514
45
504
42
514
45
539
51
false
false
false
false
false
true
666
7850_29
package nl.hanze.itann.ttt; // deze import hebben we nodig voor gebruikersinput – let daar maar niet op. import java.util.Scanner; /* EEN EXTRA VOORBEELD BIJ §7.6 VAN BLUEJ EDITIE 6: MULTI-DIMENSIONALE ARRAYS; Een multi-dimensionale array kun je het beste vergelijken met een spelbord. Dit is meestal een systeem waarbij coördinaten als (X,Y) kunnen worden weergegeven – denk aan een schaakbord waarbij je de positie van stukken weergeeft als bijvoorbeeld 'H3'. Om dit om een wat eenvoudiger manier duidelijk te maken, is onderstaand spel 'boter kaas en eieren' uitgeprogrammeerd. Dit heeft een bord als volgt: +------+------+------+ | (0,0 | (1,0 | (2,0 | +------+------+------+ | (0,1 | (1,1 | (2,1 | +------+------+------+ | (0,2 | (1,2 | (2,2 | +------+------+------+ Je ziet hier twee arrays lopen: één voor de X en één voor de Y. Beide lopen van 0 tot 2 (drie elementen). In de code wordt dit in het private veld 'board' bijgehouden, waarvan het data-type een twee-dimensionale array van char's is: private char[3][3] board ^ ^ | | X ----------- --------Y Je kunt dit spel spelen door het op te starten en dan de coördinaten in te vullen wanneer het programma daar om vraagt: als ik bijvoorbeeld een X wil zetten op het rechtsmiddelste vakje, typ ik 2,1 (zonder haakjes). Er is een minimale check op de input, want het gaat niet om een correcte werking; als het stuk gaat door een verkeerde input kun je vast wel bedenken waarom. Bestudeer de programmacode en het commentaar dat er tussendoor gegeven is. */ public class BoterKaasEieren { public static void main(String[] args) { new BoterKaasEieren(); } // Dit is het interessante veld. Een twee-dimensionale array die het speelveld bijhoudt. private char[][] board; // De huidige speler. Dit is ofwel een 'X' of een 'O' private char currentPlayerMark; //constructor public BoterKaasEieren() { board = new char[3][3]; currentPlayerMark = 'X'; initializeBoard(); playGame(); } // Dit is feitelijk de 'main loop'. Dit ding blijft lopen totdat het bord vol is // of er een winnaar is. private void playGame() { //De regels hieronder is om user-input op te vangen. Maak je daar niet druk om. //Van belang is dat de input wordt opgeslagen in de variable 'input'. Scanner reader = new Scanner(System.in); String input = ""; //De onderstaande loop wordt uitgevoerd zolang 'gameNotFinished' geen 'false' //teruggeeft (hoe heet zo'n conditie?). Dat kan omdat er in die loop een methode //wordt aangeroepen die de boel blokkeert tot iemand een input heeft gegeven. while (gameNotFinished()) { //we printen elke keer de nieuwe status van het speelbord even uit printBoard(); changePlayer(); // Hier geven we aan wie er aan de beurt is en wat hij/zij moet invullen. System.out.println("De beurt in aan "+currentPlayerMark); System.out.println("Geef positie op (x,y): "); //Deze methode blijft wachten totdat de gebruiker iets heeft ingeveoerd. //Hierom kunnen we deze loop laten blijven lopen zonder dat er continu //dingen op het scherm verschijnen. input = reader.next(); //We maken een array van Strings van de input – check de API van de string: // https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) String[] coords = input.split(","); placeMark(coords); } // Even het winnende bord afdrukken printBoard(); //als we hier komen, hebben we die reader niet meer nodig, en het is wel netjes om //die even expliciet te sluiten. reader.close(); } private boolean placeMark(String[] coords) { //We gaan er even van uit dat er in de input twee getallen zijn gegeven. int col = Integer.parseInt(coords[0]); int row = Integer.parseInt(coords[1]); //Let op hoe we opnieuw door een twee-dimensionale array lopen if ((row >= 0) && (row < 3)) { if ((col >= 0) && (col < 3)) { if (board[row][col] == '-') { board[row][col] = currentPlayerMark; return true; } } } return false; } //Hier initialiseren we de twee-dimensionale array. We hebben dus twee for-lussen nodig: //voor elke array eentje. De variabel i loopt van 0 tot 2, net als de variabele j (dat //klopt ook, want we hebben dat ding geïnitialiseerd op char[3][3]). private void initializeBoard() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = '-'; // initieel is elk element een '-' } } //Even voor het gemak de exacte coördinaten weergeven printBoardCoords(); } private void changePlayer() { // hoe heet deze constructie? currentPlayerMark = (currentPlayerMark=='X') ? 'O' : 'X'; } private boolean gameNotFinished() { return !(isBoardFull() || checkForWin()); } private void printBoard() { System.out.println("+---+---+---+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " | "); } System.out.println(); System.out.println("+---+---+---+"); } } private void printBoardCoords() { System.out.println("Vul de coördinaten in zonder haakjes, gescheiden door een komma."); System.out.println("De coördinaten in het bord zijn als volgt:"); System.out.println("+-------+-------+-------+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print("(" +j+","+i + ") | "); } System.out.println(); System.out.println("+-------+-------+-------+"); } } //Opnieuw hebben we hier een dubbele for-lus nodig, om door beide arrays heen te //loopen. We checken hier nu voor elk element wat er exact is zit, en als er nog ergens //een '-' voorkomt, is het bord nog niet vol (want initieel hebben we het bord volgezet //met een '-', in de methode initializeBoard) private boolean isBoardFull() { boolean isFull = true; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { isFull = false; //welke optimalisatie is hier nog mogelijk? } } } if (isFull) { System.out.println("Het bord is vol; eind van het spel."); return true; } return false; } // voor de rest: nevermind private boolean checkForWin() { if (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin()) { System.out.println("We hebben een winnaar: " +currentPlayerMark); return true; } return false; } private boolean checkRowsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[i][0], board[i][1], board[i][2]) == true) { return true; } } return false; } private boolean checkColumnsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[0][i], board[1][i], board[2][i]) == true) { return true; } } return false; } private boolean checkDiagonalsForWin() { return ((checkRowCol(board[0][0], board[1][1], board[2][2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2][0]) == true)); } private boolean checkRowCol(char c1, char c2, char c3) { return ((c1 != '-') && (c1 == c2) && (c2 == c3)); } }
Hanzehogeschool-hbo-ict/boterkaaseieren
BoterKaasEieren.java
2,599
//loopen. We checken hier nu voor elk element wat er exact is zit, en als er nog ergens
line_comment
nl
package nl.hanze.itann.ttt; // deze import hebben we nodig voor gebruikersinput – let daar maar niet op. import java.util.Scanner; /* EEN EXTRA VOORBEELD BIJ §7.6 VAN BLUEJ EDITIE 6: MULTI-DIMENSIONALE ARRAYS; Een multi-dimensionale array kun je het beste vergelijken met een spelbord. Dit is meestal een systeem waarbij coördinaten als (X,Y) kunnen worden weergegeven – denk aan een schaakbord waarbij je de positie van stukken weergeeft als bijvoorbeeld 'H3'. Om dit om een wat eenvoudiger manier duidelijk te maken, is onderstaand spel 'boter kaas en eieren' uitgeprogrammeerd. Dit heeft een bord als volgt: +------+------+------+ | (0,0 | (1,0 | (2,0 | +------+------+------+ | (0,1 | (1,1 | (2,1 | +------+------+------+ | (0,2 | (1,2 | (2,2 | +------+------+------+ Je ziet hier twee arrays lopen: één voor de X en één voor de Y. Beide lopen van 0 tot 2 (drie elementen). In de code wordt dit in het private veld 'board' bijgehouden, waarvan het data-type een twee-dimensionale array van char's is: private char[3][3] board ^ ^ | | X ----------- --------Y Je kunt dit spel spelen door het op te starten en dan de coördinaten in te vullen wanneer het programma daar om vraagt: als ik bijvoorbeeld een X wil zetten op het rechtsmiddelste vakje, typ ik 2,1 (zonder haakjes). Er is een minimale check op de input, want het gaat niet om een correcte werking; als het stuk gaat door een verkeerde input kun je vast wel bedenken waarom. Bestudeer de programmacode en het commentaar dat er tussendoor gegeven is. */ public class BoterKaasEieren { public static void main(String[] args) { new BoterKaasEieren(); } // Dit is het interessante veld. Een twee-dimensionale array die het speelveld bijhoudt. private char[][] board; // De huidige speler. Dit is ofwel een 'X' of een 'O' private char currentPlayerMark; //constructor public BoterKaasEieren() { board = new char[3][3]; currentPlayerMark = 'X'; initializeBoard(); playGame(); } // Dit is feitelijk de 'main loop'. Dit ding blijft lopen totdat het bord vol is // of er een winnaar is. private void playGame() { //De regels hieronder is om user-input op te vangen. Maak je daar niet druk om. //Van belang is dat de input wordt opgeslagen in de variable 'input'. Scanner reader = new Scanner(System.in); String input = ""; //De onderstaande loop wordt uitgevoerd zolang 'gameNotFinished' geen 'false' //teruggeeft (hoe heet zo'n conditie?). Dat kan omdat er in die loop een methode //wordt aangeroepen die de boel blokkeert tot iemand een input heeft gegeven. while (gameNotFinished()) { //we printen elke keer de nieuwe status van het speelbord even uit printBoard(); changePlayer(); // Hier geven we aan wie er aan de beurt is en wat hij/zij moet invullen. System.out.println("De beurt in aan "+currentPlayerMark); System.out.println("Geef positie op (x,y): "); //Deze methode blijft wachten totdat de gebruiker iets heeft ingeveoerd. //Hierom kunnen we deze loop laten blijven lopen zonder dat er continu //dingen op het scherm verschijnen. input = reader.next(); //We maken een array van Strings van de input – check de API van de string: // https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) String[] coords = input.split(","); placeMark(coords); } // Even het winnende bord afdrukken printBoard(); //als we hier komen, hebben we die reader niet meer nodig, en het is wel netjes om //die even expliciet te sluiten. reader.close(); } private boolean placeMark(String[] coords) { //We gaan er even van uit dat er in de input twee getallen zijn gegeven. int col = Integer.parseInt(coords[0]); int row = Integer.parseInt(coords[1]); //Let op hoe we opnieuw door een twee-dimensionale array lopen if ((row >= 0) && (row < 3)) { if ((col >= 0) && (col < 3)) { if (board[row][col] == '-') { board[row][col] = currentPlayerMark; return true; } } } return false; } //Hier initialiseren we de twee-dimensionale array. We hebben dus twee for-lussen nodig: //voor elke array eentje. De variabel i loopt van 0 tot 2, net als de variabele j (dat //klopt ook, want we hebben dat ding geïnitialiseerd op char[3][3]). private void initializeBoard() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = '-'; // initieel is elk element een '-' } } //Even voor het gemak de exacte coördinaten weergeven printBoardCoords(); } private void changePlayer() { // hoe heet deze constructie? currentPlayerMark = (currentPlayerMark=='X') ? 'O' : 'X'; } private boolean gameNotFinished() { return !(isBoardFull() || checkForWin()); } private void printBoard() { System.out.println("+---+---+---+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " | "); } System.out.println(); System.out.println("+---+---+---+"); } } private void printBoardCoords() { System.out.println("Vul de coördinaten in zonder haakjes, gescheiden door een komma."); System.out.println("De coördinaten in het bord zijn als volgt:"); System.out.println("+-------+-------+-------+"); for (int i = 0; i < 3; i++) { System.out.print("| "); for (int j = 0; j < 3; j++) { System.out.print("(" +j+","+i + ") | "); } System.out.println(); System.out.println("+-------+-------+-------+"); } } //Opnieuw hebben we hier een dubbele for-lus nodig, om door beide arrays heen te //loopen. We<SUF> //een '-' voorkomt, is het bord nog niet vol (want initieel hebben we het bord volgezet //met een '-', in de methode initializeBoard) private boolean isBoardFull() { boolean isFull = true; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (board[i][j] == '-') { isFull = false; //welke optimalisatie is hier nog mogelijk? } } } if (isFull) { System.out.println("Het bord is vol; eind van het spel."); return true; } return false; } // voor de rest: nevermind private boolean checkForWin() { if (checkRowsForWin() || checkColumnsForWin() || checkDiagonalsForWin()) { System.out.println("We hebben een winnaar: " +currentPlayerMark); return true; } return false; } private boolean checkRowsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[i][0], board[i][1], board[i][2]) == true) { return true; } } return false; } private boolean checkColumnsForWin() { for (int i = 0; i < 3; i++) { if (checkRowCol(board[0][i], board[1][i], board[2][i]) == true) { return true; } } return false; } private boolean checkDiagonalsForWin() { return ((checkRowCol(board[0][0], board[1][1], board[2][2]) == true) || (checkRowCol(board[0][2], board[1][1], board[2][0]) == true)); } private boolean checkRowCol(char c1, char c2, char c3) { return ((c1 != '-') && (c1 == c2) && (c2 == c3)); } }
True
2,245
25
2,567
28
2,357
24
2,567
28
2,826
26
false
false
false
false
false
true
171
17292_2
/* * Copyright (C) 2016 - 2017 B3Partners B.V. * * 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 Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.topnl; import org.locationtech.jts.io.ParseException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.SAXException; /** * * @author Meine Toonen meinetoonen@b3partners.nl */ public class Main { protected final static Log log = LogFactory.getLog(Main.class); // voeg deze dependency toe als je wilt draaien // <dependency> // <groupId>org.apache.commons</groupId> // <artifactId>commons-dbcp2</artifactId> // </dependency> public static void main (String[] args) throws Exception{ try { BasicDataSource ds = new BasicDataSource(); ds.setUrl("jdbc:postgresql://localhost:5432/topnl"); ds.setDriverClassName("org.postgresql.Driver"); // ds.setUsername("rsgb"); // ds.setPassword("rsgb"); // ds.setUrl("jdbc:oracle:thin:@b3p-demoserver:1521/ORCL"); // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUsername("top50nl"); // ds.setPassword("top50nl"); Processor p = new Processor(ds); // loadtopnl("/mnt/data/Documents/TopNL/Top50NL/TOP50NL_GML_Filechunks_november_2016/TOP50NL_GML_Filechunks", p, TopNLType.TOP50NL); //loadtopnl("/mnt/data/Documents/TopNL/Top10NL/TOP10NL_GML_Filechuncks_november_2016/TOP10NL_GML_Filechuncks", p, TopNLType.TOP10NL); loadtopnl("/mnt/data/Documents/TopNL/Tynaarlo/Top10NL", p, TopNLType.TOP10NL); //loadtopnl("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks", p, TopNLType.TOP100NL); //process("top250NL.gml", p); //process("Hoogte_top250nl.xml", TopNLType.TOP250NL, p); //process("Hoogte_top100nl.xml", TopNLType.TOP100NL, p); } catch (SAXException | ParserConfigurationException | TransformerException ex) { log.error("Cannot parse/convert/save entity: ", ex); } } private static void loadtopnl(String dir, Processor p, TopNLType type) throws Exception{ File f = new File (dir); FilenameFilter filter = (dir1, name) -> name.toLowerCase().endsWith(".gml"); /*File f = new File("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks/Top100NL_000002.gml"); p.importIntoDb(f.toURL(), TopNLType.TOP100NL);*/ File[] files = f.listFiles(filter); for (File file : files) { // String fileString = file.getCanonicalPath(); p.importIntoDb(file.toURI().toURL(), type); } } private static void process(String file, Processor p, TopNLType type) throws Exception { URL in = Main.class.getResource(file); p.importIntoDb(in, type); /* List obj = p.parse(in, type); List<TopNLEntity> entities = p.convert(obj, type); p.save(entities, type);*/ } }
B3Partners/brmo
brmo-topnl-loader/src/src-main/java/nl/b3p/topnl/Main.java
1,299
// voeg deze dependency toe als je wilt draaien
line_comment
nl
/* * Copyright (C) 2016 - 2017 B3Partners B.V. * * 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 Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.topnl; import org.locationtech.jts.io.ParseException; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.URL; import java.sql.SQLException; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.xml.sax.SAXException; /** * * @author Meine Toonen meinetoonen@b3partners.nl */ public class Main { protected final static Log log = LogFactory.getLog(Main.class); // voeg deze<SUF> // <dependency> // <groupId>org.apache.commons</groupId> // <artifactId>commons-dbcp2</artifactId> // </dependency> public static void main (String[] args) throws Exception{ try { BasicDataSource ds = new BasicDataSource(); ds.setUrl("jdbc:postgresql://localhost:5432/topnl"); ds.setDriverClassName("org.postgresql.Driver"); // ds.setUsername("rsgb"); // ds.setPassword("rsgb"); // ds.setUrl("jdbc:oracle:thin:@b3p-demoserver:1521/ORCL"); // ds.setDriverClassName("oracle.jdbc.driver.OracleDriver"); // ds.setUsername("top50nl"); // ds.setPassword("top50nl"); Processor p = new Processor(ds); // loadtopnl("/mnt/data/Documents/TopNL/Top50NL/TOP50NL_GML_Filechunks_november_2016/TOP50NL_GML_Filechunks", p, TopNLType.TOP50NL); //loadtopnl("/mnt/data/Documents/TopNL/Top10NL/TOP10NL_GML_Filechuncks_november_2016/TOP10NL_GML_Filechuncks", p, TopNLType.TOP10NL); loadtopnl("/mnt/data/Documents/TopNL/Tynaarlo/Top10NL", p, TopNLType.TOP10NL); //loadtopnl("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks", p, TopNLType.TOP100NL); //process("top250NL.gml", p); //process("Hoogte_top250nl.xml", TopNLType.TOP250NL, p); //process("Hoogte_top100nl.xml", TopNLType.TOP100NL, p); } catch (SAXException | ParserConfigurationException | TransformerException ex) { log.error("Cannot parse/convert/save entity: ", ex); } } private static void loadtopnl(String dir, Processor p, TopNLType type) throws Exception{ File f = new File (dir); FilenameFilter filter = (dir1, name) -> name.toLowerCase().endsWith(".gml"); /*File f = new File("/mnt/data/Documents/TopNL/TOP100NL_GML_Filechunks_november_2016/TOP100NL_GML_Filechunks/Top100NL_000002.gml"); p.importIntoDb(f.toURL(), TopNLType.TOP100NL);*/ File[] files = f.listFiles(filter); for (File file : files) { // String fileString = file.getCanonicalPath(); p.importIntoDb(file.toURI().toURL(), type); } } private static void process(String file, Processor p, TopNLType type) throws Exception { URL in = Main.class.getResource(file); p.importIntoDb(in, type); /* List obj = p.parse(in, type); List<TopNLEntity> entities = p.convert(obj, type); p.save(entities, type);*/ } }
True
1,046
12
1,202
14
1,238
11
1,202
14
1,361
13
false
false
false
false
false
true
1,176
20905_1
/* * Copyright 2013 Netherlands eScience Center * * 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.esciencecenter.eastroviz.flaggers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Wanneer je informatie hebt in frequentierichting zou je ook kunnen overwegen om (iteratief?) te "smoothen" in die richting: dus eerst een eerste ongevoelige (sum)threshold om de grootste pieken eruit te halen, dan een lowpass filter (e.g. 1d Gaussian convolution) op de frequentierichting uitvoeren, thresholden+smoothen nogmaals herhalen op het verschil en dan een laatste keer sumthresholden. Daardoor "vergelijk" je kanalen onderling en wordt je ook gevoeliger voor veranderingen niet-broadband RFI. Wanneer je een "absolute" sumthreshold "broadband" detector + de gesmoothde spectrale detector combineert is dit is erg effectief, denk ik. Dit is natuurlijk een geavanceerdere thresholder en vast niet het eerste algoritme wat je wilt implementeren -- ik weet uberhaubt niet of het technisch mogelijk is op de blue gene, maar het is een idee. Het is niet zoo zwaar om dit te doen. */ public class PostCorrelationSmoothedSumThresholdFlagger extends PostCorrelationSumThresholdFlagger { private static final Logger logger = LoggerFactory.getLogger(PostCorrelationSumThresholdFlagger.class); public PostCorrelationSmoothedSumThresholdFlagger(final int nrChannels, final float baseSensitivity, final float SIREtaValue) { super(nrChannels, baseSensitivity, SIREtaValue); } // we have the data for one second, all frequencies in a subband. // if one of the polarizations exceeds the threshold, flag them all. @Override protected void flag(final float[] powers, final boolean[] flagged, final int pol) { calculateStatistics(powers, flagged); // sets mean, median, stdDev logger.trace("mean = " + getMean() + ", median = " + getMedian() + ", stdDev = " + getStdDev()); // first do an insensitive sumthreshold final float originalSensitivity = getBaseSensitivity(); setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(powers, flagged); // sets flags, and replaces flagged samples with threshold // smooth final float[] smoothedPower = oneDimensionalGausConvolution(powers, 0.5f); // 2nd param is sigma, heigth of the gauss curve // calculate difference final float[] diff = new float[getNrChannels()]; for (int i = 0; i < getNrChannels(); i++) { diff[i] = powers[i] - smoothedPower[i]; } // flag based on difference calculateStatistics(diff, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(diff, flagged); // and one final pass on the flagged power calculateStatistics(powers, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 0.80f); // higher number is less sensitive! sumThreshold1D(powers, flagged); setBaseSensitivity(originalSensitivity); } }
NLeSC/eAstroViz
src/nl/esciencecenter/eastroviz/flaggers/PostCorrelationSmoothedSumThresholdFlagger.java
1,038
/* Wanneer je informatie hebt in frequentierichting zou je ook kunnen overwegen om (iteratief?) te "smoothen" in die richting: dus eerst een eerste ongevoelige (sum)threshold om de grootste pieken eruit te halen, dan een lowpass filter (e.g. 1d Gaussian convolution) op de frequentierichting uitvoeren, thresholden+smoothen nogmaals herhalen op het verschil en dan een laatste keer sumthresholden. Daardoor "vergelijk" je kanalen onderling en wordt je ook gevoeliger voor veranderingen niet-broadband RFI. Wanneer je een "absolute" sumthreshold "broadband" detector + de gesmoothde spectrale detector combineert is dit is erg effectief, denk ik. Dit is natuurlijk een geavanceerdere thresholder en vast niet het eerste algoritme wat je wilt implementeren -- ik weet uberhaubt niet of het technisch mogelijk is op de blue gene, maar het is een idee. Het is niet zoo zwaar om dit te doen. */
block_comment
nl
/* * Copyright 2013 Netherlands eScience Center * * 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.esciencecenter.eastroviz.flaggers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Wanneer je informatie<SUF>*/ public class PostCorrelationSmoothedSumThresholdFlagger extends PostCorrelationSumThresholdFlagger { private static final Logger logger = LoggerFactory.getLogger(PostCorrelationSumThresholdFlagger.class); public PostCorrelationSmoothedSumThresholdFlagger(final int nrChannels, final float baseSensitivity, final float SIREtaValue) { super(nrChannels, baseSensitivity, SIREtaValue); } // we have the data for one second, all frequencies in a subband. // if one of the polarizations exceeds the threshold, flag them all. @Override protected void flag(final float[] powers, final boolean[] flagged, final int pol) { calculateStatistics(powers, flagged); // sets mean, median, stdDev logger.trace("mean = " + getMean() + ", median = " + getMedian() + ", stdDev = " + getStdDev()); // first do an insensitive sumthreshold final float originalSensitivity = getBaseSensitivity(); setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(powers, flagged); // sets flags, and replaces flagged samples with threshold // smooth final float[] smoothedPower = oneDimensionalGausConvolution(powers, 0.5f); // 2nd param is sigma, heigth of the gauss curve // calculate difference final float[] diff = new float[getNrChannels()]; for (int i = 0; i < getNrChannels(); i++) { diff[i] = powers[i] - smoothedPower[i]; } // flag based on difference calculateStatistics(diff, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 1.0f); // higher number is less sensitive! sumThreshold1D(diff, flagged); // and one final pass on the flagged power calculateStatistics(powers, flagged); // sets mean, median, stdDev setBaseSensitivity(originalSensitivity * 0.80f); // higher number is less sensitive! sumThreshold1D(powers, flagged); setBaseSensitivity(originalSensitivity); } }
True
890
258
971
292
908
232
969
292
1,081
283
true
true
true
true
true
false
1,077
46809_4
package User; import MixingProxy.MixingProxy; import Registrar.Registrar; import javafx.scene.paint.Color; import javax.xml.bind.DatatypeConverter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.rmi.RemoteException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.rmi.server.UnicastRemoteObject; import java.util.List; import java.util.Scanner; public class UserImpl extends UnicastRemoteObject implements User { private Registrar registrar; private MixingProxy mixingProxy; private Color colorAfterQrScan; private String phone; private String name; private String QRCode; private String metInfectedPerson; private ArrayList<byte[]> userTokens; private ArrayList<String> userLogs = new ArrayList<>(); private byte[] currentToken; public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException { this.name = name; this.phone = phone; this.registrar = registrar; this.userTokens = new ArrayList<>(); this.mixingProxy = mixingProxy; } // Interface methods @Override public String getPhone() throws RemoteException { return phone; } @Override public String getName() throws RemoteException { return name; } @Override public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException { // New daily tokens this.userTokens.clear(); this.userTokens.addAll(newUserTokens); // Check if critical tokens are in logs ArrayList<String> logs = readLogs(); ArrayList<String> informedUserTokens = new ArrayList<>(); if(!criticalTokens.isEmpty()){ boolean informed = false; for(String[] sCt: criticalTokens ){ String criticalUserToken = sCt[0]; LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]); LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]); for(int i=0; i<logs.size(); i++) { String logFromString = logs.get(i).split("\\^")[0]; LocalDateTime logFrom = LocalDateTime.parse(logFromString); String QR = logs.get(i).split("\\^")[1]; String userToken = logs.get(i).split("\\^")[2]; i++; String logUntilString = logs.get(i).split("\\^")[0]; LocalDateTime logUntil = LocalDateTime.parse(logUntilString); if (criticalUserToken.equals(userToken) && !logUntil.isBefore(timeFrom) && !logFrom.isAfter(timeUntil)) { System.out.println("Je bent in contact gekomen met een positief getest persoon"); informedUserTokens.add(userToken); informed = true; break; } } if(informed){ break; } } mixingProxy.informedTokens(informedUserTokens); } } @Override public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { // User Token this.currentToken = userTokens.get(0); //tijd LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); //qr code loggen this.QRCode = qr; userLogs.add(ldt + "^" + qr + "^" + currentToken); System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken); writeToLogFile(ldt, qr, currentToken); //h value van qr code splitten om door te sturen in capsule String h = qr.substring(qr.lastIndexOf("|") + 1); boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken); // Gebruikte token verwijderen userTokens.remove(0); //symbool toekennen indien jusite qr code scan //op basis van business nummer een kleur toekennen String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|')); generateColor(businessNumber); if(validityToken){ return "ok | " + ldt; } else return "not ok" + ldt; } @Override public String leaveCatering(UserImpl user, String qr) throws RemoteException { LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); userLogs.add(ldt + "^" + qr); writeToLogFile(ldt, qr, currentToken); String h = qr.substring(qr.lastIndexOf("|") + 1); mixingProxy.retrieveExitCapsule(ld, h, currentToken); return "Successfully left catering"; } public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){ String phoneForLog = phone.replace(" ", "_"); try { File logFile = new File("logs/log_" + phoneForLog + ".txt"); if (!logFile.exists()){ logFile.createNewFile(); } FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true); logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken)); logFW.write("\n"); logFW.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } public void generateColor(String b){ switch (b) { case "1": this.colorAfterQrScan = Color.BLUE; break; case "2": this.colorAfterQrScan = Color.GREEN; break; case "3": this.colorAfterQrScan = Color.RED; break; case "4": this.colorAfterQrScan = Color.ORANGE; break; default: this.colorAfterQrScan = Color.BLACK; } } public Color getColorAfterQrScan() { return colorAfterQrScan; } public ArrayList<String> readLogs(){ String phoneForLog = phone.replace(" ", "_"); ArrayList<String> logs = new ArrayList<>(); try { File userLog = new File("logs/log_" + phoneForLog + ".txt"); if (!userLog.exists()){ userLog.createNewFile(); } Scanner userLogReader = new Scanner(userLog); while (userLogReader.hasNextLine()) { logs.add(userLogReader.nextLine()); } userLogReader.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } return logs; } //Setters en getters public ArrayList<byte[]> getUserTokens() { return userTokens; } }
MartijnVanderschelden/ProjectDistributedSystems2
src/User/UserImpl.java
2,053
// Gebruikte token verwijderen
line_comment
nl
package User; import MixingProxy.MixingProxy; import Registrar.Registrar; import javafx.scene.paint.Color; import javax.xml.bind.DatatypeConverter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.rmi.RemoteException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SignatureException; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.ArrayList; import java.rmi.server.UnicastRemoteObject; import java.util.List; import java.util.Scanner; public class UserImpl extends UnicastRemoteObject implements User { private Registrar registrar; private MixingProxy mixingProxy; private Color colorAfterQrScan; private String phone; private String name; private String QRCode; private String metInfectedPerson; private ArrayList<byte[]> userTokens; private ArrayList<String> userLogs = new ArrayList<>(); private byte[] currentToken; public UserImpl(String name, String phone, Registrar registrar, MixingProxy mixingProxy) throws RemoteException { this.name = name; this.phone = phone; this.registrar = registrar; this.userTokens = new ArrayList<>(); this.mixingProxy = mixingProxy; } // Interface methods @Override public String getPhone() throws RemoteException { return phone; } @Override public String getName() throws RemoteException { return name; } @Override public void newDay(List<byte[]> newUserTokens, List<String[]> criticalTokens, LocalDate date) throws RemoteException { // New daily tokens this.userTokens.clear(); this.userTokens.addAll(newUserTokens); // Check if critical tokens are in logs ArrayList<String> logs = readLogs(); ArrayList<String> informedUserTokens = new ArrayList<>(); if(!criticalTokens.isEmpty()){ boolean informed = false; for(String[] sCt: criticalTokens ){ String criticalUserToken = sCt[0]; LocalDateTime timeFrom = LocalDateTime.parse(sCt[1]); LocalDateTime timeUntil = LocalDateTime.parse(sCt[2]); for(int i=0; i<logs.size(); i++) { String logFromString = logs.get(i).split("\\^")[0]; LocalDateTime logFrom = LocalDateTime.parse(logFromString); String QR = logs.get(i).split("\\^")[1]; String userToken = logs.get(i).split("\\^")[2]; i++; String logUntilString = logs.get(i).split("\\^")[0]; LocalDateTime logUntil = LocalDateTime.parse(logUntilString); if (criticalUserToken.equals(userToken) && !logUntil.isBefore(timeFrom) && !logFrom.isAfter(timeUntil)) { System.out.println("Je bent in contact gekomen met een positief getest persoon"); informedUserTokens.add(userToken); informed = true; break; } } if(informed){ break; } } mixingProxy.informedTokens(informedUserTokens); } } @Override public String scanQR(String qr) throws RemoteException, NoSuchAlgorithmException, SignatureException, InvalidKeyException { // User Token this.currentToken = userTokens.get(0); //tijd LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); //qr code loggen this.QRCode = qr; userLogs.add(ldt + "^" + qr + "^" + currentToken); System.out.println("Following log is added to user logs: " + ldt + "|" + qr + "|" + currentToken); writeToLogFile(ldt, qr, currentToken); //h value van qr code splitten om door te sturen in capsule String h = qr.substring(qr.lastIndexOf("|") + 1); boolean validityToken = mixingProxy.retrieveCapsule(phone, ld, h, currentToken); // Gebruikte token<SUF> userTokens.remove(0); //symbool toekennen indien jusite qr code scan //op basis van business nummer een kleur toekennen String businessNumber = qr.substring(qr.indexOf('|') + 1, qr.lastIndexOf('|')); generateColor(businessNumber); if(validityToken){ return "ok | " + ldt; } else return "not ok" + ldt; } @Override public String leaveCatering(UserImpl user, String qr) throws RemoteException { LocalDate ld = registrar.getDate(); LocalDateTime ldt = registrar.getDate().atTime(LocalTime.now()); userLogs.add(ldt + "^" + qr); writeToLogFile(ldt, qr, currentToken); String h = qr.substring(qr.lastIndexOf("|") + 1); mixingProxy.retrieveExitCapsule(ld, h, currentToken); return "Successfully left catering"; } public void writeToLogFile(LocalDateTime ldt, String qr, byte[] currentToken){ String phoneForLog = phone.replace(" ", "_"); try { File logFile = new File("logs/log_" + phoneForLog + ".txt"); if (!logFile.exists()){ logFile.createNewFile(); } FileWriter logFW = new FileWriter("logs/log_" + phoneForLog + ".txt", true); logFW.write(ldt + "^" + qr + "^" + DatatypeConverter.printHexBinary(currentToken)); logFW.write("\n"); logFW.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } } public void generateColor(String b){ switch (b) { case "1": this.colorAfterQrScan = Color.BLUE; break; case "2": this.colorAfterQrScan = Color.GREEN; break; case "3": this.colorAfterQrScan = Color.RED; break; case "4": this.colorAfterQrScan = Color.ORANGE; break; default: this.colorAfterQrScan = Color.BLACK; } } public Color getColorAfterQrScan() { return colorAfterQrScan; } public ArrayList<String> readLogs(){ String phoneForLog = phone.replace(" ", "_"); ArrayList<String> logs = new ArrayList<>(); try { File userLog = new File("logs/log_" + phoneForLog + ".txt"); if (!userLog.exists()){ userLog.createNewFile(); } Scanner userLogReader = new Scanner(userLog); while (userLogReader.hasNextLine()) { logs.add(userLogReader.nextLine()); } userLogReader.close(); } catch (IOException e) { System.out.println("An error occurred."); e.printStackTrace(); } return logs; } //Setters en getters public ArrayList<byte[]> getUserTokens() { return userTokens; } }
True
1,463
10
1,646
9
1,736
5
1,646
9
2,043
10
false
false
false
false
false
true
686
83986_7
package oop.voetbalmanager.model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.jdom2.DataConversionException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class XMLreader { public XMLreader(){ } public Divisie readDivisie(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Team> teamList = new ArrayList<Team>(); String divisieNaam = ""; int speeldag = -1; int stand = -1; String avatarPath = ""; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); //parse naam en get teamlist divisieNaam = divisieEl.getChildText("naam"); teamList = readTeamList(divisieEl); //parse speeldag speeldag = Integer.parseInt(divisieEl.getChildText("speeldag")); stand = Integer.parseInt(divisieEl.getChildText("stand")); avatarPath = divisieEl.getChildText("avatarPath"); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //maak divisie Divisie divisie = new Divisie(divisieNaam, teamList, speeldag, stand, avatarPath); return divisie; } public ArrayList<Team> readTeamList(Element divisie){ ArrayList<Team> teamList = new ArrayList<Team>(); //maak lijst van alle <team> List<Element> teamElementList = divisie.getChildren("team"); //<team> als element in arrraylist toevoegen for (int i = 0; i < teamElementList.size(); i++) { //parse teamNaam, rank en get spelerList Element teamEl = (Element) teamElementList.get(i); //parse naam, rank, spelerslijst, winst .... teamList.add(readTeam(teamEl)); } return teamList; } public Team readTeam(Element teamEl){ //parse naam, rank, spelerslijst, winst .... String teamNaam = teamEl.getChildText("naam"); int rank = Integer.parseInt(teamEl.getChildText("rank")); ArrayList<Speler> spelerList = readSpelerList(teamNaam, teamEl); int winst = Integer.parseInt(teamEl.getChildText("winst")); int verlies = Integer.parseInt(teamEl.getChildText("verlies")); int gelijkspel = Integer.parseInt(teamEl.getChildText("gelijkspel")); int doelsaldo = Integer.parseInt(teamEl.getChildText("doelsaldo")); int doeltegen = Integer.parseInt(teamEl.getChildText("doeltegen")); int doelvoor = Integer.parseInt(teamEl.getChildText("doelvoor")); double budget = Double.parseDouble(teamEl.getChildText("budget")); int score = Integer.parseInt(teamEl.getChildText("score")); Team team = new Team(teamNaam, rank, spelerList, winst, verlies, gelijkspel, doelsaldo, doeltegen, doelvoor, budget, score); return team; } public ArrayList<Speler> readSpelerList(String teamNaam, Element team){ ArrayList<Speler> spelerList = new ArrayList<Speler>(); //maak lijst van alle <team> List<Element> spelerElementList = team.getChildren("speler"); //<team> als element in arrraylist toevoegen for (int i = 0; i < spelerElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element spelerEl = (Element) spelerElementList.get(i); spelerList.add(readSpeler(spelerEl)); } return spelerList; } public Speler readSpeler(Element spelerEl){ String spelerNaam = spelerEl.getChildText("naam"); int nummer=-1; try { nummer = spelerEl.getAttribute("id").getIntValue(); } catch (DataConversionException e) { e.printStackTrace(); } String type = spelerEl.getChildText("type"); int offense = Integer.parseInt(spelerEl.getChildText("offense")); int defence = Integer.parseInt(spelerEl.getChildText("defence")); int uithouding = Integer.parseInt(spelerEl.getChildText("uithouding")); String beschikbaarheid = spelerEl.getChildText("beschikbaarheid"); double prijs = Double.parseDouble(spelerEl.getChildText("prijs")); Speler speler = new Speler(spelerNaam, nummer, type, offense, defence, uithouding, beschikbaarheid, prijs); return speler; } public ArrayList<Opstelling> readOpstellingList(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Opstelling> opstellingen = new ArrayList<Opstelling>(); try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element opsteling = divisieEl.getChild("opstellingen"); //maak lijst van alle opstellingen List<Element> opstElementList = opsteling.getChildren("opstelling_posities"); //<opstelling> als element in arrraylist toevoegen for (int i = 0; i < opstElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element opstEl = (Element) opstElementList.get(i); opstellingen.add(readOpstelling(opstEl)); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //parse naam, rank, spelerslijst, winst .... return opstellingen; } public Opstelling readOpstelling(Element opstEl){ List<Element> positiesList = opstEl.getChildren(); ArrayList<Positie> posities = new ArrayList<Positie>(); for (int i = 1; i < positiesList.size(); i++) { int x = Integer.parseInt(positiesList.get(i).getText().split(",")[0]); int y = Integer.parseInt(positiesList.get(i).getText().split(",")[1]); String type = positiesList.get(i).getName(); type = type.substring(0, type.length()-1); Positie speler = new Positie(x, y, type); posities.add(speler); } Collections.sort(posities, new Comparator<Positie>() { @Override public int compare(Positie p1, Positie p2) { return Integer.compare(p2.getY(), p1.getY()); } }); //parse naam, spelerslijst .... Opstelling opstelling = new Opstelling(opstEl.getChildText("naam"), posities); return opstelling; } public Wedstrijdteam readWedstrijdteam(Team userteam, String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); Wedstrijdteam wteam = null; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element wteamElement = divisieEl.getChild("Wedstrijdteam"); //parse naam, rank, spelerslijst, winst .... String opstelling = wteamElement.getChildText("opstelling"); int tactiek = Integer.parseInt(wteamElement.getChildText("tactiek")); String spelers = wteamElement.getChildText("spelers"); String gespeeldMet = wteamElement.getChildText("gespeeldMet"); if(userteam==null){ String teamNaam = wteamElement.getChildText("TeamNaam"); Team team = Divisie.findTeamByName(teamNaam); User.setTeam(team); wteam = new Wedstrijdteam(team); }else{ wteam = new Wedstrijdteam(userteam); } ArrayList<Speler> spelerList = new ArrayList<Speler>(); for(Speler s: wteam.getSpelerList()){ if(spelers.contains(s.getNaam())){ spelerList.add(s); } } if(spelerList.size()<1){ for(Speler s: wteam.getSpelerList()){ if(s.getType().contains("doelman")){ spelerList.add(s); break; } } for(Speler s: wteam.getSpelerList()){ if(!s.getType().contains("doelman")){ spelerList.add(s); } if(spelerList.size()==11){ break; } } } Collections.reverse(spelerList); Speler[] spelersArray = new Speler[11]; spelerList.toArray(spelersArray); ArrayList<Opstelling> opstellingen = readOpstellingList(infile); for(Opstelling op: opstellingen){ if(op.getNaam().equals(opstelling)){ wteam.setOpstelling(op); } } wteam.setTactiek(tactiek); wteam.setWSpelers(spelersArray); wteam.setGespeeldMet(gespeeldMet); System.out.println("xmlreader: "+gespeeldMet); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } return wteam; } }
Hazinck/OOP-project
Voetbalmanager/src/oop/voetbalmanager/model/XMLreader.java
2,920
//maak lijst van alle <team>
line_comment
nl
package oop.voetbalmanager.model; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import org.jdom2.DataConversionException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class XMLreader { public XMLreader(){ } public Divisie readDivisie(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Team> teamList = new ArrayList<Team>(); String divisieNaam = ""; int speeldag = -1; int stand = -1; String avatarPath = ""; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); //parse naam en get teamlist divisieNaam = divisieEl.getChildText("naam"); teamList = readTeamList(divisieEl); //parse speeldag speeldag = Integer.parseInt(divisieEl.getChildText("speeldag")); stand = Integer.parseInt(divisieEl.getChildText("stand")); avatarPath = divisieEl.getChildText("avatarPath"); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //maak divisie Divisie divisie = new Divisie(divisieNaam, teamList, speeldag, stand, avatarPath); return divisie; } public ArrayList<Team> readTeamList(Element divisie){ ArrayList<Team> teamList = new ArrayList<Team>(); //maak lijst van alle <team> List<Element> teamElementList = divisie.getChildren("team"); //<team> als element in arrraylist toevoegen for (int i = 0; i < teamElementList.size(); i++) { //parse teamNaam, rank en get spelerList Element teamEl = (Element) teamElementList.get(i); //parse naam, rank, spelerslijst, winst .... teamList.add(readTeam(teamEl)); } return teamList; } public Team readTeam(Element teamEl){ //parse naam, rank, spelerslijst, winst .... String teamNaam = teamEl.getChildText("naam"); int rank = Integer.parseInt(teamEl.getChildText("rank")); ArrayList<Speler> spelerList = readSpelerList(teamNaam, teamEl); int winst = Integer.parseInt(teamEl.getChildText("winst")); int verlies = Integer.parseInt(teamEl.getChildText("verlies")); int gelijkspel = Integer.parseInt(teamEl.getChildText("gelijkspel")); int doelsaldo = Integer.parseInt(teamEl.getChildText("doelsaldo")); int doeltegen = Integer.parseInt(teamEl.getChildText("doeltegen")); int doelvoor = Integer.parseInt(teamEl.getChildText("doelvoor")); double budget = Double.parseDouble(teamEl.getChildText("budget")); int score = Integer.parseInt(teamEl.getChildText("score")); Team team = new Team(teamNaam, rank, spelerList, winst, verlies, gelijkspel, doelsaldo, doeltegen, doelvoor, budget, score); return team; } public ArrayList<Speler> readSpelerList(String teamNaam, Element team){ ArrayList<Speler> spelerList = new ArrayList<Speler>(); //maak lijst<SUF> List<Element> spelerElementList = team.getChildren("speler"); //<team> als element in arrraylist toevoegen for (int i = 0; i < spelerElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element spelerEl = (Element) spelerElementList.get(i); spelerList.add(readSpeler(spelerEl)); } return spelerList; } public Speler readSpeler(Element spelerEl){ String spelerNaam = spelerEl.getChildText("naam"); int nummer=-1; try { nummer = spelerEl.getAttribute("id").getIntValue(); } catch (DataConversionException e) { e.printStackTrace(); } String type = spelerEl.getChildText("type"); int offense = Integer.parseInt(spelerEl.getChildText("offense")); int defence = Integer.parseInt(spelerEl.getChildText("defence")); int uithouding = Integer.parseInt(spelerEl.getChildText("uithouding")); String beschikbaarheid = spelerEl.getChildText("beschikbaarheid"); double prijs = Double.parseDouble(spelerEl.getChildText("prijs")); Speler speler = new Speler(spelerNaam, nummer, type, offense, defence, uithouding, beschikbaarheid, prijs); return speler; } public ArrayList<Opstelling> readOpstellingList(String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); ArrayList<Opstelling> opstellingen = new ArrayList<Opstelling>(); try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element opsteling = divisieEl.getChild("opstellingen"); //maak lijst van alle opstellingen List<Element> opstElementList = opsteling.getChildren("opstelling_posities"); //<opstelling> als element in arrraylist toevoegen for (int i = 0; i < opstElementList.size(); i++) { //parse teamNaam, rank, get spelerList ... Element opstEl = (Element) opstElementList.get(i); opstellingen.add(readOpstelling(opstEl)); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } //parse naam, rank, spelerslijst, winst .... return opstellingen; } public Opstelling readOpstelling(Element opstEl){ List<Element> positiesList = opstEl.getChildren(); ArrayList<Positie> posities = new ArrayList<Positie>(); for (int i = 1; i < positiesList.size(); i++) { int x = Integer.parseInt(positiesList.get(i).getText().split(",")[0]); int y = Integer.parseInt(positiesList.get(i).getText().split(",")[1]); String type = positiesList.get(i).getName(); type = type.substring(0, type.length()-1); Positie speler = new Positie(x, y, type); posities.add(speler); } Collections.sort(posities, new Comparator<Positie>() { @Override public int compare(Positie p1, Positie p2) { return Integer.compare(p2.getY(), p1.getY()); } }); //parse naam, spelerslijst .... Opstelling opstelling = new Opstelling(opstEl.getChildText("naam"), posities); return opstelling; } public Wedstrijdteam readWedstrijdteam(Team userteam, String infile){ SAXBuilder builder = new SAXBuilder(); File xmlFile = new File(infile); Wedstrijdteam wteam = null; try { //open xml Document document = (Document) builder.build(xmlFile); //maak element van <divisie> Element divisieEl = document.getRootElement(); Element wteamElement = divisieEl.getChild("Wedstrijdteam"); //parse naam, rank, spelerslijst, winst .... String opstelling = wteamElement.getChildText("opstelling"); int tactiek = Integer.parseInt(wteamElement.getChildText("tactiek")); String spelers = wteamElement.getChildText("spelers"); String gespeeldMet = wteamElement.getChildText("gespeeldMet"); if(userteam==null){ String teamNaam = wteamElement.getChildText("TeamNaam"); Team team = Divisie.findTeamByName(teamNaam); User.setTeam(team); wteam = new Wedstrijdteam(team); }else{ wteam = new Wedstrijdteam(userteam); } ArrayList<Speler> spelerList = new ArrayList<Speler>(); for(Speler s: wteam.getSpelerList()){ if(spelers.contains(s.getNaam())){ spelerList.add(s); } } if(spelerList.size()<1){ for(Speler s: wteam.getSpelerList()){ if(s.getType().contains("doelman")){ spelerList.add(s); break; } } for(Speler s: wteam.getSpelerList()){ if(!s.getType().contains("doelman")){ spelerList.add(s); } if(spelerList.size()==11){ break; } } } Collections.reverse(spelerList); Speler[] spelersArray = new Speler[11]; spelerList.toArray(spelersArray); ArrayList<Opstelling> opstellingen = readOpstellingList(infile); for(Opstelling op: opstellingen){ if(op.getNaam().equals(opstelling)){ wteam.setOpstelling(op); } } wteam.setTactiek(tactiek); wteam.setWSpelers(spelersArray); wteam.setGespeeldMet(gespeeldMet); System.out.println("xmlreader: "+gespeeldMet); } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } return wteam; } }
True
2,360
10
2,720
10
2,640
8
2,720
10
3,220
10
false
false
false
false
false
true
4,385
213151_6
package com.vividsolutions.jump.workbench.imagery.geotiff;_x000D_ _x000D_ /*_x000D_ * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI _x000D_ * for visualizing and manipulating spatial features with geometry and attributes._x000D_ *_x000D_ * Copyright (C) 2003 Vivid Solutions_x000D_ * _x000D_ * This program is free software; you can redistribute it and/or_x000D_ * modify it under the terms of the GNU General Public License_x000D_ * as published by the Free Software Foundation; either version 2_x000D_ * of the License, or (at your option) any later version._x000D_ * _x000D_ * This program is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU General Public License for more details._x000D_ * _x000D_ * You should have received a copy of the GNU General Public License_x000D_ * along with this program; if not, write to the Free Software_x000D_ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA._x000D_ * _x000D_ * For more information, contact:_x000D_ *_x000D_ * Vivid Solutions_x000D_ * Suite #1A_x000D_ * 2328 Government Street_x000D_ * Victoria BC V8T 5G5_x000D_ * Canada_x000D_ *_x000D_ * (250)385-6040_x000D_ * www.vividsolutions.com_x000D_ */_x000D_ import java.awt.geom.AffineTransform;_x000D_ import java.util.List;_x000D_ _x000D_ import org.geotiff.image.jai.GeoTIFFDescriptor;_x000D_ import org.geotiff.image.jai.GeoTIFFDirectory;_x000D_ import org.libtiff.jai.codec.XTIFF;_x000D_ import org.libtiff.jai.codec.XTIFFField;_x000D_ _x000D_ import com.vividsolutions.jts.geom.Coordinate;_x000D_ import com.vividsolutions.jump.util.FileUtil;_x000D_ _x000D_ public class GeoTIFFRaster extends GeoReferencedRaster_x000D_ {_x000D_ private final String MSG_GENERAL = "This is not a valid GeoTIFF file.";_x000D_ String fileName;_x000D_ _x000D_ boolean hoPatch = false;_x000D_ _x000D_ /**_x000D_ * Called by Java2XML_x000D_ */_x000D_ public GeoTIFFRaster(String imageFileLocation)_x000D_ throws Exception_x000D_ {_x000D_ super(imageFileLocation);_x000D_ registerWithJAI();_x000D_ readRasterfile();_x000D_ }_x000D_ _x000D_ private void registerWithJAI()_x000D_ {_x000D_ // Register the GeoTIFF descriptor with JAI._x000D_ GeoTIFFDescriptor.register();_x000D_ }_x000D_ _x000D_ private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception_x000D_ {_x000D_ // Find the ModelTiePoints field_x000D_ XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS);_x000D_ if (fieldModelTiePoints == null)_x000D_ throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL);_x000D_ _x000D_ // Get the number of modeltiepoints_x000D_ // int numModelTiePoints = fieldModelTiePoints.getCount() / 6;_x000D_ _x000D_ // ToDo: alleen numModelTiePoints == 1 ondersteunen._x000D_ _x000D_ // Map the modeltiepoints from raster to model space_x000D_ _x000D_ // Read the tiepoints_x000D_ setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints_x000D_ .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0));_x000D_ setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3),_x000D_ fieldModelTiePoints.getAsDouble(4), 0));_x000D_ setEnvelope();_x000D_ // Find the ModelPixelScale field_x000D_ XTIFFField fieldModelPixelScale = dir_x000D_ .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE);_x000D_ if (fieldModelPixelScale == null)_x000D_ throw new Exception("Missing pixelscale-tag in file." + "\n"_x000D_ + MSG_GENERAL);_x000D_ _x000D_ setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0));_x000D_ setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1));_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return filename of the tiff worldfile_x000D_ */_x000D_ private String worldFileName()_x000D_ {_x000D_ int posDot = fileName.lastIndexOf('.');_x000D_ if (posDot == -1)_x000D_ {_x000D_ posDot = fileName.length();_x000D_ }_x000D_ return fileName.substring(0, posDot) + ".tfw";_x000D_ }_x000D_ _x000D_ private void parseWorldFile() throws Exception_x000D_ {_x000D_ // Get the name of the tiff worldfile._x000D_ String name = worldFileName();_x000D_ _x000D_ // Read the tags from the tiff worldfile._x000D_ List lines = FileUtil.getContents(name);_x000D_ double[] tags = new double[6];_x000D_ for (int i = 0; i < 6; i++)_x000D_ {_x000D_ String line = (String) lines.get(i);_x000D_ tags[i] = Double.parseDouble(line);_x000D_ }_x000D_ setAffineTransformation(new AffineTransform(tags));_x000D_ }_x000D_ _x000D_ protected void readRasterfile() throws Exception_x000D_ {_x000D_ // ImageCodec originalCodec = ImageCodec.getCodec("tiff");_x000D_ _x000D_ try_x000D_ {_x000D_ super.readRasterfile();_x000D_ _x000D_ // Get access to the tags and geokeys._x000D_ // First, get the TIFF directory_x000D_ GeoTIFFDirectory dir = (GeoTIFFDirectory) src_x000D_ .getProperty("tiff.directory");_x000D_ if (dir == null)_x000D_ throw new Exception("This is not a (geo)tiff file.");_x000D_ _x000D_ try_x000D_ {_x000D_ // Try to parse any embedded geotiff tags._x000D_ parseGeoTIFFDirectory(dir);_x000D_ } catch (Exception E)_x000D_ {_x000D_ // Embedded geotiff tags have not been found. Try_x000D_ // to use a geotiff world file._x000D_ try_x000D_ {_x000D_ parseWorldFile();_x000D_ } catch (Exception e)_x000D_ {_x000D_ throw new Exception(_x000D_ "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL);_x000D_ }_x000D_ }_x000D_ } finally_x000D_ {_x000D_ }_x000D_ }_x000D_ _x000D_ }
stackmystack/newmotorbac
src-jump/com/vividsolutions/jump/workbench/imagery/geotiff/GeoTIFFRaster.java
1,666
// ToDo: alleen numModelTiePoints == 1 ondersteunen._x000D_
line_comment
nl
package com.vividsolutions.jump.workbench.imagery.geotiff;_x000D_ _x000D_ /*_x000D_ * The Unified Mapping Platform (JUMP) is an extensible, interactive GUI _x000D_ * for visualizing and manipulating spatial features with geometry and attributes._x000D_ *_x000D_ * Copyright (C) 2003 Vivid Solutions_x000D_ * _x000D_ * This program is free software; you can redistribute it and/or_x000D_ * modify it under the terms of the GNU General Public License_x000D_ * as published by the Free Software Foundation; either version 2_x000D_ * of the License, or (at your option) any later version._x000D_ * _x000D_ * This program is distributed in the hope that it will be useful,_x000D_ * but WITHOUT ANY WARRANTY; without even the implied warranty of_x000D_ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the_x000D_ * GNU General Public License for more details._x000D_ * _x000D_ * You should have received a copy of the GNU General Public License_x000D_ * along with this program; if not, write to the Free Software_x000D_ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA._x000D_ * _x000D_ * For more information, contact:_x000D_ *_x000D_ * Vivid Solutions_x000D_ * Suite #1A_x000D_ * 2328 Government Street_x000D_ * Victoria BC V8T 5G5_x000D_ * Canada_x000D_ *_x000D_ * (250)385-6040_x000D_ * www.vividsolutions.com_x000D_ */_x000D_ import java.awt.geom.AffineTransform;_x000D_ import java.util.List;_x000D_ _x000D_ import org.geotiff.image.jai.GeoTIFFDescriptor;_x000D_ import org.geotiff.image.jai.GeoTIFFDirectory;_x000D_ import org.libtiff.jai.codec.XTIFF;_x000D_ import org.libtiff.jai.codec.XTIFFField;_x000D_ _x000D_ import com.vividsolutions.jts.geom.Coordinate;_x000D_ import com.vividsolutions.jump.util.FileUtil;_x000D_ _x000D_ public class GeoTIFFRaster extends GeoReferencedRaster_x000D_ {_x000D_ private final String MSG_GENERAL = "This is not a valid GeoTIFF file.";_x000D_ String fileName;_x000D_ _x000D_ boolean hoPatch = false;_x000D_ _x000D_ /**_x000D_ * Called by Java2XML_x000D_ */_x000D_ public GeoTIFFRaster(String imageFileLocation)_x000D_ throws Exception_x000D_ {_x000D_ super(imageFileLocation);_x000D_ registerWithJAI();_x000D_ readRasterfile();_x000D_ }_x000D_ _x000D_ private void registerWithJAI()_x000D_ {_x000D_ // Register the GeoTIFF descriptor with JAI._x000D_ GeoTIFFDescriptor.register();_x000D_ }_x000D_ _x000D_ private void parseGeoTIFFDirectory(GeoTIFFDirectory dir) throws Exception_x000D_ {_x000D_ // Find the ModelTiePoints field_x000D_ XTIFFField fieldModelTiePoints = dir.getField(XTIFF.TIFFTAG_GEO_TIEPOINTS);_x000D_ if (fieldModelTiePoints == null)_x000D_ throw new Exception("Missing tiepoints-tag in file.\n" + MSG_GENERAL);_x000D_ _x000D_ // Get the number of modeltiepoints_x000D_ // int numModelTiePoints = fieldModelTiePoints.getCount() / 6;_x000D_ _x000D_ // ToDo: alleen<SUF> _x000D_ // Map the modeltiepoints from raster to model space_x000D_ _x000D_ // Read the tiepoints_x000D_ setCoorRasterTiff_tiepointLT(new Coordinate(fieldModelTiePoints_x000D_ .getAsDouble(0), fieldModelTiePoints.getAsDouble(1), 0));_x000D_ setCoorModel_tiepointLT(new Coordinate(fieldModelTiePoints.getAsDouble(3),_x000D_ fieldModelTiePoints.getAsDouble(4), 0));_x000D_ setEnvelope();_x000D_ // Find the ModelPixelScale field_x000D_ XTIFFField fieldModelPixelScale = dir_x000D_ .getField(XTIFF.TIFFTAG_GEO_PIXEL_SCALE);_x000D_ if (fieldModelPixelScale == null)_x000D_ throw new Exception("Missing pixelscale-tag in file." + "\n"_x000D_ + MSG_GENERAL);_x000D_ _x000D_ setDblModelUnitsPerRasterUnit_X(fieldModelPixelScale.getAsDouble(0));_x000D_ setDblModelUnitsPerRasterUnit_Y(fieldModelPixelScale.getAsDouble(1));_x000D_ }_x000D_ _x000D_ /**_x000D_ * @return filename of the tiff worldfile_x000D_ */_x000D_ private String worldFileName()_x000D_ {_x000D_ int posDot = fileName.lastIndexOf('.');_x000D_ if (posDot == -1)_x000D_ {_x000D_ posDot = fileName.length();_x000D_ }_x000D_ return fileName.substring(0, posDot) + ".tfw";_x000D_ }_x000D_ _x000D_ private void parseWorldFile() throws Exception_x000D_ {_x000D_ // Get the name of the tiff worldfile._x000D_ String name = worldFileName();_x000D_ _x000D_ // Read the tags from the tiff worldfile._x000D_ List lines = FileUtil.getContents(name);_x000D_ double[] tags = new double[6];_x000D_ for (int i = 0; i < 6; i++)_x000D_ {_x000D_ String line = (String) lines.get(i);_x000D_ tags[i] = Double.parseDouble(line);_x000D_ }_x000D_ setAffineTransformation(new AffineTransform(tags));_x000D_ }_x000D_ _x000D_ protected void readRasterfile() throws Exception_x000D_ {_x000D_ // ImageCodec originalCodec = ImageCodec.getCodec("tiff");_x000D_ _x000D_ try_x000D_ {_x000D_ super.readRasterfile();_x000D_ _x000D_ // Get access to the tags and geokeys._x000D_ // First, get the TIFF directory_x000D_ GeoTIFFDirectory dir = (GeoTIFFDirectory) src_x000D_ .getProperty("tiff.directory");_x000D_ if (dir == null)_x000D_ throw new Exception("This is not a (geo)tiff file.");_x000D_ _x000D_ try_x000D_ {_x000D_ // Try to parse any embedded geotiff tags._x000D_ parseGeoTIFFDirectory(dir);_x000D_ } catch (Exception E)_x000D_ {_x000D_ // Embedded geotiff tags have not been found. Try_x000D_ // to use a geotiff world file._x000D_ try_x000D_ {_x000D_ parseWorldFile();_x000D_ } catch (Exception e)_x000D_ {_x000D_ throw new Exception(_x000D_ "Neither geotiff tags nor valid worldfile found.\n" + MSG_GENERAL);_x000D_ }_x000D_ }_x000D_ } finally_x000D_ {_x000D_ }_x000D_ }_x000D_ _x000D_ }
True
2,274
23
2,456
24
2,499
20
2,456
24
2,736
25
false
false
false
false
false
true
1,857
25134_1
package gamejam.weapons; import gamejam.GameManager; import gamejam.event.EventConsumer; import gamejam.event.EventQueue; import gamejam.event.EventType; import gamejam.event.events.WeaponFireEvent; import gamejam.weapons.augmentation.WeaponAugmenter; import java.util.Random; public abstract class Weapon { protected float damage; protected float bulletSpeed; protected float bulletSize; protected int bulletAmount; protected float bulletAngleSpread; // firing logic stuffs protected int coolDownMs; protected long lastFireTime = 0; protected Random random = new Random(); public Weapon(float damage, float bulletSpeed, float bulletSize, int bulletAmount, float bulletAngleSpread, int coolDownMs) { this.damage = damage; this.bulletSpeed = bulletSpeed; this.bulletSize = bulletSize; this.bulletAmount = bulletAmount; this.bulletAngleSpread = bulletAngleSpread; this.coolDownMs = coolDownMs; EventConsumer<WeaponFireEvent> consumer = this::onWeaponFire; EventQueue.getInstance().registerConsumer(consumer, EventType.WEAPON_FIRED); } private void onWeaponFire(WeaponFireEvent event) { if (event.getWeapon() == this) { GameManager.getInstance().getCamera().startShake(); } } /** * Wanneer de {@link gamejam.objects.collidable.Player} isFiringWeapon true is, dan wordt deze methode aangeroepen. * @return True als het wapen werd afgevuurd, anders false (cooldown tijd nog niet verstreken). */ public boolean fire(float originX, float originY, float xVelocity, float yVelocity) { final long now = System.currentTimeMillis(); if (now - this.lastFireTime > this.coolDownMs) { this.lastFireTime = now; EventQueue.getInstance().invoke(new WeaponFireEvent(this)); return true; } else { return false; } } public void applyAugmentation(WeaponAugmenter weaponAugmenter) { weaponAugmenter.augment(this); } public void scaleBulletSize(float scale) { bulletSize = bulletSize * scale; } public void scaleBulletSize(int scale) { bulletSize += scale; } public void scaleBulletDamage(float scale) { damage = damage * scale; } public void scaleBulletDamage(int scale) { damage += scale; } public void addBulletAmount(int amount) { this.bulletAmount += amount; } public void addBulletSpeed(int amount) { this.bulletSpeed += amount; } public float getDamage() { return damage; } public int getCoolDownMs() { return coolDownMs; } public void setCoolDownMs(int coolDownMs) { this.coolDownMs = coolDownMs; } public void augmentExplosion(int initialAmount, int addAmount) { } }
Vulcanostrol/lipsum-game-2022
core/src/gamejam/weapons/Weapon.java
835
/** * Wanneer de {@link gamejam.objects.collidable.Player} isFiringWeapon true is, dan wordt deze methode aangeroepen. * @return True als het wapen werd afgevuurd, anders false (cooldown tijd nog niet verstreken). */
block_comment
nl
package gamejam.weapons; import gamejam.GameManager; import gamejam.event.EventConsumer; import gamejam.event.EventQueue; import gamejam.event.EventType; import gamejam.event.events.WeaponFireEvent; import gamejam.weapons.augmentation.WeaponAugmenter; import java.util.Random; public abstract class Weapon { protected float damage; protected float bulletSpeed; protected float bulletSize; protected int bulletAmount; protected float bulletAngleSpread; // firing logic stuffs protected int coolDownMs; protected long lastFireTime = 0; protected Random random = new Random(); public Weapon(float damage, float bulletSpeed, float bulletSize, int bulletAmount, float bulletAngleSpread, int coolDownMs) { this.damage = damage; this.bulletSpeed = bulletSpeed; this.bulletSize = bulletSize; this.bulletAmount = bulletAmount; this.bulletAngleSpread = bulletAngleSpread; this.coolDownMs = coolDownMs; EventConsumer<WeaponFireEvent> consumer = this::onWeaponFire; EventQueue.getInstance().registerConsumer(consumer, EventType.WEAPON_FIRED); } private void onWeaponFire(WeaponFireEvent event) { if (event.getWeapon() == this) { GameManager.getInstance().getCamera().startShake(); } } /** * Wanneer de {@link<SUF>*/ public boolean fire(float originX, float originY, float xVelocity, float yVelocity) { final long now = System.currentTimeMillis(); if (now - this.lastFireTime > this.coolDownMs) { this.lastFireTime = now; EventQueue.getInstance().invoke(new WeaponFireEvent(this)); return true; } else { return false; } } public void applyAugmentation(WeaponAugmenter weaponAugmenter) { weaponAugmenter.augment(this); } public void scaleBulletSize(float scale) { bulletSize = bulletSize * scale; } public void scaleBulletSize(int scale) { bulletSize += scale; } public void scaleBulletDamage(float scale) { damage = damage * scale; } public void scaleBulletDamage(int scale) { damage += scale; } public void addBulletAmount(int amount) { this.bulletAmount += amount; } public void addBulletSpeed(int amount) { this.bulletSpeed += amount; } public float getDamage() { return damage; } public int getCoolDownMs() { return coolDownMs; } public void setCoolDownMs(int coolDownMs) { this.coolDownMs = coolDownMs; } public void augmentExplosion(int initialAmount, int addAmount) { } }
True
649
62
711
75
745
62
711
75
888
77
false
false
false
false
false
true
4,637
80482_3
package utils; import java.util.Locale; /** * Die Klasse Vector2D stellt eine Hilfsklasse zur Berechnung von Koordinaten dar. In erster Linie ist die Klasse zur * Nutzung als Ortsvektor gedacht, eine Nutzung als Richtungsvektor ist aber ebenfalls möglich. * Alle Methoden arbeiten nicht-destruktiv, um Fehlern bei der Nutzung vorzubeugen. * @author Viktor Winkelmann * */ public class Vector2D { private static final double MAX_DEVIATION = 0.00001; // Maximale Koordinaten Abweichung für Objektgleichheit private double x,y; public Vector2D(double x, double y) { this.x = x; this.y = y; } public Vector2D() { this(0,0); } /** * Liefert den X-Koordinaten Anteil. * @return X-Koordinate */ public double getX() { return x; } /** * Liefert den Y-Koordinaten Anteil. * @return Y-Koordinate */ public double getY() { return y; } /** * Addiert einen Vektor. * @param other Zu addierender Vektor * @return Neuer Vektor */ public Vector2D add(Vector2D other) { return new Vector2D(x + other.x, y + other.y); } /** * Subtrahiert einen Vektor. * @param other Zu subtrahierender Vektor * @return Neuer Vektor */ public Vector2D subtract(Vector2D other) { return new Vector2D(x - other.x, y - other.y); } /** * Multipliziert den Vektor mit einem Skalar. * @param scalar Skalar * @return Neuer Vektor */ public Vector2D multiply(double scalar) { return new Vector2D(x * scalar, y * scalar); } /** * Dividiert den Vektor durch einen Skalar. * @param scalar Skalar * @return Neuer Vektor */ public Vector2D divide(double scalar) { return new Vector2D(x / scalar, y / scalar); } /** * Berechnet die Länge des Vektors. * @return Vektorlänge */ public double length(){ return Math.sqrt(x*x + y*y); } /** * Berechnet die Distanz zu einem anderen Vektor. * @param other Anderer Vektor * @return Distanz */ public double distanceTo(Vector2D other) { return other.subtract(this).length(); } /** * Berechnet den Winkel zu einem anderen Vektor im Bereich * von -180 bis 180 Grad. Ist der andere Vektor im Uhrzeigesinn * gedreht, ist der Winkel postiv, sonst negativ. * * @param other Anderer Vektor * @return Winkel */ public double angleTo(Vector2D other) { return other.getNormalHeading() - getNormalHeading(); } /** * Liefert die Richtung eines Vektors im Bereich von 0 bis 360 Grad. * 0 = Norden, 90 = Osten, 180 = Süden, 270 = Westen * @return Richtung in Grad */ public double getHeading() { double mathAngle = Utils.radToDeg(Math.acos(x / length())); if (y >= 0) { if (x < 0) { return 450 - mathAngle; } else { return 90 - mathAngle; } } else { return mathAngle + 90; } } /** * Liefert die normalisierte Richtung eines Vektors im Bereich von -180 bis 180 Grad. * -180 = Westen, -90 = Norden, 0 = Osten, 90 = Süden * @return Normalisierte Richtung in Grad */ public double getNormalHeading() { double mathAngle = Utils.radToDeg(Math.acos(x / length())); return (y >= 0) ? -1 * mathAngle : mathAngle; } /** * Dreht den Vektor um einen Winkel in Grad. * Die Drehung erfolgt um den Vektorursprung im mathematisch * negativer Richtung (im Uhrzeigesinn). * @param angleDegrees Winkel in Grad * @return Neuer Vektor */ public Vector2D rotate(double angleDegrees) { return rotateRad(Utils.degToRad(angleDegrees)); } /** * Dreht den Vektor um einen Winkel im Bogenmaß. * Die Drehung erfolgt um den Vektorursprung im mathematisch * negativer Richtung (im Uhrzeigesinn). * @param angleRadians Winkel in Rad * @return Neuer Vektor */ public Vector2D rotateRad(double angleRadians) { angleRadians = angleRadians * -1; return new Vector2D(x * Math.cos(angleRadians) - y * Math.sin(angleRadians), x * Math.sin(angleRadians) + y * Math.cos(angleRadians)); } /** * Prüf ob der Vector in einem Rechteck liegt. * @param x * @param y * @param width * @param height * @return */ public boolean inRectangle(double x, double y, double width, double height) { return !(this.x < x || this.y < y || this.x > x + width || this.y > y + height); } /** * Liefert eine String Darstellung der Vektorkoordinaten. */ @Override public String toString() { return String.format(Locale.ENGLISH, "X: %1$,.3f, Y: %2$,.3f", x, y); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(x); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(y); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vector2D other = (Vector2D) obj; if (Math.abs(x - other.x) > MAX_DEVIATION) return false; if (Math.abs(y - other.y) > MAX_DEVIATION) return false; return true; } }
vikwin/HAW-LernendeAgenten_RC
LARCbot_OliViktor/LARC/src/utils/Vector2D.java
1,907
/** * Liefert den Y-Koordinaten Anteil. * @return Y-Koordinate */
block_comment
nl
package utils; import java.util.Locale; /** * Die Klasse Vector2D stellt eine Hilfsklasse zur Berechnung von Koordinaten dar. In erster Linie ist die Klasse zur * Nutzung als Ortsvektor gedacht, eine Nutzung als Richtungsvektor ist aber ebenfalls möglich. * Alle Methoden arbeiten nicht-destruktiv, um Fehlern bei der Nutzung vorzubeugen. * @author Viktor Winkelmann * */ public class Vector2D { private static final double MAX_DEVIATION = 0.00001; // Maximale Koordinaten Abweichung für Objektgleichheit private double x,y; public Vector2D(double x, double y) { this.x = x; this.y = y; } public Vector2D() { this(0,0); } /** * Liefert den X-Koordinaten Anteil. * @return X-Koordinate */ public double getX() { return x; } /** * Liefert den Y-Koordinaten<SUF>*/ public double getY() { return y; } /** * Addiert einen Vektor. * @param other Zu addierender Vektor * @return Neuer Vektor */ public Vector2D add(Vector2D other) { return new Vector2D(x + other.x, y + other.y); } /** * Subtrahiert einen Vektor. * @param other Zu subtrahierender Vektor * @return Neuer Vektor */ public Vector2D subtract(Vector2D other) { return new Vector2D(x - other.x, y - other.y); } /** * Multipliziert den Vektor mit einem Skalar. * @param scalar Skalar * @return Neuer Vektor */ public Vector2D multiply(double scalar) { return new Vector2D(x * scalar, y * scalar); } /** * Dividiert den Vektor durch einen Skalar. * @param scalar Skalar * @return Neuer Vektor */ public Vector2D divide(double scalar) { return new Vector2D(x / scalar, y / scalar); } /** * Berechnet die Länge des Vektors. * @return Vektorlänge */ public double length(){ return Math.sqrt(x*x + y*y); } /** * Berechnet die Distanz zu einem anderen Vektor. * @param other Anderer Vektor * @return Distanz */ public double distanceTo(Vector2D other) { return other.subtract(this).length(); } /** * Berechnet den Winkel zu einem anderen Vektor im Bereich * von -180 bis 180 Grad. Ist der andere Vektor im Uhrzeigesinn * gedreht, ist der Winkel postiv, sonst negativ. * * @param other Anderer Vektor * @return Winkel */ public double angleTo(Vector2D other) { return other.getNormalHeading() - getNormalHeading(); } /** * Liefert die Richtung eines Vektors im Bereich von 0 bis 360 Grad. * 0 = Norden, 90 = Osten, 180 = Süden, 270 = Westen * @return Richtung in Grad */ public double getHeading() { double mathAngle = Utils.radToDeg(Math.acos(x / length())); if (y >= 0) { if (x < 0) { return 450 - mathAngle; } else { return 90 - mathAngle; } } else { return mathAngle + 90; } } /** * Liefert die normalisierte Richtung eines Vektors im Bereich von -180 bis 180 Grad. * -180 = Westen, -90 = Norden, 0 = Osten, 90 = Süden * @return Normalisierte Richtung in Grad */ public double getNormalHeading() { double mathAngle = Utils.radToDeg(Math.acos(x / length())); return (y >= 0) ? -1 * mathAngle : mathAngle; } /** * Dreht den Vektor um einen Winkel in Grad. * Die Drehung erfolgt um den Vektorursprung im mathematisch * negativer Richtung (im Uhrzeigesinn). * @param angleDegrees Winkel in Grad * @return Neuer Vektor */ public Vector2D rotate(double angleDegrees) { return rotateRad(Utils.degToRad(angleDegrees)); } /** * Dreht den Vektor um einen Winkel im Bogenmaß. * Die Drehung erfolgt um den Vektorursprung im mathematisch * negativer Richtung (im Uhrzeigesinn). * @param angleRadians Winkel in Rad * @return Neuer Vektor */ public Vector2D rotateRad(double angleRadians) { angleRadians = angleRadians * -1; return new Vector2D(x * Math.cos(angleRadians) - y * Math.sin(angleRadians), x * Math.sin(angleRadians) + y * Math.cos(angleRadians)); } /** * Prüf ob der Vector in einem Rechteck liegt. * @param x * @param y * @param width * @param height * @return */ public boolean inRectangle(double x, double y, double width, double height) { return !(this.x < x || this.y < y || this.x > x + width || this.y > y + height); } /** * Liefert eine String Darstellung der Vektorkoordinaten. */ @Override public String toString() { return String.format(Locale.ENGLISH, "X: %1$,.3f, Y: %2$,.3f", x, y); } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(x); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits(y); result = prime * result + (int) (temp ^ (temp >>> 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Vector2D other = (Vector2D) obj; if (Math.abs(x - other.x) > MAX_DEVIATION) return false; if (Math.abs(y - other.y) > MAX_DEVIATION) return false; return true; } }
False
1,620
26
1,838
28
1,759
24
1,838
28
1,964
29
false
false
false
false
false
true
2,320
105214_1
package nl.hva.ict.ss.pathfinding.weigthedgraph; import java.util.LinkedList; import nl.hva.ict.ss.pathfinding.tileworld.TileType; import nl.hva.ict.ss.pathfinding.tileworld.TileWorldUtil; /** * The {@code EdgeWeightedDigraph} class represents a edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all of edges incident from a given vertex. * It also provides * methods for returning the number of vertices <em>V</em> and the number * of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of @link{Bag} objects. * All operations take constant time (in the worst case) except * iterating over the edges incident from a given vertex, which takes * time proportional to the number of such edges. * <p> * For additional documentation, * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * Overgenomen uit de library algs4-package.jar van Robert Sedgwick * Aanpassingen specifiek t.b.v. PO2 Sorting&amp;Searching * * @author Robert Sedgewick * @author Kevin Wayne * @author Eric Ravestein * @author Nico Tromp */ public class EdgeWeightedDigraph { private final int V; private int E; private final int startIndex; private final int endIndex; private final LinkedList<DirectedEdge>[] adj; private final TileWorldUtil t; private final int breedte; private final int hoogte; /** * Constructor maakt een Digraph aan met V knooppunten (vertices) * Direct overgenomen uit Sedgwick. T.b.v. Floyd-Warshall * @param V aantal knooppunten */ public EdgeWeightedDigraph(int V) { if (V < 0) { throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative"); } this.V = V; this.E = 0; hoogte = 0; breedte = 0; t = null; startIndex = 0; endIndex = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; for (int v = 0; v < V; v++) { adj[v] = new LinkedList<DirectedEdge>(); } } /** * Constructor. * Leest de TileWorldUtil in van bitmap fileName+".png" en * maakt de adjacency list adj * * @param fileName filenaam van de bitmap */ public EdgeWeightedDigraph(String fileName) { t = new TileWorldUtil(fileName + ".png"); // Aantal knopen hoogte = t.getHeight(); breedte = t.getWidth(); this.V = hoogte * breedte; // Start- en Eindindex this.startIndex = t.findStartIndex(); this.endIndex = t.findEndIndex(); this.E = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; int v; for (v = 0; v < V; v++) { adj[v] = findAdjacent(v); } } /** * getter voor het aantal knooppunten * @return aantal knooppunten */ public int V() { return V; } /** * Bewaart de bitmap onder de naam fileName. * @param fileName naam van de bitmap */ public void save(String fileName) { t.save(fileName); } /** * Maakt een Digraph met een adjacency matrix in plaats van een * adjacencylist. * Nodig voor Floyd=Warshall algoritme. * * @return een Digraph met Adjacencymatrix in plaats van list. */ public AdjMatrixEdgeWeightedDigraph createAdjMatrixEdgeWeightedDigraph() { AdjMatrixEdgeWeightedDigraph g; Iterable<DirectedEdge> edges; g = new AdjMatrixEdgeWeightedDigraph(V); edges = edges(); for (DirectedEdge d : edges) { g.addEdge(d); } return g; } /** * Zoekt alle aanliggende knoopunten van knooppunt v. * * @param v het te onderzoeken knooppunt * @return LinkedList van alle aanliggende (=bereikbare) * knooppunten met de cost om daar te komen. */ private LinkedList<DirectedEdge> findAdjacent(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); LinkedList<DirectedEdge> b = new LinkedList<DirectedEdge>(); if (x > 0) { // naar Links b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y), t.getTileType(x - 1, y).getCost())); if (y > 0) { // Links onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y - 1), t.getTileType(x - 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Links boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y + 1), t.getTileType(x - 1, y + 1).getDiagonalCost())); } } if (x < breedte - 1) { // Rechts b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y), t.getTileType(x + 1, y).getCost())); if (y > 0) { // Rechts onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y - 1), t.getTileType(x + 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Rechts boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y + 1), t.getTileType(x + 1, y + 1).getDiagonalCost())); } } if (y > 0) { // Onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y - 1), t.getTileType(x, y - 1).getCost())); } if (y < hoogte - 1) { // Boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y + 1), t.getTileType(x, y + 1).getCost())); } return b; } /** * Geeft de x coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getX(int v) { return t.oneDimToTwoDimXCoordinate(v); } /** * Geeft de y coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getY(int v) { return t.oneDimToTwoDimYCoordinate(v); } /** * Geeft de index in de adjacency list van het knooppunt dat in de TileWorldUtil t een coordinaat (x,y) heeft. * @param x x-coordinaat van te onderzoeken punt * @param y y-coordinaat van te onderzoeken punt * @return index van dit punt in de adjacencylist adj */ public int getIndex(int x, int y) { return t.twoDimIndexToOneDimIndex(x, y); } /** * Bepaalt alle aanliggende edges van knooppunt v * @param v het te onderzoeken knooppunt * @return lijst van edges die beginnen of eindigen in v */ public Iterable<DirectedEdge> adj(int v) { return adj[v]; } /** * Maakt een grote list van alle edges in de Digraph * @return LinkedList met alle edges */ public Iterable<DirectedEdge> edges() { LinkedList<DirectedEdge> list = new LinkedList<>(); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj[v]) { list.add(e); } } return list; } /** * getter voor het Startpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getStart() { return (startIndex); } /** * getter voor het Eindpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getEnd() { return (endIndex); } /** * Laat de bitmap zien in een jFrame * @param filename naam van de bitmap * @param title aanvullende titel ter specificatie van de bitmap */ public void show(String filename, String title) { t.show(filename + ".png " + title, 10, 0, 0); } /** * Tekent het pad sp in de juiste kleur in de bitmap. * @param sp het te tekenen pad */ public void tekenPad(Iterable<DirectedEdge> sp) { for (DirectedEdge de : sp) { int x = t.oneDimToTwoDimXCoordinate(de.from()); int y = t.oneDimToTwoDimYCoordinate(de.from()); t.setTileType(x, y, TileType.PATH); } } public TileType markAsVisited(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); TileType currentType = t.getTileType(x, y); t.setTileType(x, y, TileType.UNKNOWN); return currentType; } /** * Adds the directed edge e to the edge-weighted digraph. * * Uit Sedgwick: tbv Floyd-Warshall * @param e the edge */ public void addEdge(DirectedEdge e) { int v = e.from(); adj[v].add(e); E++; } }
buracc/Sorting-Searching
Assignment-2/src/main/java/nl/hva/ict/ss/pathfinding/weigthedgraph/EdgeWeightedDigraph.java
3,109
/** * Constructor maakt een Digraph aan met V knooppunten (vertices) * Direct overgenomen uit Sedgwick. T.b.v. Floyd-Warshall * @param V aantal knooppunten */
block_comment
nl
package nl.hva.ict.ss.pathfinding.weigthedgraph; import java.util.LinkedList; import nl.hva.ict.ss.pathfinding.tileworld.TileType; import nl.hva.ict.ss.pathfinding.tileworld.TileWorldUtil; /** * The {@code EdgeWeightedDigraph} class represents a edge-weighted * digraph of vertices named 0 through <em>V</em> - 1, where each * directed edge is of type {@link DirectedEdge} and has a real-valued weight. * It supports the following two primary operations: add a directed edge * to the digraph and iterate over all of edges incident from a given vertex. * It also provides * methods for returning the number of vertices <em>V</em> and the number * of edges <em>E</em>. Parallel edges and self-loops are permitted. * <p> * This implementation uses an adjacency-lists representation, which * is a vertex-indexed array of @link{Bag} objects. * All operations take constant time (in the worst case) except * iterating over the edges incident from a given vertex, which takes * time proportional to the number of such edges. * <p> * For additional documentation, * see <a href="http://algs4.cs.princeton.edu/44sp">Section 4.4</a> of * <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne. * * Overgenomen uit de library algs4-package.jar van Robert Sedgwick * Aanpassingen specifiek t.b.v. PO2 Sorting&amp;Searching * * @author Robert Sedgewick * @author Kevin Wayne * @author Eric Ravestein * @author Nico Tromp */ public class EdgeWeightedDigraph { private final int V; private int E; private final int startIndex; private final int endIndex; private final LinkedList<DirectedEdge>[] adj; private final TileWorldUtil t; private final int breedte; private final int hoogte; /** * Constructor maakt een<SUF>*/ public EdgeWeightedDigraph(int V) { if (V < 0) { throw new IllegalArgumentException("Number of vertices in a Digraph must be nonnegative"); } this.V = V; this.E = 0; hoogte = 0; breedte = 0; t = null; startIndex = 0; endIndex = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; for (int v = 0; v < V; v++) { adj[v] = new LinkedList<DirectedEdge>(); } } /** * Constructor. * Leest de TileWorldUtil in van bitmap fileName+".png" en * maakt de adjacency list adj * * @param fileName filenaam van de bitmap */ public EdgeWeightedDigraph(String fileName) { t = new TileWorldUtil(fileName + ".png"); // Aantal knopen hoogte = t.getHeight(); breedte = t.getWidth(); this.V = hoogte * breedte; // Start- en Eindindex this.startIndex = t.findStartIndex(); this.endIndex = t.findEndIndex(); this.E = 0; adj = (LinkedList<DirectedEdge>[]) new LinkedList[V]; int v; for (v = 0; v < V; v++) { adj[v] = findAdjacent(v); } } /** * getter voor het aantal knooppunten * @return aantal knooppunten */ public int V() { return V; } /** * Bewaart de bitmap onder de naam fileName. * @param fileName naam van de bitmap */ public void save(String fileName) { t.save(fileName); } /** * Maakt een Digraph met een adjacency matrix in plaats van een * adjacencylist. * Nodig voor Floyd=Warshall algoritme. * * @return een Digraph met Adjacencymatrix in plaats van list. */ public AdjMatrixEdgeWeightedDigraph createAdjMatrixEdgeWeightedDigraph() { AdjMatrixEdgeWeightedDigraph g; Iterable<DirectedEdge> edges; g = new AdjMatrixEdgeWeightedDigraph(V); edges = edges(); for (DirectedEdge d : edges) { g.addEdge(d); } return g; } /** * Zoekt alle aanliggende knoopunten van knooppunt v. * * @param v het te onderzoeken knooppunt * @return LinkedList van alle aanliggende (=bereikbare) * knooppunten met de cost om daar te komen. */ private LinkedList<DirectedEdge> findAdjacent(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); LinkedList<DirectedEdge> b = new LinkedList<DirectedEdge>(); if (x > 0) { // naar Links b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y), t.getTileType(x - 1, y).getCost())); if (y > 0) { // Links onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y - 1), t.getTileType(x - 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Links boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x - 1, y + 1), t.getTileType(x - 1, y + 1).getDiagonalCost())); } } if (x < breedte - 1) { // Rechts b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y), t.getTileType(x + 1, y).getCost())); if (y > 0) { // Rechts onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y - 1), t.getTileType(x + 1, y - 1).getDiagonalCost())); } if (y < hoogte - 1) { // Rechts boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x + 1, y + 1), t.getTileType(x + 1, y + 1).getDiagonalCost())); } } if (y > 0) { // Onder b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y - 1), t.getTileType(x, y - 1).getCost())); } if (y < hoogte - 1) { // Boven b.add(new DirectedEdge(v, t.twoDimIndexToOneDimIndex(x, y + 1), t.getTileType(x, y + 1).getCost())); } return b; } /** * Geeft de x coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getX(int v) { return t.oneDimToTwoDimXCoordinate(v); } /** * Geeft de y coordinaat van knooppunt v in de bitmap. * * @param v index van knoopunt v * @return x coordinaat */ public int getY(int v) { return t.oneDimToTwoDimYCoordinate(v); } /** * Geeft de index in de adjacency list van het knooppunt dat in de TileWorldUtil t een coordinaat (x,y) heeft. * @param x x-coordinaat van te onderzoeken punt * @param y y-coordinaat van te onderzoeken punt * @return index van dit punt in de adjacencylist adj */ public int getIndex(int x, int y) { return t.twoDimIndexToOneDimIndex(x, y); } /** * Bepaalt alle aanliggende edges van knooppunt v * @param v het te onderzoeken knooppunt * @return lijst van edges die beginnen of eindigen in v */ public Iterable<DirectedEdge> adj(int v) { return adj[v]; } /** * Maakt een grote list van alle edges in de Digraph * @return LinkedList met alle edges */ public Iterable<DirectedEdge> edges() { LinkedList<DirectedEdge> list = new LinkedList<>(); for (int v = 0; v < V; v++) { for (DirectedEdge e : adj[v]) { list.add(e); } } return list; } /** * getter voor het Startpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getStart() { return (startIndex); } /** * getter voor het Eindpunt van het te zoeken pad. * * @return index in de adjacency list van het startpunt */ public int getEnd() { return (endIndex); } /** * Laat de bitmap zien in een jFrame * @param filename naam van de bitmap * @param title aanvullende titel ter specificatie van de bitmap */ public void show(String filename, String title) { t.show(filename + ".png " + title, 10, 0, 0); } /** * Tekent het pad sp in de juiste kleur in de bitmap. * @param sp het te tekenen pad */ public void tekenPad(Iterable<DirectedEdge> sp) { for (DirectedEdge de : sp) { int x = t.oneDimToTwoDimXCoordinate(de.from()); int y = t.oneDimToTwoDimYCoordinate(de.from()); t.setTileType(x, y, TileType.PATH); } } public TileType markAsVisited(int v) { int x = t.oneDimToTwoDimXCoordinate(v); int y = t.oneDimToTwoDimYCoordinate(v); TileType currentType = t.getTileType(x, y); t.setTileType(x, y, TileType.UNKNOWN); return currentType; } /** * Adds the directed edge e to the edge-weighted digraph. * * Uit Sedgwick: tbv Floyd-Warshall * @param e the edge */ public void addEdge(DirectedEdge e) { int v = e.from(); adj[v].add(e); E++; } }
True
2,520
54
2,737
57
2,819
54
2,738
57
3,120
64
false
false
false
false
false
true
2,118
41146_4
/** * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * * 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 * * https://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.pkl.core; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.stream.StreamSupport; import org.pkl.core.packages.PackageAssetUri; import org.pkl.core.runtime.VmContext; import org.pkl.core.settings.PklSettings; import org.pkl.core.util.IoUtils; /** Static factory for stack frame transformers. */ public final class StackFrameTransformers { private StackFrameTransformers() {} public static final StackFrameTransformer empty = s -> s; public static final StackFrameTransformer convertStdLibUrlToExternalUrl = frame -> { var uri = frame.getModuleUri(); if (uri.startsWith("pkl:")) { var moduleName = uri.substring(4); return frame.withModuleUri( Release.current() .sourceCode() .getFilePage("stdlib/" + moduleName + ".pkl#L" + frame.getStartLine())); } return frame; }; public static final StackFrameTransformer replacePackageUriWithSourceCodeUrl = frame -> { var uri = URI.create(frame.getModuleUri()); if (!uri.getScheme().equalsIgnoreCase("package")) { return frame; } try { var assetUri = new PackageAssetUri(uri); var packageResolver = VmContext.get(null).getPackageResolver(); assert packageResolver != null; var pkg = packageResolver.getDependencyMetadata(assetUri.getPackageUri(), null); var sourceCode = pkg.getSourceCodeUrlScheme(); if (sourceCode == null) { return frame; } return transformUri(frame, uri.getFragment(), sourceCode); } catch (IOException | URISyntaxException | SecurityManagerException e) { // should never get here. by this point, we should have already performed all validation // and downloaded all assets. throw PklBugException.unreachableCode(); } }; public static final StackFrameTransformer fromServiceProviders = loadFromServiceProviders(); public static final StackFrameTransformer defaultTransformer = fromServiceProviders .andThen(convertStdLibUrlToExternalUrl) .andThen(replacePackageUriWithSourceCodeUrl); private static StackFrame transformUri(StackFrame frame, String path, String format) { var uri = frame.getModuleUri(); var newUri = format .replace("%{path}", path) .replace("%{url}", uri) .replace("%{line}", String.valueOf(frame.getStartLine())) .replace("%{endLine}", String.valueOf(frame.getEndLine())) .replace("%{column}", String.valueOf(frame.getStartColumn())) .replace("%{endColumn}", String.valueOf(frame.getEndColumn())); return frame.withModuleUri(newUri); } public static StackFrameTransformer convertFilePathToUriScheme(String scheme) { return frame -> { var uri = frame.getModuleUri(); if (!uri.startsWith("file:")) return frame; return transformUri(frame, Path.of(URI.create(uri)).toString(), scheme); }; } public static StackFrameTransformer relativizeModuleUri(URI baseUri) { return frame -> { var uri = URI.create(frame.getModuleUri()); var relativized = baseUri.relativize(uri); return frame.withModuleUri(relativized.toString()); }; } public static StackFrameTransformer createDefault(PklSettings settings) { return defaultTransformer // order is relevant .andThen(convertFilePathToUriScheme(settings.getEditor().getUrlScheme())); } private static StackFrameTransformer loadFromServiceProviders() { var loader = IoUtils.createServiceLoader(StackFrameTransformer.class); return StreamSupport.stream(loader.spliterator(), false) .reduce((t1, t2) -> t1.andThen(t2)) .orElse(t -> t); // use no-op transformer if no service providers found } }
apple/pkl
pkl-core/src/main/java/org/pkl/core/StackFrameTransformers.java
1,259
// order is relevant
line_comment
nl
/** * Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved. * * 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 * * https://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.pkl.core; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; import java.util.stream.StreamSupport; import org.pkl.core.packages.PackageAssetUri; import org.pkl.core.runtime.VmContext; import org.pkl.core.settings.PklSettings; import org.pkl.core.util.IoUtils; /** Static factory for stack frame transformers. */ public final class StackFrameTransformers { private StackFrameTransformers() {} public static final StackFrameTransformer empty = s -> s; public static final StackFrameTransformer convertStdLibUrlToExternalUrl = frame -> { var uri = frame.getModuleUri(); if (uri.startsWith("pkl:")) { var moduleName = uri.substring(4); return frame.withModuleUri( Release.current() .sourceCode() .getFilePage("stdlib/" + moduleName + ".pkl#L" + frame.getStartLine())); } return frame; }; public static final StackFrameTransformer replacePackageUriWithSourceCodeUrl = frame -> { var uri = URI.create(frame.getModuleUri()); if (!uri.getScheme().equalsIgnoreCase("package")) { return frame; } try { var assetUri = new PackageAssetUri(uri); var packageResolver = VmContext.get(null).getPackageResolver(); assert packageResolver != null; var pkg = packageResolver.getDependencyMetadata(assetUri.getPackageUri(), null); var sourceCode = pkg.getSourceCodeUrlScheme(); if (sourceCode == null) { return frame; } return transformUri(frame, uri.getFragment(), sourceCode); } catch (IOException | URISyntaxException | SecurityManagerException e) { // should never get here. by this point, we should have already performed all validation // and downloaded all assets. throw PklBugException.unreachableCode(); } }; public static final StackFrameTransformer fromServiceProviders = loadFromServiceProviders(); public static final StackFrameTransformer defaultTransformer = fromServiceProviders .andThen(convertStdLibUrlToExternalUrl) .andThen(replacePackageUriWithSourceCodeUrl); private static StackFrame transformUri(StackFrame frame, String path, String format) { var uri = frame.getModuleUri(); var newUri = format .replace("%{path}", path) .replace("%{url}", uri) .replace("%{line}", String.valueOf(frame.getStartLine())) .replace("%{endLine}", String.valueOf(frame.getEndLine())) .replace("%{column}", String.valueOf(frame.getStartColumn())) .replace("%{endColumn}", String.valueOf(frame.getEndColumn())); return frame.withModuleUri(newUri); } public static StackFrameTransformer convertFilePathToUriScheme(String scheme) { return frame -> { var uri = frame.getModuleUri(); if (!uri.startsWith("file:")) return frame; return transformUri(frame, Path.of(URI.create(uri)).toString(), scheme); }; } public static StackFrameTransformer relativizeModuleUri(URI baseUri) { return frame -> { var uri = URI.create(frame.getModuleUri()); var relativized = baseUri.relativize(uri); return frame.withModuleUri(relativized.toString()); }; } public static StackFrameTransformer createDefault(PklSettings settings) { return defaultTransformer // order is<SUF> .andThen(convertFilePathToUriScheme(settings.getEditor().getUrlScheme())); } private static StackFrameTransformer loadFromServiceProviders() { var loader = IoUtils.createServiceLoader(StackFrameTransformer.class); return StreamSupport.stream(loader.spliterator(), false) .reduce((t1, t2) -> t1.andThen(t2)) .orElse(t -> t); // use no-op transformer if no service providers found } }
True
957
4
1,064
4
1,147
4
1,064
4
1,252
4
false
false
false
false
false
true
4,123
24577_6
package nl.consumergram.consumergramv2.services; import jakarta.persistence.EntityNotFoundException; import nl.consumergram.consumergramv2.dtos.UserDto; import nl.consumergram.consumergramv2.models.User; import nl.consumergram.consumergramv2.repositories.UserRepository; import nl.consumergram.consumergramv2.utils.RandomStringGenerator; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserService { public PasswordEncoder passwordEncoder; // De constructor injecteert een instantie van UserRepository private final UserRepository userRepository; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } // // Opslaan van het versleutelde wachtwoord in de database of ergens anders // userRepository.save(new User(UserDto.getUsername(), encodedPassword)); // } public List<UserDto> getUsers() { List<UserDto> collection = new ArrayList<>(); List<User> list = userRepository.findAll(); for (User user : list) { collection.add(fromUser(user)); } return collection; } // Haalt een specifieke gebruiker op basis van de gebruikersnaam en converteert deze naar een UserDto public UserDto getUser(String username) { UserDto dto = new UserDto(); Optional<User> user = userRepository.findById(username); if (user.isPresent()) { dto = fromUser(user.get()); } else { throw new UsernameNotFoundException(username); } return dto; } // Controleert of een gebruiker met de opgegeven gebruikersnaam bestaat. public boolean userExists(String username) { return userRepository.existsById(username); } // Genereert een willekeurige API-sleutel, stelt deze in op de UserDto en slaat een nieuwe gebruiker op in de database. Geeft de gebruikersnaam van de aangemaakte gebruiker terug. public String createUser(UserDto userDto) { String randomString = RandomStringGenerator.generateAlphaNumeric(20); userDto.setApikey(randomString); User newUser = userRepository.save(toUser(userDto)); return newUser.getUsername(); } // Verwijdert een gebruiker op basis van de gebruikersnaam. public void deleteUser(String username) { userRepository.deleteById(username); } public UserDto updateUser(String username, UserDto dto) { User user = userRepository.findByUsername(username) .orElseThrow(() -> new EntityNotFoundException("User not found with username " + username)); user.setEmail(dto.getEmail()); user.setUsername(dto.getUsername()); // Check if the password field in the incoming UserDto is null or empty if (dto.getPassword() != null && !dto.getPassword().isEmpty()) { user.setPassword(passwordEncoder.encode(dto.getPassword())); } User updatedUser = userRepository.save(user); UserDto updatedUserDto = convertToDto(updatedUser); return updatedUserDto; } public UserDto convertToDto(User user) { UserDto userDto = new UserDto(); userDto.setUsername(user.getUsername()); userDto.setPassword(user.getPassword()); userDto.setEnabled(user.isEnabled()); userDto.setApikey(user.getApikey()); userDto.setEmail(user.getEmail()); userDto.setAuthorities(user.getAuthorities()); return userDto; } // Zet een User-object om naar een UserDto public static UserDto fromUser(User user) { var dto = new UserDto(); // In de code lijkt getUsername() de // gebruikersnaam terug te geven, die vaak wordt gebruikt als een unieke // identificator voor een gebruiker. dto.username = user.getUsername(); dto.password = user.getPassword(); dto.enabled = user.isEnabled(); dto.apikey = user.getApikey(); dto.email = user.getEmail(); dto.authorities = user.getAuthorities(); return dto; } // Zet een UserDto-object om naar een User. public User toUser(UserDto userDto) { var user = new User(); user.setUsername(userDto.getUsername()); user.setPassword(passwordEncoder.encode(userDto.password)); // user.setPassword(userDto.getPassword()); user.setEnabled(userDto.getEnabled()); user.setApikey(userDto.getApikey()); user.setEmail(userDto.getEmail()); return user; } }
rayzathegrave/ConsumerGramBackendv2
src/main/java/nl/consumergram/consumergramv2/services/UserService.java
1,406
// Verwijdert een gebruiker op basis van de gebruikersnaam.
line_comment
nl
package nl.consumergram.consumergramv2.services; import jakarta.persistence.EntityNotFoundException; import nl.consumergram.consumergramv2.dtos.UserDto; import nl.consumergram.consumergramv2.models.User; import nl.consumergram.consumergramv2.repositories.UserRepository; import nl.consumergram.consumergramv2.utils.RandomStringGenerator; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class UserService { public PasswordEncoder passwordEncoder; // De constructor injecteert een instantie van UserRepository private final UserRepository userRepository; public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.passwordEncoder = passwordEncoder; } // // Opslaan van het versleutelde wachtwoord in de database of ergens anders // userRepository.save(new User(UserDto.getUsername(), encodedPassword)); // } public List<UserDto> getUsers() { List<UserDto> collection = new ArrayList<>(); List<User> list = userRepository.findAll(); for (User user : list) { collection.add(fromUser(user)); } return collection; } // Haalt een specifieke gebruiker op basis van de gebruikersnaam en converteert deze naar een UserDto public UserDto getUser(String username) { UserDto dto = new UserDto(); Optional<User> user = userRepository.findById(username); if (user.isPresent()) { dto = fromUser(user.get()); } else { throw new UsernameNotFoundException(username); } return dto; } // Controleert of een gebruiker met de opgegeven gebruikersnaam bestaat. public boolean userExists(String username) { return userRepository.existsById(username); } // Genereert een willekeurige API-sleutel, stelt deze in op de UserDto en slaat een nieuwe gebruiker op in de database. Geeft de gebruikersnaam van de aangemaakte gebruiker terug. public String createUser(UserDto userDto) { String randomString = RandomStringGenerator.generateAlphaNumeric(20); userDto.setApikey(randomString); User newUser = userRepository.save(toUser(userDto)); return newUser.getUsername(); } // Verwijdert een<SUF> public void deleteUser(String username) { userRepository.deleteById(username); } public UserDto updateUser(String username, UserDto dto) { User user = userRepository.findByUsername(username) .orElseThrow(() -> new EntityNotFoundException("User not found with username " + username)); user.setEmail(dto.getEmail()); user.setUsername(dto.getUsername()); // Check if the password field in the incoming UserDto is null or empty if (dto.getPassword() != null && !dto.getPassword().isEmpty()) { user.setPassword(passwordEncoder.encode(dto.getPassword())); } User updatedUser = userRepository.save(user); UserDto updatedUserDto = convertToDto(updatedUser); return updatedUserDto; } public UserDto convertToDto(User user) { UserDto userDto = new UserDto(); userDto.setUsername(user.getUsername()); userDto.setPassword(user.getPassword()); userDto.setEnabled(user.isEnabled()); userDto.setApikey(user.getApikey()); userDto.setEmail(user.getEmail()); userDto.setAuthorities(user.getAuthorities()); return userDto; } // Zet een User-object om naar een UserDto public static UserDto fromUser(User user) { var dto = new UserDto(); // In de code lijkt getUsername() de // gebruikersnaam terug te geven, die vaak wordt gebruikt als een unieke // identificator voor een gebruiker. dto.username = user.getUsername(); dto.password = user.getPassword(); dto.enabled = user.isEnabled(); dto.apikey = user.getApikey(); dto.email = user.getEmail(); dto.authorities = user.getAuthorities(); return dto; } // Zet een UserDto-object om naar een User. public User toUser(UserDto userDto) { var user = new User(); user.setUsername(userDto.getUsername()); user.setPassword(passwordEncoder.encode(userDto.password)); // user.setPassword(userDto.getPassword()); user.setEnabled(userDto.getEnabled()); user.setApikey(userDto.getApikey()); user.setEmail(userDto.getEmail()); return user; } }
True
957
18
1,168
19
1,157
15
1,168
19
1,401
19
false
false
false
false
false
true
3,334
64986_6
package prefuse.render;_x000D_ _x000D_ import java.awt.FontMetrics;_x000D_ import java.awt.Graphics2D;_x000D_ import java.awt.Shape;_x000D_ import java.awt.geom.AffineTransform;_x000D_ import java.awt.geom.Line2D;_x000D_ import java.awt.geom.Point2D;_x000D_ import java.awt.geom.Rectangle2D;_x000D_ _x000D_ import prefuse.Constants;_x000D_ import prefuse.util.ColorLib;_x000D_ import prefuse.util.GraphicsLib;_x000D_ import prefuse.visual.VisualItem;_x000D_ _x000D_ /**_x000D_ * Renderer for drawing an axis tick mark and label._x000D_ * _x000D_ * @author <a href="http://jheer.org">jeffrey heer</a>_x000D_ * @author jgood_x000D_ */_x000D_ public class AxisRenderer extends AbstractShapeRenderer {_x000D_ _x000D_ private Line2D m_line = new Line2D.Double();_x000D_ private Rectangle2D m_box = new Rectangle2D.Double();_x000D_ _x000D_ private int m_xalign;_x000D_ private int m_yalign;_x000D_ private int m_ascent;_x000D_ _x000D_ /**_x000D_ * Create a new AxisRenderer. By default, axis labels are drawn along the_x000D_ * left edge and underneath the tick marks._x000D_ */_x000D_ public AxisRenderer() {_x000D_ this(Constants.LEFT, Constants.BOTTOM);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Create a new AxisRenderer._x000D_ * @param xalign the horizontal alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#LEFT}, {@link prefuse.Constants#RIGHT},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ * @param yalign the vertical alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#TOP}, {@link prefuse.Constants#BOTTOM},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ */_x000D_ public AxisRenderer(int xalign, int yalign) {_x000D_ m_xalign = xalign;_x000D_ m_yalign = yalign;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Set the horizontal alignment of axis labels._x000D_ * @param xalign the horizontal alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#LEFT}, {@link prefuse.Constants#RIGHT},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ */_x000D_ public void setHorizontalAlignment(int xalign) {_x000D_ m_xalign = xalign;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Set the vertical alignment of axis labels._x000D_ * @param yalign the vertical alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#TOP}, {@link prefuse.Constants#BOTTOM},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ */_x000D_ public void setVerticalAlignment(int yalign) {_x000D_ m_yalign = yalign;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.AbstractShapeRenderer#getRawShape(prefuse.visual.VisualItem)_x000D_ */_x000D_ protected Shape getRawShape(VisualItem item) {_x000D_ double x1 = item.getDouble(VisualItem.X);_x000D_ double y1 = item.getDouble(VisualItem.Y);_x000D_ double x2 = item.getDouble(VisualItem.X2);_x000D_ double y2 = item.getDouble(VisualItem.Y2);_x000D_ m_line.setLine(x1,y1,x2,y2);_x000D_ _x000D_ if ( !item.canGetString(VisualItem.LABEL) )_x000D_ return m_line;_x000D_ _x000D_ String label = item.getString(VisualItem.LABEL);_x000D_ if ( label == null ) return m_line;_x000D_ _x000D_ FontMetrics fm = DEFAULT_GRAPHICS.getFontMetrics(item.getFont());_x000D_ m_ascent = fm.getAscent();_x000D_ int h = fm.getHeight();_x000D_ int w = fm.stringWidth(label);_x000D_ _x000D_ double tx, ty;_x000D_ _x000D_ // get text x-coord_x000D_ switch ( m_xalign ) {_x000D_ case Constants.FAR_RIGHT:_x000D_ tx = x2 + 2;_x000D_ break;_x000D_ case Constants.FAR_LEFT:_x000D_ tx = x1 - w - 2;_x000D_ break;_x000D_ case Constants.CENTER:_x000D_ tx = x1 + (x2-x1)/2 - w/2;_x000D_ break;_x000D_ case Constants.RIGHT:_x000D_ tx = x2 - w;_x000D_ break;_x000D_ case Constants.LEFT:_x000D_ default:_x000D_ tx = x1;_x000D_ }_x000D_ // get text y-coord_x000D_ switch ( m_yalign ) {_x000D_ case Constants.FAR_TOP:_x000D_ ty = y1-h;_x000D_ break;_x000D_ case Constants.FAR_BOTTOM:_x000D_ ty = y2;_x000D_ break;_x000D_ case Constants.CENTER:_x000D_ ty = y1 + (y2-y1)/2 - h/2;_x000D_ break;_x000D_ case Constants.TOP:_x000D_ ty = y1;_x000D_ break;_x000D_ case Constants.BOTTOM:_x000D_ default:_x000D_ ty = y2-h; _x000D_ }_x000D_ m_box.setFrame(tx,ty,w,h);_x000D_ return m_box;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.Renderer#render(java.awt.Graphics2D, prefuse.visual.VisualItem)_x000D_ */_x000D_ public void render(Graphics2D g, VisualItem item) { _x000D_ Shape s = getShape(item); _x000D_ GraphicsLib.paint(g, item, m_line, getStroke(item), getRenderType(item)); _x000D_ _x000D_ // check if we have a text label, if so, render it _x000D_ if ( item.canGetString(VisualItem.LABEL) ) { _x000D_ float x = (float)m_box.getMinX(); _x000D_ float y = (float)m_box.getMinY() + m_ascent; _x000D_ _x000D_ // draw label background _x000D_ GraphicsLib.paint(g, item, s, null, RENDER_TYPE_FILL); _x000D_ _x000D_ String str = item.getString(VisualItem.LABEL); _x000D_ AffineTransform origTransform = g.getTransform();_x000D_ AffineTransform transform = this.getTransform(item);_x000D_ if ( transform != null ) g.setTransform(transform);_x000D_ _x000D_ g.setFont(item.getFont()); _x000D_ g.setColor(ColorLib.getColor(item.getTextColor())); _x000D_ g.drawString(str, x, y);_x000D_ _x000D_ if ( transform != null ) g.setTransform(origTransform); _x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.Renderer#locatePoint(java.awt.geom.Point2D, prefuse.visual.VisualItem)_x000D_ */_x000D_ public boolean locatePoint(Point2D p, VisualItem item) {_x000D_ Shape s = getShape(item);_x000D_ if ( s == null ) {_x000D_ return false;_x000D_ } else if ( s == m_box && m_box.contains(p) ) {_x000D_ return true;_x000D_ } else {_x000D_ double width = Math.max(2, item.getSize());_x000D_ double halfWidth = width/2.0;_x000D_ return s.intersects(p.getX()-halfWidth,_x000D_ p.getY()-halfWidth,_x000D_ width,width);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.Renderer#setBounds(prefuse.visual.VisualItem)_x000D_ */_x000D_ public void setBounds(VisualItem item) {_x000D_ if ( !m_manageBounds ) return;_x000D_ Shape shape = getShape(item);_x000D_ if ( shape == null ) {_x000D_ item.setBounds(item.getX(), item.getY(), 0, 0);_x000D_ } else if ( shape == m_line ) {_x000D_ GraphicsLib.setBounds(item, shape, getStroke(item));_x000D_ } else {_x000D_ m_box.add(m_line.getX1(),m_line.getY1());_x000D_ m_box.add(m_line.getX2(),m_line.getY2());_x000D_ item.setBounds(m_box.getMinX(), m_box.getMinY(),_x000D_ m_box.getWidth(), m_box.getHeight());_x000D_ }_x000D_ }_x000D_ _x000D_ } // end of class AxisRenderer_x000D_
kaspp/ISPrototype
src/prefuse/render/AxisRenderer.java
2,193
// get text x-coord_x000D_
line_comment
nl
package prefuse.render;_x000D_ _x000D_ import java.awt.FontMetrics;_x000D_ import java.awt.Graphics2D;_x000D_ import java.awt.Shape;_x000D_ import java.awt.geom.AffineTransform;_x000D_ import java.awt.geom.Line2D;_x000D_ import java.awt.geom.Point2D;_x000D_ import java.awt.geom.Rectangle2D;_x000D_ _x000D_ import prefuse.Constants;_x000D_ import prefuse.util.ColorLib;_x000D_ import prefuse.util.GraphicsLib;_x000D_ import prefuse.visual.VisualItem;_x000D_ _x000D_ /**_x000D_ * Renderer for drawing an axis tick mark and label._x000D_ * _x000D_ * @author <a href="http://jheer.org">jeffrey heer</a>_x000D_ * @author jgood_x000D_ */_x000D_ public class AxisRenderer extends AbstractShapeRenderer {_x000D_ _x000D_ private Line2D m_line = new Line2D.Double();_x000D_ private Rectangle2D m_box = new Rectangle2D.Double();_x000D_ _x000D_ private int m_xalign;_x000D_ private int m_yalign;_x000D_ private int m_ascent;_x000D_ _x000D_ /**_x000D_ * Create a new AxisRenderer. By default, axis labels are drawn along the_x000D_ * left edge and underneath the tick marks._x000D_ */_x000D_ public AxisRenderer() {_x000D_ this(Constants.LEFT, Constants.BOTTOM);_x000D_ }_x000D_ _x000D_ /**_x000D_ * Create a new AxisRenderer._x000D_ * @param xalign the horizontal alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#LEFT}, {@link prefuse.Constants#RIGHT},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ * @param yalign the vertical alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#TOP}, {@link prefuse.Constants#BOTTOM},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ */_x000D_ public AxisRenderer(int xalign, int yalign) {_x000D_ m_xalign = xalign;_x000D_ m_yalign = yalign;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Set the horizontal alignment of axis labels._x000D_ * @param xalign the horizontal alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#LEFT}, {@link prefuse.Constants#RIGHT},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ */_x000D_ public void setHorizontalAlignment(int xalign) {_x000D_ m_xalign = xalign;_x000D_ }_x000D_ _x000D_ /**_x000D_ * Set the vertical alignment of axis labels._x000D_ * @param yalign the vertical alignment for the axis label. One of_x000D_ * {@link prefuse.Constants#TOP}, {@link prefuse.Constants#BOTTOM},_x000D_ * or {@link prefuse.Constants#CENTER}._x000D_ */_x000D_ public void setVerticalAlignment(int yalign) {_x000D_ m_yalign = yalign;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.AbstractShapeRenderer#getRawShape(prefuse.visual.VisualItem)_x000D_ */_x000D_ protected Shape getRawShape(VisualItem item) {_x000D_ double x1 = item.getDouble(VisualItem.X);_x000D_ double y1 = item.getDouble(VisualItem.Y);_x000D_ double x2 = item.getDouble(VisualItem.X2);_x000D_ double y2 = item.getDouble(VisualItem.Y2);_x000D_ m_line.setLine(x1,y1,x2,y2);_x000D_ _x000D_ if ( !item.canGetString(VisualItem.LABEL) )_x000D_ return m_line;_x000D_ _x000D_ String label = item.getString(VisualItem.LABEL);_x000D_ if ( label == null ) return m_line;_x000D_ _x000D_ FontMetrics fm = DEFAULT_GRAPHICS.getFontMetrics(item.getFont());_x000D_ m_ascent = fm.getAscent();_x000D_ int h = fm.getHeight();_x000D_ int w = fm.stringWidth(label);_x000D_ _x000D_ double tx, ty;_x000D_ _x000D_ // get text<SUF> switch ( m_xalign ) {_x000D_ case Constants.FAR_RIGHT:_x000D_ tx = x2 + 2;_x000D_ break;_x000D_ case Constants.FAR_LEFT:_x000D_ tx = x1 - w - 2;_x000D_ break;_x000D_ case Constants.CENTER:_x000D_ tx = x1 + (x2-x1)/2 - w/2;_x000D_ break;_x000D_ case Constants.RIGHT:_x000D_ tx = x2 - w;_x000D_ break;_x000D_ case Constants.LEFT:_x000D_ default:_x000D_ tx = x1;_x000D_ }_x000D_ // get text y-coord_x000D_ switch ( m_yalign ) {_x000D_ case Constants.FAR_TOP:_x000D_ ty = y1-h;_x000D_ break;_x000D_ case Constants.FAR_BOTTOM:_x000D_ ty = y2;_x000D_ break;_x000D_ case Constants.CENTER:_x000D_ ty = y1 + (y2-y1)/2 - h/2;_x000D_ break;_x000D_ case Constants.TOP:_x000D_ ty = y1;_x000D_ break;_x000D_ case Constants.BOTTOM:_x000D_ default:_x000D_ ty = y2-h; _x000D_ }_x000D_ m_box.setFrame(tx,ty,w,h);_x000D_ return m_box;_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.Renderer#render(java.awt.Graphics2D, prefuse.visual.VisualItem)_x000D_ */_x000D_ public void render(Graphics2D g, VisualItem item) { _x000D_ Shape s = getShape(item); _x000D_ GraphicsLib.paint(g, item, m_line, getStroke(item), getRenderType(item)); _x000D_ _x000D_ // check if we have a text label, if so, render it _x000D_ if ( item.canGetString(VisualItem.LABEL) ) { _x000D_ float x = (float)m_box.getMinX(); _x000D_ float y = (float)m_box.getMinY() + m_ascent; _x000D_ _x000D_ // draw label background _x000D_ GraphicsLib.paint(g, item, s, null, RENDER_TYPE_FILL); _x000D_ _x000D_ String str = item.getString(VisualItem.LABEL); _x000D_ AffineTransform origTransform = g.getTransform();_x000D_ AffineTransform transform = this.getTransform(item);_x000D_ if ( transform != null ) g.setTransform(transform);_x000D_ _x000D_ g.setFont(item.getFont()); _x000D_ g.setColor(ColorLib.getColor(item.getTextColor())); _x000D_ g.drawString(str, x, y);_x000D_ _x000D_ if ( transform != null ) g.setTransform(origTransform); _x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.Renderer#locatePoint(java.awt.geom.Point2D, prefuse.visual.VisualItem)_x000D_ */_x000D_ public boolean locatePoint(Point2D p, VisualItem item) {_x000D_ Shape s = getShape(item);_x000D_ if ( s == null ) {_x000D_ return false;_x000D_ } else if ( s == m_box && m_box.contains(p) ) {_x000D_ return true;_x000D_ } else {_x000D_ double width = Math.max(2, item.getSize());_x000D_ double halfWidth = width/2.0;_x000D_ return s.intersects(p.getX()-halfWidth,_x000D_ p.getY()-halfWidth,_x000D_ width,width);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * @see prefuse.render.Renderer#setBounds(prefuse.visual.VisualItem)_x000D_ */_x000D_ public void setBounds(VisualItem item) {_x000D_ if ( !m_manageBounds ) return;_x000D_ Shape shape = getShape(item);_x000D_ if ( shape == null ) {_x000D_ item.setBounds(item.getX(), item.getY(), 0, 0);_x000D_ } else if ( shape == m_line ) {_x000D_ GraphicsLib.setBounds(item, shape, getStroke(item));_x000D_ } else {_x000D_ m_box.add(m_line.getX1(),m_line.getY1());_x000D_ m_box.add(m_line.getX2(),m_line.getY2());_x000D_ item.setBounds(m_box.getMinX(), m_box.getMinY(),_x000D_ m_box.getWidth(), m_box.getHeight());_x000D_ }_x000D_ }_x000D_ _x000D_ } // end of class AxisRenderer_x000D_
False
2,843
12
3,067
13
3,279
13
3,067
13
3,496
14
false
false
false
false
false
true
2,747
194689_6
///////////////////////////////////////_x000D_ /// Projekt: Morphologische Analyse _x000D_ /// Klasse: Main.java _x000D_ /// Paket: meinPaket_x000D_ /// Autor: Eva Hasler _x000D_ /// Datum: 8.4.06 _x000D_ /// Weitere Pakete: BioJava, _x000D_ /// suffixComparator, _x000D_ /// wordCount _x000D_ ///////////////////////////////////////_x000D_ _x000D_ package meinPaket;_x000D_ _x000D_ import javax.swing.JOptionPane;_x000D_ _x000D_ public class Main{_x000D_ _x000D_ public static void main(String[] args) {_x000D_ // Auswahldialog_x000D_ String options[] = { "Suffixe", "Praefixe", "Suffixe und Praefixe", "Suffixe(Ukkonen)" };_x000D_ String baumArt = (String) JOptionPane.showInputDialog( null, "Was soll ermittelt werden?",_x000D_ "Morpholog. Analyse", JOptionPane.QUESTION_MESSAGE, null, options, options[0] );_x000D_ if(baumArt.equals("Suffixe")){_x000D_ GUI_suffixe.meinFenster = new GUI_suffixe("Kompakter Trie (Suffixanalyse)");_x000D_ }_x000D_ else if(baumArt.equals("Praefixe")){_x000D_ GUI_praefixe.meinFenster = new GUI_praefixe("Kompakter Trie (Praefixanalyse)");_x000D_ }_x000D_ else if(baumArt.equals("Suffixe und Praefixe")){_x000D_ GUI_prae_suf.meinFenster = new GUI_prae_suf("Kompakter Trie (Praefix- und Suffixanalyse )");_x000D_ }_x000D_ else if(baumArt.equals("Suffixe(Ukkonen)")){_x000D_ GUI_suffixe_Ukkonen.meinFenster = new GUI_suffixe_Ukkonen("Ukkonen-Suffixbaum (Suffixanalyse)");_x000D_ } _x000D_ }_x000D_ }_x000D_
fsteeg/stnl
de.uni_koeln.spinfo.strings.morpho/src/meinPaket/Main.java
534
/// wordCount _x000D_
line_comment
nl
///////////////////////////////////////_x000D_ /// Projekt: Morphologische Analyse _x000D_ /// Klasse: Main.java _x000D_ /// Paket: meinPaket_x000D_ /// Autor: Eva Hasler _x000D_ /// Datum: 8.4.06 _x000D_ /// Weitere Pakete: BioJava, _x000D_ /// suffixComparator, _x000D_ /// wordCount <SUF> ///////////////////////////////////////_x000D_ _x000D_ package meinPaket;_x000D_ _x000D_ import javax.swing.JOptionPane;_x000D_ _x000D_ public class Main{_x000D_ _x000D_ public static void main(String[] args) {_x000D_ // Auswahldialog_x000D_ String options[] = { "Suffixe", "Praefixe", "Suffixe und Praefixe", "Suffixe(Ukkonen)" };_x000D_ String baumArt = (String) JOptionPane.showInputDialog( null, "Was soll ermittelt werden?",_x000D_ "Morpholog. Analyse", JOptionPane.QUESTION_MESSAGE, null, options, options[0] );_x000D_ if(baumArt.equals("Suffixe")){_x000D_ GUI_suffixe.meinFenster = new GUI_suffixe("Kompakter Trie (Suffixanalyse)");_x000D_ }_x000D_ else if(baumArt.equals("Praefixe")){_x000D_ GUI_praefixe.meinFenster = new GUI_praefixe("Kompakter Trie (Praefixanalyse)");_x000D_ }_x000D_ else if(baumArt.equals("Suffixe und Praefixe")){_x000D_ GUI_prae_suf.meinFenster = new GUI_prae_suf("Kompakter Trie (Praefix- und Suffixanalyse )");_x000D_ }_x000D_ else if(baumArt.equals("Suffixe(Ukkonen)")){_x000D_ GUI_suffixe_Ukkonen.meinFenster = new GUI_suffixe_Ukkonen("Ukkonen-Suffixbaum (Suffixanalyse)");_x000D_ } _x000D_ }_x000D_ }_x000D_
False
617
12
706
14
645
12
706
14
791
17
false
false
false
false
false
true
3,124
101472_0
package afvink3; /** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */ import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ private final int lengte = 250; private Paard[] horses = new Paard[5]; private JButton button; private BufferedImage horse_image; /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */ /* (3) Declareer een button met de naam button van het type JButton */ private RacePanel panel; public Race(){ try { horse_image = ImageIO.read(new File("/home/bastiaan/IdeaProjects/Afvinkopdracht3/src/afvink3/horse.png")); } catch (IOException e) { } String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } } /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.setSize(new Dimension(400, 300)); frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de finish streep */ /* (5) Geef de finish streep een rode kleur */ //g.setColor(Color.RED); //g.fillRect(lengte+10, 0, 3, 200); /* String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } */ //panel.repaint(); for (Paard horse : horses){ horse.setAfstand(0); } /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ /** Loop tot een paard over de finish is*/ boolean keepRunning = true; while (keepRunning) { g.setColor(Color.white); g.fillRect(0, 0, 300, 200); for (Paard horse : horses){ horse.run(); tekenPaard(g, horse); if (horse.getAfstand() >= lengte){ keepRunning = false; } } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); //panel.repaint(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ pauzeer(200); /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ /** for (Paard horse : horses){ tekenPaard(g, horse); } for (Paard horse : horses){ if (horse.getAfstand() >= lengte){ keepRunning = false; } } */ } /** Kijk welk paard gewonnen heeft */ for (Paard horse : horses){ if (horse.getAfstand() >= lengte) { JOptionPane.showMessageDialog(null, horse.getNaam() + " heeft gewonnen!"); } } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new RacePanel(); panel.setPreferredSize(new Dimension(300, 200)); panel.setBackground(Color.white); window.add(panel); /* (9) Zet hier de tekst Run! op de button */ button = new JButton("Run!"); window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { //g.setColor(h.getKleur()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer()-1), 30, 30,null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } private class RacePanel extends JPanel{ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Paard h : horses) { System.out.println(h.getAfstand()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer() - 1), 30, 30, null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); } } }
itbc-bin/1819-owe5a-afvinkopdracht3-BastiaanBrier
src/afvink3/Race.java
2,450
/** * Race class * Class Race maakt gebruik van de class Paard * * @author Martijn van der Bruggen * @version alpha - aanroep van cruciale methodes ontbreekt * (c) 2009 Hogeschool van Arnhem en Nijmegen * * Note: deze code is bewust niet op alle punten generiek * dit om nog onbekende constructies te vermijden. * * Updates * 2010: verduidelijking van opdrachten in de code MvdB * 2011: verbetering leesbaarheid code MvdB * 2012: verbetering layout code en aanpassing commentaar MvdB * 2013: commentaar aangepast aan nieuwe opdracht MvdB * ************************************************* * Afvinkopdracht: werken met methodes en objecten ************************************************* * Opdrachten zitten verwerkt in de code * 1) Declaratie constante * 2) Declaratie van Paard (niet instantiering) * 3) Declareer een button * 4) Zet breedte en hoogte van het frame * 5) Teken een finish streep * 6) Creatie van 4 paarden * 7) Pauzeer * 8) Teken 4 paarden * 9) Plaats tekst op de button * 10) Start de race, methode aanroep * * */
block_comment
nl
package afvink3; /** * Race class <SUF>*/ import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; public class Race extends JFrame implements ActionListener { /** declaratie van variabelen */ private final int lengte = 250; private Paard[] horses = new Paard[5]; private JButton button; private BufferedImage horse_image; /* (1) Declareer hier een constante int met de naam lengte en een waarde van 250 */ /* (2) Declareer hier h1, h2, h3, h4 van het type Paard * Deze paarden instantieer je later in het programma */ /* (3) Declareer een button met de naam button van het type JButton */ private RacePanel panel; public Race(){ try { horse_image = ImageIO.read(new File("/home/bastiaan/IdeaProjects/Afvinkopdracht3/src/afvink3/horse.png")); } catch (IOException e) { } String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } } /** Applicatie - main functie voor runnen applicatie */ public static void main(String[] args) { Race frame = new Race(); /* (4) Geef het frame een breedte van 400 en hoogte van 140 */ frame.setSize(new Dimension(400, 300)); frame.createGUI(); frame.setVisible(true); } /** Loop de race */ private void startRace(Graphics g) { panel.setBackground(Color.white); /** Tekenen van de finish streep */ /* (5) Geef de finish streep een rode kleur */ //g.setColor(Color.RED); //g.fillRect(lengte+10, 0, 3, 200); /* String[] names = { "Winey", "Blaze", "Pinky", "Hopper", "Shadow" }; Color[] hColors = { new Color(95, 2, 31), new Color(236, 71, 28), new Color(250, 28, 183), new Color(50, 200, 29), new Color(0,0,0) }; for (int x = 0; x < horses.length; x++){ horses[x] = new Paard(names[x], hColors[x]); //tekenPaard(g, horses[x]); } */ //panel.repaint(); for (Paard horse : horses){ horse.setAfstand(0); } /**(6) Creatie van 4 paarden * Dit is een instantiering van de 4 paard objecten * Bij de instantiering geef je de paarden een naam en een kleur mee * Kijk in de class Paard hoe je de paarden * kunt initialiseren. */ /** Loop tot een paard over de finish is*/ boolean keepRunning = true; while (keepRunning) { g.setColor(Color.white); g.fillRect(0, 0, 300, 200); for (Paard horse : horses){ horse.run(); tekenPaard(g, horse); if (horse.getAfstand() >= lengte){ keepRunning = false; } } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); //panel.repaint(); /* (7) Voeg hier een aanroep van de methode pauzeer toe zodanig * dat er 1 seconde pauze is. De methode pauzeer is onderdeel * van deze class */ pauzeer(200); /* (8) Voeg hier code in om 4 paarden te tekenen die rennen * Dus een call van de methode tekenPaard */ /** for (Paard horse : horses){ tekenPaard(g, horse); } for (Paard horse : horses){ if (horse.getAfstand() >= lengte){ keepRunning = false; } } */ } /** Kijk welk paard gewonnen heeft */ for (Paard horse : horses){ if (horse.getAfstand() >= lengte) { JOptionPane.showMessageDialog(null, horse.getNaam() + " heeft gewonnen!"); } } } /** Creatie van de GUI*/ private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout()); panel = new RacePanel(); panel.setPreferredSize(new Dimension(300, 200)); panel.setBackground(Color.white); window.add(panel); /* (9) Zet hier de tekst Run! op de button */ button = new JButton("Run!"); window.add(button); button.addActionListener(this); } /** Teken het paard */ private void tekenPaard(Graphics g, Paard h) { //g.setColor(h.getKleur()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer()-1), 30, 30,null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } /** Actie indien de button geklikt is*/ public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); /* (10) Roep hier de methode startrace aan met de juiste parameterisering */ startRace (paper); } /** Pauzeer gedurende x millisecondes*/ public void pauzeer(int msec) { try { Thread.sleep(msec); } catch (InterruptedException e) { System.out.println("Pauze interruptie"); } } private class RacePanel extends JPanel{ @Override protected void paintComponent(Graphics g) { super.paintComponent(g); for (Paard h : horses) { System.out.println(h.getAfstand()); //g.fillRect(h.getAfstand(), 20 * h.getPaardNummer(), 10, 5); g.drawImage(horse_image, h.getAfstand(), 40 * (h.getPaardNummer() - 1), 30, 30, null); //g.fillRect(10, 20 * h.getPaardNummer(), h.getAfstand(), 5); } g.setColor(Color.RED); g.fillRect(lengte+10, 0, 3, 200); } } }
True
2,041
348
2,280
378
2,263
329
2,280
378
2,519
371
true
true
true
true
true
false
781
180575_2
package de.hs_el.streekmann.algodat.aufgabe1; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedList<E> implements List<E> { //Variablen public int currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt public int iteratorCount = 0; //Var die die Anzahl der Iterator List aufrufe Zählt private class Node { E element; Node successor; Node(E element) { this.element = element; this.successor = null; //erstellt nulltes Element (leeres Element) } } Node firstNode; Node lastNode; Node emptyNode; int numberOfElements; public LinkedList() { emptyNode = new Node (null); firstNode = emptyNode; lastNode = emptyNode; numberOfElements = 0; //setzt die Anzahl der Elemente auf 0 } //Methoden für die LinkedList @Override public boolean add(E element) { Node addedNode = new Node(element); lastNode.successor = addedNode; lastNode = addedNode; numberOfElements++; return true; } @Override public E get(int index) { if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt throw new IndexOutOfBoundsException(); } Node nodeAtCurrentIndex = firstNode.successor; //setzt die Var nodeAtCurrentIndex auf das erste Element das nicht das leere Element ist currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt for (int currentIndex = 0; currentIndex < index; currentIndex++) { //geht durch die Liste bis zum gewünschten Index nodeAtCurrentIndex = nodeAtCurrentIndex.successor; //setzt die Var nodeAtCurrentIndex auf das nächste Element currentCount++; //zählt die Anzahl der Schleifendurchläufe (Aufgabe 3.1) } return nodeAtCurrentIndex.element; } //Aufgabe 3 @Override public int getCurrentCount(int index){ //retunt die anzahl der Listenaufrufe return currentCount; } @Override public int getIteratorCount(){ //retunt die anzahl der Listenaufrufe im Iterator return iteratorCount; } @Override public int size() { //gibt die "länge" der Liste (Anzahl der Elemente zurück) return numberOfElements; } @Override public E remove(int index) { //entfernt ein Element an der Stelle index if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt throw new IndexOutOfBoundsException(); } // Allgemeiner Fall: Element in der Mitte oder am Ende entfernen Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist Node currentNode = previousNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist for (int currentIndex = 0; currentIndex < index; currentIndex++){ //geht durch die Liste bis zum gewünschten Index previousNode = currentNode; //setzt die Var previousNode auf das Element das currentNode ist currentNode = currentNode.successor; //setzt die Var currentNode auf den nachfolger der currentNode } if(index == numberOfElements -1) { //wenn der nachfolger des zu entfernenden Elements null ist... lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element } E removedElement = currentNode.element; previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements numberOfElements--; //subtrahiert die Anzahl der Elemente um 1 return removedElement; } //notwendig? private Node getNodeAtIndex(int index) { //gibt das Element an der Stelle index zurück Node nodeAtCurrentIndex = firstNode; for (int currentIndex = 0; currentIndex < index; currentIndex++) { nodeAtCurrentIndex = nodeAtCurrentIndex.successor; } return nodeAtCurrentIndex; } @Override public boolean remove(Object o) { //entfernt ein Element Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist Node currentNode = firstNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist while (currentNode != null) { //solange currentNode nicht null ist... if (o == null ? currentNode.element == null : o.equals(currentNode.element)) { //prüft ob das Element null ist // Spezialfall: Das erste Element(das nicht Empty/Null ist :D) der Liste wird entfernt!!! if (previousNode != null) { //wenn previousNode nicht null ist... previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements if(currentNode == lastNode) { //wenn der nachfolger des zu entfernenden Elements null ist... lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element } numberOfElements--; return true; //Element gefunden und entfernt } } previousNode = currentNode; //setzt previousNode auf das Element der currentNode currentNode = currentNode.successor; //setzt currentNode auf den nachfolger der currentNode } return false; //Das gesuchte Element nicht gefunden und nicht entfernt } @Override public int indexOf(Object o) { int index = 0; Node currentNode = firstNode; while (currentNode != null) { if (o == null ? currentNode.element == null : o.equals(currentNode.element)) { // Das gesuchte Element wurde gefunden return index -1; } currentNode = currentNode.successor; index++; } return -1; } @Override public Iterator<E> iterator() { return new Iterator<E>() { Node nextNode = firstNode; @Override public boolean hasNext() { return nextNode != null && nextNode.successor != null; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } E element = nextNode.successor.element; nextNode = nextNode.successor; iteratorCount = 0; iteratorCount++; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
JJOmin/AlgoDatTesting
src/main/java/de/hs_el/streekmann/algodat/aufgabe1/LinkedList.java
1,785
//erstellt nulltes Element (leeres Element)
line_comment
nl
package de.hs_el.streekmann.algodat.aufgabe1; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedList<E> implements List<E> { //Variablen public int currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt public int iteratorCount = 0; //Var die die Anzahl der Iterator List aufrufe Zählt private class Node { E element; Node successor; Node(E element) { this.element = element; this.successor = null; //erstellt nulltes<SUF> } } Node firstNode; Node lastNode; Node emptyNode; int numberOfElements; public LinkedList() { emptyNode = new Node (null); firstNode = emptyNode; lastNode = emptyNode; numberOfElements = 0; //setzt die Anzahl der Elemente auf 0 } //Methoden für die LinkedList @Override public boolean add(E element) { Node addedNode = new Node(element); lastNode.successor = addedNode; lastNode = addedNode; numberOfElements++; return true; } @Override public E get(int index) { if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt throw new IndexOutOfBoundsException(); } Node nodeAtCurrentIndex = firstNode.successor; //setzt die Var nodeAtCurrentIndex auf das erste Element das nicht das leere Element ist currentCount = 0; //Var die die Anzahl der Listenaufrufe zählt for (int currentIndex = 0; currentIndex < index; currentIndex++) { //geht durch die Liste bis zum gewünschten Index nodeAtCurrentIndex = nodeAtCurrentIndex.successor; //setzt die Var nodeAtCurrentIndex auf das nächste Element currentCount++; //zählt die Anzahl der Schleifendurchläufe (Aufgabe 3.1) } return nodeAtCurrentIndex.element; } //Aufgabe 3 @Override public int getCurrentCount(int index){ //retunt die anzahl der Listenaufrufe return currentCount; } @Override public int getIteratorCount(){ //retunt die anzahl der Listenaufrufe im Iterator return iteratorCount; } @Override public int size() { //gibt die "länge" der Liste (Anzahl der Elemente zurück) return numberOfElements; } @Override public E remove(int index) { //entfernt ein Element an der Stelle index if (index < 0 || index >= numberOfElements) { //prüft ob der Index im Array liegt throw new IndexOutOfBoundsException(); } // Allgemeiner Fall: Element in der Mitte oder am Ende entfernen Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist Node currentNode = previousNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist for (int currentIndex = 0; currentIndex < index; currentIndex++){ //geht durch die Liste bis zum gewünschten Index previousNode = currentNode; //setzt die Var previousNode auf das Element das currentNode ist currentNode = currentNode.successor; //setzt die Var currentNode auf den nachfolger der currentNode } if(index == numberOfElements -1) { //wenn der nachfolger des zu entfernenden Elements null ist... lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element } E removedElement = currentNode.element; previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements numberOfElements--; //subtrahiert die Anzahl der Elemente um 1 return removedElement; } //notwendig? private Node getNodeAtIndex(int index) { //gibt das Element an der Stelle index zurück Node nodeAtCurrentIndex = firstNode; for (int currentIndex = 0; currentIndex < index; currentIndex++) { nodeAtCurrentIndex = nodeAtCurrentIndex.successor; } return nodeAtCurrentIndex; } @Override public boolean remove(Object o) { //entfernt ein Element Node previousNode = firstNode; //setzt die Var previousNode auf das erste Element das nicht das leere Element ist Node currentNode = firstNode.successor; //setzt die Var currentNode auf das zweite Element das nicht das leere Element ist while (currentNode != null) { //solange currentNode nicht null ist... if (o == null ? currentNode.element == null : o.equals(currentNode.element)) { //prüft ob das Element null ist // Spezialfall: Das erste Element(das nicht Empty/Null ist :D) der Liste wird entfernt!!! if (previousNode != null) { //wenn previousNode nicht null ist... previousNode.successor = currentNode.successor; //setzt den nachfolger des vorherigen Elements auf den nachfolger des zu entfernenden Elements if(currentNode == lastNode) { //wenn der nachfolger des zu entfernenden Elements null ist... lastNode = previousNode; //setzt die Var lastNode auf das vorherige Element } numberOfElements--; return true; //Element gefunden und entfernt } } previousNode = currentNode; //setzt previousNode auf das Element der currentNode currentNode = currentNode.successor; //setzt currentNode auf den nachfolger der currentNode } return false; //Das gesuchte Element nicht gefunden und nicht entfernt } @Override public int indexOf(Object o) { int index = 0; Node currentNode = firstNode; while (currentNode != null) { if (o == null ? currentNode.element == null : o.equals(currentNode.element)) { // Das gesuchte Element wurde gefunden return index -1; } currentNode = currentNode.successor; index++; } return -1; } @Override public Iterator<E> iterator() { return new Iterator<E>() { Node nextNode = firstNode; @Override public boolean hasNext() { return nextNode != null && nextNode.successor != null; } @Override public E next() { if (!hasNext()) { throw new NoSuchElementException(); } E element = nextNode.successor.element; nextNode = nextNode.successor; iteratorCount = 0; iteratorCount++; return element; } @Override public void remove() { throw new UnsupportedOperationException(); } }; } }
False
1,510
12
1,692
11
1,565
11
1,692
11
1,955
12
false
false
false
false
false
true
3,846
15321_0
package nl.novi.stuivenberg.springboot.example.security.service; import nl.novi.stuivenberg.springboot.example.security.domain.ERole; import nl.novi.stuivenberg.springboot.example.security.domain.Role; import nl.novi.stuivenberg.springboot.example.security.domain.User; import nl.novi.stuivenberg.springboot.example.security.payload.request.LoginRequest; import nl.novi.stuivenberg.springboot.example.security.payload.request.SignupRequest; import nl.novi.stuivenberg.springboot.example.security.payload.response.JwtResponse; import nl.novi.stuivenberg.springboot.example.security.payload.response.MessageResponse; import nl.novi.stuivenberg.springboot.example.security.repository.RoleRepository; import nl.novi.stuivenberg.springboot.example.security.repository.UserRepository; import nl.novi.stuivenberg.springboot.example.security.service.security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Username is already taken!")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Email is already in use!")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } user.setRoles(roles); userRepository.save(user); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet die allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link nl.novi.stuivenberg.springboot.example.security.service.security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */ public ResponseEntity<JwtResponse> authenticateUser(LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
novaeeken/sd-novi-authentication-backend
src/main/java/nl/novi/stuivenberg/springboot/example/security/service/AuthorizationService.java
1,789
/** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */
block_comment
nl
package nl.novi.stuivenberg.springboot.example.security.service; import nl.novi.stuivenberg.springboot.example.security.domain.ERole; import nl.novi.stuivenberg.springboot.example.security.domain.Role; import nl.novi.stuivenberg.springboot.example.security.domain.User; import nl.novi.stuivenberg.springboot.example.security.payload.request.LoginRequest; import nl.novi.stuivenberg.springboot.example.security.payload.request.SignupRequest; import nl.novi.stuivenberg.springboot.example.security.payload.response.JwtResponse; import nl.novi.stuivenberg.springboot.example.security.payload.response.MessageResponse; import nl.novi.stuivenberg.springboot.example.security.repository.RoleRepository; import nl.novi.stuivenberg.springboot.example.security.repository.UserRepository; import nl.novi.stuivenberg.springboot.example.security.service.security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt<SUF>*/ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Username is already taken!")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("Error: Email is already in use!")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } user.setRoles(roles); userRepository.save(user); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet die allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link nl.novi.stuivenberg.springboot.example.security.service.security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */ public ResponseEntity<JwtResponse> authenticateUser(LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
True
1,197
93
1,483
103
1,504
92
1,483
103
1,770
107
false
false
false
false
false
true
1,751
101007_2
package io.github.stealingdapenta.idletd.command; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayer; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayerService; import io.github.stealingdapenta.idletd.plot.Plot; import io.github.stealingdapenta.idletd.plot.PlotService; import io.github.stealingdapenta.idletd.towerdefense.TowerDefense; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseManager; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseService; import lombok.RequiredArgsConstructor; import net.kyori.adventure.text.Component; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Objects; import static io.github.stealingdapenta.idletd.Idletd.logger; @RequiredArgsConstructor public class TowerDefenseCommand implements CommandExecutor { private static final String NO_PLOT = "Please create a plot before launching a TD game!"; private static final String NO_IDLE_PLAYER = "Internal error. Please contact a system admin."; private final PlotService plotService; private final TowerDefenseService towerDefenseService; private final IdlePlayerService idlePlayerService; private final TowerDefenseManager towerDefenseManager; @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { Player player = (Player) commandSender; IdlePlayer idlePlayer = idlePlayerService.getIdlePlayer(player); if (Objects.isNull(idlePlayer)) { logger.severe(player.getName() + " doesn't have a linked IdlePlayer."); player.sendMessage(Component.text(NO_IDLE_PLAYER)); return true; } TowerDefense towerDefense = towerDefenseManager.getActiveTDGame(idlePlayer); if (Objects.nonNull(towerDefense)) { player.sendMessage("You already have an active game."); return true; } towerDefense = towerDefenseService.findTowerDefense(idlePlayer); if (Objects.isNull(towerDefense)) { Plot plot = plotService.findPlot(player); if (Objects.isNull(plot)) { logger.info(player.getName() + " tried to start a TD game without even owning a plot yet."); player.sendMessage(Component.text(NO_PLOT)); return true; } towerDefense = TowerDefense.builder() .plot(plot.getId()) .playerUUID(idlePlayer.getPlayerUUID()) .stageLevel(1) .build(); towerDefenseService.saveTowerDefense(towerDefense); } towerDefenseManager.activateTDGame(towerDefense); // todo calculate AFK income (idle) // todo add economy, reward per kill, bank value // todo voor afk gold income, misschien "highest income op een round" + "duur round" saven en dan percentage daarvan per minuut uitbetalen met zelfde verhouding return true; } }
TomDesch/idletd
src/main/java/io/github/stealingdapenta/idletd/command/TowerDefenseCommand.java
899
// todo voor afk gold income, misschien "highest income op een round" + "duur round" saven en dan percentage daarvan per minuut uitbetalen met zelfde verhouding
line_comment
nl
package io.github.stealingdapenta.idletd.command; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayer; import io.github.stealingdapenta.idletd.idleplayer.IdlePlayerService; import io.github.stealingdapenta.idletd.plot.Plot; import io.github.stealingdapenta.idletd.plot.PlotService; import io.github.stealingdapenta.idletd.towerdefense.TowerDefense; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseManager; import io.github.stealingdapenta.idletd.towerdefense.TowerDefenseService; import lombok.RequiredArgsConstructor; import net.kyori.adventure.text.Component; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import java.util.Objects; import static io.github.stealingdapenta.idletd.Idletd.logger; @RequiredArgsConstructor public class TowerDefenseCommand implements CommandExecutor { private static final String NO_PLOT = "Please create a plot before launching a TD game!"; private static final String NO_IDLE_PLAYER = "Internal error. Please contact a system admin."; private final PlotService plotService; private final TowerDefenseService towerDefenseService; private final IdlePlayerService idlePlayerService; private final TowerDefenseManager towerDefenseManager; @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { Player player = (Player) commandSender; IdlePlayer idlePlayer = idlePlayerService.getIdlePlayer(player); if (Objects.isNull(idlePlayer)) { logger.severe(player.getName() + " doesn't have a linked IdlePlayer."); player.sendMessage(Component.text(NO_IDLE_PLAYER)); return true; } TowerDefense towerDefense = towerDefenseManager.getActiveTDGame(idlePlayer); if (Objects.nonNull(towerDefense)) { player.sendMessage("You already have an active game."); return true; } towerDefense = towerDefenseService.findTowerDefense(idlePlayer); if (Objects.isNull(towerDefense)) { Plot plot = plotService.findPlot(player); if (Objects.isNull(plot)) { logger.info(player.getName() + " tried to start a TD game without even owning a plot yet."); player.sendMessage(Component.text(NO_PLOT)); return true; } towerDefense = TowerDefense.builder() .plot(plot.getId()) .playerUUID(idlePlayer.getPlayerUUID()) .stageLevel(1) .build(); towerDefenseService.saveTowerDefense(towerDefense); } towerDefenseManager.activateTDGame(towerDefense); // todo calculate AFK income (idle) // todo add economy, reward per kill, bank value // todo voor<SUF> return true; } }
True
640
46
771
47
768
37
771
47
899
46
false
false
false
false
false
true
541
83128_1
package components;_x000D_ /**_x000D_ * SSD class. Contains all the information that a Solid State Drive has._x000D_ * All the fields match the fields in the Neo4j Database._x000D_ * Extends {@link components.Hardware}_x000D_ *_x000D_ * @author Frenesius_x000D_ * @since 1-1-2015_x000D_ * @version 0.1_x000D_ */_x000D_ public class SSD extends Hardware{_x000D_ private String beoordeling;_x000D_ private String hoogte;_x000D_ private String verkoopstatus;_x000D_ private String fabrieksgarantie;_x000D_ private String product;_x000D_ private String serie;_x000D_ private String hardeschijfbusintern; // origineel Hardeschijf bus (intern)_x000D_ private String behuizingbayintern;_x000D_ private String ssdeigenschappen;_x000D_ private String opslagcapaciteit;_x000D_ private String lezensequentieel; // origineel Lezen (sequentieel)_x000D_ private String prijspergb;_x000D_ private String ssdtype; // origineel SSD-type_x000D_ private String ssdcontroller; // origineel SSD-controller_x000D_ private String schrijvensequentieel; // origineel Schrijven (sequentieel)_x000D_ private String stroomverbruiklezen; // origineel Stroomverbruik (lezen)_x000D_ private String lezenrandom4k; // origineel Lezen (random 4K)_x000D_ private String schrijvenrandom4k; // origineel Schrijven (random 4K)_x000D_ private String drivecache;_x000D_ private String stroomverbruikschrijven; // origineel Stroomverbruik (schrijven)_x000D_ private String meantimebetweenfailures;_x000D_ private String hddssdaansluiting; // HDD/SSD-aansluiting_x000D_ _x000D_ public String getBeoordeling() {_x000D_ return beoordeling;_x000D_ }_x000D_ public void setBeoordeling(String beoordeling) {_x000D_ this.beoordeling = beoordeling;_x000D_ }_x000D_ public String getHoogte() {_x000D_ return hoogte;_x000D_ }_x000D_ public void setHoogte(String hoogte) {_x000D_ this.hoogte = hoogte;_x000D_ }_x000D_ public String getVerkoopstatus() {_x000D_ return verkoopstatus;_x000D_ }_x000D_ public void setVerkoopstatus(String verkoopstatus) {_x000D_ this.verkoopstatus = verkoopstatus;_x000D_ }_x000D_ public String getFabrieksgarantie() {_x000D_ return fabrieksgarantie;_x000D_ }_x000D_ public void setFabrieksgarantie(String fabrieksgarantie) {_x000D_ this.fabrieksgarantie = fabrieksgarantie;_x000D_ }_x000D_ public String getProduct() {_x000D_ return product;_x000D_ }_x000D_ public void setProduct(String product) {_x000D_ this.product = product;_x000D_ }_x000D_ public String getSerie() {_x000D_ return serie;_x000D_ }_x000D_ public void setSerie(String serie) {_x000D_ this.serie = serie;_x000D_ }_x000D_ public String getHardeschijfbusintern() {_x000D_ return hardeschijfbusintern;_x000D_ }_x000D_ public void setHardeschijfbusintern(String hardeschijfbusintern) {_x000D_ this.hardeschijfbusintern = hardeschijfbusintern;_x000D_ }_x000D_ public String getBehuizingbayintern() {_x000D_ return behuizingbayintern;_x000D_ }_x000D_ public void setBehuizingbayintern(String behuizingbayintern) {_x000D_ this.behuizingbayintern = behuizingbayintern;_x000D_ }_x000D_ public String getSsdeigenschappen() {_x000D_ return ssdeigenschappen;_x000D_ }_x000D_ public void setSsdeigenschappen(String ssdeigenschappen) {_x000D_ this.ssdeigenschappen = ssdeigenschappen;_x000D_ }_x000D_ public String getOpslagcapaciteit() {_x000D_ return opslagcapaciteit;_x000D_ }_x000D_ public void setOpslagcapaciteit(String opslagcapaciteit) {_x000D_ this.opslagcapaciteit = opslagcapaciteit;_x000D_ }_x000D_ public String getLezensequentieel() {_x000D_ return lezensequentieel;_x000D_ }_x000D_ public void setLezensequentieel(String lezensequentieel) {_x000D_ this.lezensequentieel = lezensequentieel;_x000D_ }_x000D_ public String getPrijspergb() {_x000D_ return prijspergb;_x000D_ }_x000D_ public void setPrijspergb(String prijspergb) {_x000D_ this.prijspergb = prijspergb;_x000D_ }_x000D_ public String getSsdtype() {_x000D_ return ssdtype;_x000D_ }_x000D_ public void setSsdtype(String ssdtype) {_x000D_ this.ssdtype = ssdtype;_x000D_ }_x000D_ public String getSsdcontroller() {_x000D_ return ssdcontroller;_x000D_ }_x000D_ public void setSsdcontroller(String ssdcontroller) {_x000D_ this.ssdcontroller = ssdcontroller;_x000D_ }_x000D_ public String getSchrijvensequentieel() {_x000D_ return schrijvensequentieel;_x000D_ }_x000D_ public void setSchrijvensequentieel(String schrijvensequentieel) {_x000D_ this.schrijvensequentieel = schrijvensequentieel;_x000D_ }_x000D_ public String getStroomverbruiklezen() {_x000D_ return stroomverbruiklezen;_x000D_ }_x000D_ public void setStroomverbruiklezen(String stroomverbruiklezen) {_x000D_ this.stroomverbruiklezen = stroomverbruiklezen;_x000D_ }_x000D_ public String getLezenrandom4k() {_x000D_ return lezenrandom4k;_x000D_ }_x000D_ public void setLezenrandom4k(String lezenrandom4k) {_x000D_ this.lezenrandom4k = lezenrandom4k;_x000D_ }_x000D_ public String getSchrijvenrandom4k() {_x000D_ return schrijvenrandom4k;_x000D_ }_x000D_ public void setSchrijvenrandom4k(String schrijvenrandom4k) {_x000D_ this.schrijvenrandom4k = schrijvenrandom4k;_x000D_ }_x000D_ public String getDrivecache() {_x000D_ return drivecache;_x000D_ }_x000D_ public void setDrivecache(String drivecache) {_x000D_ this.drivecache = drivecache;_x000D_ }_x000D_ public String getStroomverbruikschrijven() {_x000D_ return stroomverbruikschrijven;_x000D_ }_x000D_ public void setStroomverbruikschrijven(String stroomverbruikschrijven) {_x000D_ this.stroomverbruikschrijven = stroomverbruikschrijven;_x000D_ }_x000D_ public String getMeantimebetweenfailures() {_x000D_ return meantimebetweenfailures;_x000D_ }_x000D_ public void setMeantimebetweenfailures(String meantimebetweenfailures) {_x000D_ this.meantimebetweenfailures = meantimebetweenfailures;_x000D_ }_x000D_ public String getHddssdaansluiting() {_x000D_ return hddssdaansluiting;_x000D_ }_x000D_ public void setHddssdaansluiting(String hddssdaansluiting) {_x000D_ this.hddssdaansluiting = hddssdaansluiting;_x000D_ }_x000D_ }
Frenesius/PC-Builder-Matcher
src/components/SSD.java
1,785
// origineel Hardeschijf bus (intern)_x000D_
line_comment
nl
package components;_x000D_ /**_x000D_ * SSD class. Contains all the information that a Solid State Drive has._x000D_ * All the fields match the fields in the Neo4j Database._x000D_ * Extends {@link components.Hardware}_x000D_ *_x000D_ * @author Frenesius_x000D_ * @since 1-1-2015_x000D_ * @version 0.1_x000D_ */_x000D_ public class SSD extends Hardware{_x000D_ private String beoordeling;_x000D_ private String hoogte;_x000D_ private String verkoopstatus;_x000D_ private String fabrieksgarantie;_x000D_ private String product;_x000D_ private String serie;_x000D_ private String hardeschijfbusintern; // origineel Hardeschijf<SUF> private String behuizingbayintern;_x000D_ private String ssdeigenschappen;_x000D_ private String opslagcapaciteit;_x000D_ private String lezensequentieel; // origineel Lezen (sequentieel)_x000D_ private String prijspergb;_x000D_ private String ssdtype; // origineel SSD-type_x000D_ private String ssdcontroller; // origineel SSD-controller_x000D_ private String schrijvensequentieel; // origineel Schrijven (sequentieel)_x000D_ private String stroomverbruiklezen; // origineel Stroomverbruik (lezen)_x000D_ private String lezenrandom4k; // origineel Lezen (random 4K)_x000D_ private String schrijvenrandom4k; // origineel Schrijven (random 4K)_x000D_ private String drivecache;_x000D_ private String stroomverbruikschrijven; // origineel Stroomverbruik (schrijven)_x000D_ private String meantimebetweenfailures;_x000D_ private String hddssdaansluiting; // HDD/SSD-aansluiting_x000D_ _x000D_ public String getBeoordeling() {_x000D_ return beoordeling;_x000D_ }_x000D_ public void setBeoordeling(String beoordeling) {_x000D_ this.beoordeling = beoordeling;_x000D_ }_x000D_ public String getHoogte() {_x000D_ return hoogte;_x000D_ }_x000D_ public void setHoogte(String hoogte) {_x000D_ this.hoogte = hoogte;_x000D_ }_x000D_ public String getVerkoopstatus() {_x000D_ return verkoopstatus;_x000D_ }_x000D_ public void setVerkoopstatus(String verkoopstatus) {_x000D_ this.verkoopstatus = verkoopstatus;_x000D_ }_x000D_ public String getFabrieksgarantie() {_x000D_ return fabrieksgarantie;_x000D_ }_x000D_ public void setFabrieksgarantie(String fabrieksgarantie) {_x000D_ this.fabrieksgarantie = fabrieksgarantie;_x000D_ }_x000D_ public String getProduct() {_x000D_ return product;_x000D_ }_x000D_ public void setProduct(String product) {_x000D_ this.product = product;_x000D_ }_x000D_ public String getSerie() {_x000D_ return serie;_x000D_ }_x000D_ public void setSerie(String serie) {_x000D_ this.serie = serie;_x000D_ }_x000D_ public String getHardeschijfbusintern() {_x000D_ return hardeschijfbusintern;_x000D_ }_x000D_ public void setHardeschijfbusintern(String hardeschijfbusintern) {_x000D_ this.hardeschijfbusintern = hardeschijfbusintern;_x000D_ }_x000D_ public String getBehuizingbayintern() {_x000D_ return behuizingbayintern;_x000D_ }_x000D_ public void setBehuizingbayintern(String behuizingbayintern) {_x000D_ this.behuizingbayintern = behuizingbayintern;_x000D_ }_x000D_ public String getSsdeigenschappen() {_x000D_ return ssdeigenschappen;_x000D_ }_x000D_ public void setSsdeigenschappen(String ssdeigenschappen) {_x000D_ this.ssdeigenschappen = ssdeigenschappen;_x000D_ }_x000D_ public String getOpslagcapaciteit() {_x000D_ return opslagcapaciteit;_x000D_ }_x000D_ public void setOpslagcapaciteit(String opslagcapaciteit) {_x000D_ this.opslagcapaciteit = opslagcapaciteit;_x000D_ }_x000D_ public String getLezensequentieel() {_x000D_ return lezensequentieel;_x000D_ }_x000D_ public void setLezensequentieel(String lezensequentieel) {_x000D_ this.lezensequentieel = lezensequentieel;_x000D_ }_x000D_ public String getPrijspergb() {_x000D_ return prijspergb;_x000D_ }_x000D_ public void setPrijspergb(String prijspergb) {_x000D_ this.prijspergb = prijspergb;_x000D_ }_x000D_ public String getSsdtype() {_x000D_ return ssdtype;_x000D_ }_x000D_ public void setSsdtype(String ssdtype) {_x000D_ this.ssdtype = ssdtype;_x000D_ }_x000D_ public String getSsdcontroller() {_x000D_ return ssdcontroller;_x000D_ }_x000D_ public void setSsdcontroller(String ssdcontroller) {_x000D_ this.ssdcontroller = ssdcontroller;_x000D_ }_x000D_ public String getSchrijvensequentieel() {_x000D_ return schrijvensequentieel;_x000D_ }_x000D_ public void setSchrijvensequentieel(String schrijvensequentieel) {_x000D_ this.schrijvensequentieel = schrijvensequentieel;_x000D_ }_x000D_ public String getStroomverbruiklezen() {_x000D_ return stroomverbruiklezen;_x000D_ }_x000D_ public void setStroomverbruiklezen(String stroomverbruiklezen) {_x000D_ this.stroomverbruiklezen = stroomverbruiklezen;_x000D_ }_x000D_ public String getLezenrandom4k() {_x000D_ return lezenrandom4k;_x000D_ }_x000D_ public void setLezenrandom4k(String lezenrandom4k) {_x000D_ this.lezenrandom4k = lezenrandom4k;_x000D_ }_x000D_ public String getSchrijvenrandom4k() {_x000D_ return schrijvenrandom4k;_x000D_ }_x000D_ public void setSchrijvenrandom4k(String schrijvenrandom4k) {_x000D_ this.schrijvenrandom4k = schrijvenrandom4k;_x000D_ }_x000D_ public String getDrivecache() {_x000D_ return drivecache;_x000D_ }_x000D_ public void setDrivecache(String drivecache) {_x000D_ this.drivecache = drivecache;_x000D_ }_x000D_ public String getStroomverbruikschrijven() {_x000D_ return stroomverbruikschrijven;_x000D_ }_x000D_ public void setStroomverbruikschrijven(String stroomverbruikschrijven) {_x000D_ this.stroomverbruikschrijven = stroomverbruikschrijven;_x000D_ }_x000D_ public String getMeantimebetweenfailures() {_x000D_ return meantimebetweenfailures;_x000D_ }_x000D_ public void setMeantimebetweenfailures(String meantimebetweenfailures) {_x000D_ this.meantimebetweenfailures = meantimebetweenfailures;_x000D_ }_x000D_ public String getHddssdaansluiting() {_x000D_ return hddssdaansluiting;_x000D_ }_x000D_ public void setHddssdaansluiting(String hddssdaansluiting) {_x000D_ this.hddssdaansluiting = hddssdaansluiting;_x000D_ }_x000D_ }
True
2,535
18
2,770
19
2,633
17
2,770
19
2,969
18
false
false
false
false
false
true
711
8497_0
package Spel; import Tools.*; import javax.swing.JFrame; import java.util.ArrayList; /** * Deze klasse zorgt voor de dynamica van het spel. * * @author (E.E. Koldenhof) * @version (V.1.0) * * Deze klasse mag je NIET veranderen * */ public class Beweeg{ private ArrayList<KanBewegen> beweegLijst; /** * Vult de 4 basis objecten die de controller nodig heeft om de * dynamica van het spel te kunnen afhandelen */ public Beweeg(){ beweegLijst = new ArrayList<KanBewegen>(); } public void voegObjectToe(KanBewegen o){ beweegLijst.add(o); } public void verwijderObject(KanBewegen o){ beweegLijst.remove(o); } public void voegLijstToe(ArrayList lijst){ beweegLijst.addAll(lijst); } public void verwijderLijst(ArrayList lijst){ beweegLijst.removeAll(lijst); } public void beweegAlles(float stapGrootte){ int teller = 0; while (teller < beweegLijst.size()){ beweegLijst.get(teller).beweeg(stapGrootte); teller ++; } } }
Hutsmeister/Spel
Spelluhtjuh/Spel/Beweeg.java
413
/** * Deze klasse zorgt voor de dynamica van het spel. * * @author (E.E. Koldenhof) * @version (V.1.0) * * Deze klasse mag je NIET veranderen * */
block_comment
nl
package Spel; import Tools.*; import javax.swing.JFrame; import java.util.ArrayList; /** * Deze klasse zorgt<SUF>*/ public class Beweeg{ private ArrayList<KanBewegen> beweegLijst; /** * Vult de 4 basis objecten die de controller nodig heeft om de * dynamica van het spel te kunnen afhandelen */ public Beweeg(){ beweegLijst = new ArrayList<KanBewegen>(); } public void voegObjectToe(KanBewegen o){ beweegLijst.add(o); } public void verwijderObject(KanBewegen o){ beweegLijst.remove(o); } public void voegLijstToe(ArrayList lijst){ beweegLijst.addAll(lijst); } public void verwijderLijst(ArrayList lijst){ beweegLijst.removeAll(lijst); } public void beweegAlles(float stapGrootte){ int teller = 0; while (teller < beweegLijst.size()){ beweegLijst.get(teller).beweeg(stapGrootte); teller ++; } } }
True
330
55
369
65
354
57
369
65
401
65
false
false
false
false
false
true
3,025
83232_0
package be.pxl.h5.oefening1;_x000D_ _x000D_ public class HuwelijkApp {_x000D_ public static void main(String[] args) {_x000D_ // Gemeente gemeente = new Gemeente(35004, "has47278selt");_x000D_ Adres adres = new Adres("Grote bameriklaan", "28", 35400, "hasselt");_x000D_ System.out.println(adres);_x000D_ Datum datum = new Datum();_x000D_ }_x000D_ }
hursittarcan/pxl
YEAR 1/Java Essentials/H5/src/be/pxl/h5/oefening1/HuwelijkApp.java
119
// Gemeente gemeente = new Gemeente(35004, "has47278selt");_x000D_
line_comment
nl
package be.pxl.h5.oefening1;_x000D_ _x000D_ public class HuwelijkApp {_x000D_ public static void main(String[] args) {_x000D_ // Gemeente gemeente<SUF> Adres adres = new Adres("Grote bameriklaan", "28", 35400, "hasselt");_x000D_ System.out.println(adres);_x000D_ Datum datum = new Datum();_x000D_ }_x000D_ }
False
165
33
179
36
174
31
179
36
187
32
false
false
false
false
false
true
1,729
79106_0
package Chess.Core.Pieces; import Chess.Core.*; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableBlackPawnMoves; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableWhitePawnMoves; import Chess.Core.Usecases.LocateKing.LocateKing; import java.util.HashSet; // TODO // - De witte pawn geeft een verkeerde available move: // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | * * | | | | | // | | | | | | | | | 6 // | | | | * * | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | | | | | | // | | | | | (P) | P | | | 5 (En passant row) // | | | | | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ public class Pawn extends Piece { private final PromotionHandler promotionHandler; public Pawn(Color color, Board board) { super(color, board); this.promotionHandler = (pawn, location) -> {}; } public Pawn(Color color, Board board, PromotionHandler promotionHandler) { super(color, board); this.promotionHandler = promotionHandler; } /** * Checks if the pawn reached the end of the board and if so calls the promotion-handler to handle the promotion of the pawn. * * @param state The current state of the game. * @param location The current location of the chess piece. * @param destination The destination of the chess piece. * @throws MoveNotPossible When the piece cannot be moved the the specified destination. */ @Override public void move(State state, Coords location, Coords destination) throws MoveNotPossible, Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { if (isEnPassantMove(location, destination)) { executeEnPassantMove(location, destination); setMoves(getMoves() + 1); } else super.move(state, location, destination); if (destination.y() >= 8 || destination.y() <= 1) promotionHandler.handlePromotion(this, destination); } @Override public HashSet<Coords> availableMoves(State state, Coords location) throws Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { var listMoves = switch (getColor()) { case white -> new ListAvailableWhitePawnMoves(); case black -> new ListAvailableBlackPawnMoves(); }; var moves = listMoves.list(getBoard(), location); removeMovesThatCausesChecks(state, location, moves); return moves; } private boolean isEnPassantMove(Coords location, Coords destination) { return !getBoard().pieceOnField(destination) && location.x() != destination.x(); } private void executeEnPassantMove(Coords location, Coords destination) throws Field.NoPieceAvailable, Board.FieldNotFound { var board = getBoard(); switch (getColor()) { case black -> board.removePiece(new Coords(destination.x(), destination.y() + 1)); case white -> board.removePiece(new Coords(destination.x(), destination.y() - 1)); } board.setPiece(destination, this); board.removePiece(location); } }
ThomasLuchies/projecten
OOP projecten/schaken/src/Chess/Core/Pieces/Pawn.java
1,041
// - De witte pawn geeft een verkeerde available move:
line_comment
nl
package Chess.Core.Pieces; import Chess.Core.*; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableBlackPawnMoves; import Chess.Core.Usecases.ListAvailableMoves.ListAvailableWhitePawnMoves; import Chess.Core.Usecases.LocateKing.LocateKing; import java.util.HashSet; // TODO // - De<SUF> // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | * * | | | | | // | | | | | | | | | 6 // | | | | * * | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ // | | | | | | | | | // | | | | | (P) | P | | | 5 (En passant row) // | | | | | | | | | // +-------+-------+-------+-------+-------+-------+-------+-------+ public class Pawn extends Piece { private final PromotionHandler promotionHandler; public Pawn(Color color, Board board) { super(color, board); this.promotionHandler = (pawn, location) -> {}; } public Pawn(Color color, Board board, PromotionHandler promotionHandler) { super(color, board); this.promotionHandler = promotionHandler; } /** * Checks if the pawn reached the end of the board and if so calls the promotion-handler to handle the promotion of the pawn. * * @param state The current state of the game. * @param location The current location of the chess piece. * @param destination The destination of the chess piece. * @throws MoveNotPossible When the piece cannot be moved the the specified destination. */ @Override public void move(State state, Coords location, Coords destination) throws MoveNotPossible, Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { if (isEnPassantMove(location, destination)) { executeEnPassantMove(location, destination); setMoves(getMoves() + 1); } else super.move(state, location, destination); if (destination.y() >= 8 || destination.y() <= 1) promotionHandler.handlePromotion(this, destination); } @Override public HashSet<Coords> availableMoves(State state, Coords location) throws Field.NoPieceAvailable, Board.FieldNotFound, LocateKing.KingNotFound { var listMoves = switch (getColor()) { case white -> new ListAvailableWhitePawnMoves(); case black -> new ListAvailableBlackPawnMoves(); }; var moves = listMoves.list(getBoard(), location); removeMovesThatCausesChecks(state, location, moves); return moves; } private boolean isEnPassantMove(Coords location, Coords destination) { return !getBoard().pieceOnField(destination) && location.x() != destination.x(); } private void executeEnPassantMove(Coords location, Coords destination) throws Field.NoPieceAvailable, Board.FieldNotFound { var board = getBoard(); switch (getColor()) { case black -> board.removePiece(new Coords(destination.x(), destination.y() + 1)); case white -> board.removePiece(new Coords(destination.x(), destination.y() - 1)); } board.setPiece(destination, this); board.removePiece(location); } }
True
800
16
860
18
915
13
860
18
1,022
17
false
false
false
false
false
true
630
3031_1
package controller;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.json.Json;_x000D_ import javax.json.JsonArrayBuilder;_x000D_ import javax.json.JsonObject;_x000D_ _x000D_ import model.Docent;_x000D_ import model.PrIS;_x000D_ import model.Vak;_x000D_ import server.Conversation;_x000D_ import server.Handler;_x000D_ _x000D_ public class DocentController implements Handler {_x000D_ private PrIS informatieSysteem;_x000D_ _x000D_ /**_x000D_ * De DocentController klasse moet alle docent-gerelateerde aanvragen_x000D_ * afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat_x000D_ * dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI_x000D_ * een nieuwe methode schrijven._x000D_ * _x000D_ * @param infoSys - het toegangspunt tot het domeinmodel_x000D_ */_x000D_ public DocentController(PrIS infoSys) {_x000D_ informatieSysteem = infoSys;_x000D_ }_x000D_ _x000D_ public void handle(Conversation conversation) {_x000D_ if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {_x000D_ mijnVakken(conversation);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden_x000D_ * de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden_x000D_ * dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!_x000D_ * _x000D_ * @param conversation - alle informatie over het request_x000D_ */_x000D_ private void mijnVakken(Conversation conversation) {_x000D_ JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();_x000D_ String gebruikersnaam = jsonObjectIn.getString("username");_x000D_ _x000D_ Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!_x000D_ ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!_x000D_ _x000D_ JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met..._x000D_ _x000D_ for (Vak v : vakken) {_x000D_ jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object..._x000D_ .add("vakcode", v.getVakCode())_x000D_ .add("vaknaam", v.getVakNaam()));_x000D_ }_x000D_ _x000D_ conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!_x000D_ }_x000D_ }_x000D_
Gundraub/PrIS
src/controller/DocentController.java
697
/**_x000D_ * Deze methode haalt eerst de opgestuurde JSON-data op. Daarna worden_x000D_ * de benodigde gegevens uit het domeinmodel gehaald. Deze gegevens worden_x000D_ * dan weer omgezet naar JSON en teruggestuurd naar de Polymer-GUI!_x000D_ * _x000D_ * @param conversation - alle informatie over het request_x000D_ */
block_comment
nl
package controller;_x000D_ _x000D_ import java.util.ArrayList;_x000D_ _x000D_ import javax.json.Json;_x000D_ import javax.json.JsonArrayBuilder;_x000D_ import javax.json.JsonObject;_x000D_ _x000D_ import model.Docent;_x000D_ import model.PrIS;_x000D_ import model.Vak;_x000D_ import server.Conversation;_x000D_ import server.Handler;_x000D_ _x000D_ public class DocentController implements Handler {_x000D_ private PrIS informatieSysteem;_x000D_ _x000D_ /**_x000D_ * De DocentController klasse moet alle docent-gerelateerde aanvragen_x000D_ * afhandelen. Methode handle() kijkt welke URI is opgevraagd en laat_x000D_ * dan de juiste methode het werk doen. Je kunt voor elke nieuwe URI_x000D_ * een nieuwe methode schrijven._x000D_ * _x000D_ * @param infoSys - het toegangspunt tot het domeinmodel_x000D_ */_x000D_ public DocentController(PrIS infoSys) {_x000D_ informatieSysteem = infoSys;_x000D_ }_x000D_ _x000D_ public void handle(Conversation conversation) {_x000D_ if (conversation.getRequestedURI().startsWith("/docent/mijnvakken")) {_x000D_ mijnVakken(conversation);_x000D_ }_x000D_ }_x000D_ _x000D_ /**_x000D_ * Deze methode haalt<SUF>*/_x000D_ private void mijnVakken(Conversation conversation) {_x000D_ JsonObject jsonObjectIn = (JsonObject) conversation.getRequestBodyAsJSON();_x000D_ String gebruikersnaam = jsonObjectIn.getString("username");_x000D_ _x000D_ Docent docent = informatieSysteem.getDocent(gebruikersnaam); // Docent-object ophalen!_x000D_ ArrayList<Vak> vakken = docent.getVakken(); // Vakken van de docent ophalen!_x000D_ _x000D_ JsonArrayBuilder jab = Json.createArrayBuilder(); // En uiteindelijk gaat er een JSON-array met..._x000D_ _x000D_ for (Vak v : vakken) {_x000D_ jab.add(Json.createObjectBuilder() // daarin voor elk vak een JSON-object..._x000D_ .add("vakcode", v.getVakCode())_x000D_ .add("vaknaam", v.getVakNaam()));_x000D_ }_x000D_ _x000D_ conversation.sendJSONMessage(jab.build().toString()); // terug naar de Polymer-GUI!_x000D_ }_x000D_ }_x000D_
True
924
120
1,029
128
960
119
1,029
128
1,128
135
false
false
false
false
false
true
254
29534_4
package activemq;_x000D_ _x000D_ import algoritmes.ConcurrentMergeSort;_x000D_ import helper.CustomUtilities;_x000D_ import org.apache.activemq.ActiveMQConnectionFactory;_x000D_ _x000D_ import javax.jms.*;_x000D_ import java.util.ArrayList;_x000D_ import java.util.List;_x000D_ _x000D_ import static helper.Config.ACTIVEMQ_URL;_x000D_ _x000D_ /**_x000D_ * Parallel Computing_x000D_ * AUTHOR: R. Lobato & C. Verra_x000D_ */_x000D_ public class Consumer {_x000D_ private static String subject = "resultaat";_x000D_ _x000D_ public static void main(String[] args) throws JMSException {_x000D_ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);_x000D_ Connection connection = connectionFactory.createConnection();_x000D_ connection.start();_x000D_ _x000D_ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);_x000D_ Destination destination = session.createQueue(subject);_x000D_ MessageConsumer consumer = session.createConsumer(destination);_x000D_ _x000D_ int count = 0;_x000D_ _x000D_ // Lijst van Integers_x000D_ List<Integer> list = new ArrayList<>();_x000D_ _x000D_ while (true) {_x000D_ _x000D_ Message message = consumer.receive();_x000D_ if (message instanceof TextMessage) {_x000D_ count++;_x000D_ TextMessage textMessage = (TextMessage) message;_x000D_ _x000D_ // String aan integers opslaan_x000D_ String str = textMessage.getText();_x000D_ // String aan integers opsplitten_x000D_ String[] integerStrings = str.split(" ");_x000D_ _x000D_ // Parse String Integers naar ints_x000D_ for (String integerString : integerStrings) {_x000D_ int j = Integer.parseInt(integerString);_x000D_ // Voeg toe aan list_x000D_ list.add(j);_x000D_ }_x000D_ _x000D_ // Als het aantal lijsten gelijk is aan het aantal producers_x000D_ if (count == Producer.NODES) {_x000D_ int[] array = list.stream().mapToInt(i -> i).toArray();_x000D_ // Sorteer lijsten individueel_x000D_ ConcurrentMergeSort concurrentMergeSort = new ConcurrentMergeSort(array);_x000D_ concurrentMergeSort.sort();_x000D_ _x000D_ if (CustomUtilities.isArraySorted(array))_x000D_ break;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ connection.close();_x000D_ }_x000D_ }
Buggyy/Parallel-Computing
src/activemq/Consumer.java
603
// Parse String Integers naar ints_x000D_
line_comment
nl
package activemq;_x000D_ _x000D_ import algoritmes.ConcurrentMergeSort;_x000D_ import helper.CustomUtilities;_x000D_ import org.apache.activemq.ActiveMQConnectionFactory;_x000D_ _x000D_ import javax.jms.*;_x000D_ import java.util.ArrayList;_x000D_ import java.util.List;_x000D_ _x000D_ import static helper.Config.ACTIVEMQ_URL;_x000D_ _x000D_ /**_x000D_ * Parallel Computing_x000D_ * AUTHOR: R. Lobato & C. Verra_x000D_ */_x000D_ public class Consumer {_x000D_ private static String subject = "resultaat";_x000D_ _x000D_ public static void main(String[] args) throws JMSException {_x000D_ ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);_x000D_ Connection connection = connectionFactory.createConnection();_x000D_ connection.start();_x000D_ _x000D_ Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);_x000D_ Destination destination = session.createQueue(subject);_x000D_ MessageConsumer consumer = session.createConsumer(destination);_x000D_ _x000D_ int count = 0;_x000D_ _x000D_ // Lijst van Integers_x000D_ List<Integer> list = new ArrayList<>();_x000D_ _x000D_ while (true) {_x000D_ _x000D_ Message message = consumer.receive();_x000D_ if (message instanceof TextMessage) {_x000D_ count++;_x000D_ TextMessage textMessage = (TextMessage) message;_x000D_ _x000D_ // String aan integers opslaan_x000D_ String str = textMessage.getText();_x000D_ // String aan integers opsplitten_x000D_ String[] integerStrings = str.split(" ");_x000D_ _x000D_ // Parse String<SUF> for (String integerString : integerStrings) {_x000D_ int j = Integer.parseInt(integerString);_x000D_ // Voeg toe aan list_x000D_ list.add(j);_x000D_ }_x000D_ _x000D_ // Als het aantal lijsten gelijk is aan het aantal producers_x000D_ if (count == Producer.NODES) {_x000D_ int[] array = list.stream().mapToInt(i -> i).toArray();_x000D_ // Sorteer lijsten individueel_x000D_ ConcurrentMergeSort concurrentMergeSort = new ConcurrentMergeSort(array);_x000D_ concurrentMergeSort.sort();_x000D_ _x000D_ if (CustomUtilities.isArraySorted(array))_x000D_ break;_x000D_ }_x000D_ }_x000D_ }_x000D_ _x000D_ connection.close();_x000D_ }_x000D_ }
True
837
14
922
16
953
15
922
16
1,025
17
false
false
false
false
false
true
3,057
36150_0
package be.ibizz.hackathon.repository; import java.io.Reader; import org.ektorp.CouchDbConnector; import org.ektorp.dataload.DataLoader; import org.ektorp.support.CouchDbRepositorySupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import be.ibizz.hackathon.util.loader.CustomDataLoader; /** * Deze abstracte klasse gebruiken we voor alle onderliggende repository classes. Een repository is simpleweg een * klasse die we gebruiken om data te lezen/schrijven. In dit geval dus naar Cloudant. * * De datafiles die hier meegegeven worden zijn de JSON bestanden die je vindt onder src/main/resources/database. * Bij de start van de applicatie wordt deze json data ingeladen in cloudant om snel van start te kunnen gaan. */ public abstract class AbstractCloudantRepository<T> extends CouchDbRepositorySupport<T> implements DataLoader { private static final Logger LOGGER = LoggerFactory.getLogger(AccountRepository.class); private String[] dataFiles; protected AbstractCloudantRepository(Class<T> type, CouchDbConnector db, String... dataFiles) { super(type, db); this.dataFiles = dataFiles; initStandardDesignDocument(); } @Override public void loadInitialData(Reader in) { new CustomDataLoader(db).load(in, type); } @Override public void allDataLoaded() { for(String dataFile : dataFiles) { LOGGER.info("Uploaded '{}'", dataFile); } } @Override public String[] getDataLocations() { return dataFiles; } }
ibizz/hackathon-ucll
app/AB InBev/src/main/java/be/ibizz/hackathon/repository/AbstractCloudantRepository.java
461
/** * Deze abstracte klasse gebruiken we voor alle onderliggende repository classes. Een repository is simpleweg een * klasse die we gebruiken om data te lezen/schrijven. In dit geval dus naar Cloudant. * * De datafiles die hier meegegeven worden zijn de JSON bestanden die je vindt onder src/main/resources/database. * Bij de start van de applicatie wordt deze json data ingeladen in cloudant om snel van start te kunnen gaan. */
block_comment
nl
package be.ibizz.hackathon.repository; import java.io.Reader; import org.ektorp.CouchDbConnector; import org.ektorp.dataload.DataLoader; import org.ektorp.support.CouchDbRepositorySupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import be.ibizz.hackathon.util.loader.CustomDataLoader; /** * Deze abstracte klasse<SUF>*/ public abstract class AbstractCloudantRepository<T> extends CouchDbRepositorySupport<T> implements DataLoader { private static final Logger LOGGER = LoggerFactory.getLogger(AccountRepository.class); private String[] dataFiles; protected AbstractCloudantRepository(Class<T> type, CouchDbConnector db, String... dataFiles) { super(type, db); this.dataFiles = dataFiles; initStandardDesignDocument(); } @Override public void loadInitialData(Reader in) { new CustomDataLoader(db).load(in, type); } @Override public void allDataLoaded() { for(String dataFile : dataFiles) { LOGGER.info("Uploaded '{}'", dataFile); } } @Override public String[] getDataLocations() { return dataFiles; } }
True
349
107
432
127
412
104
432
127
468
119
false
false
false
false
false
true
3,163
186809_11
package com.nhlstenden.JabberPoint.Slides; import com.nhlstenden.JabberPoint.Styles.Style; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.ImageObserver; import java.util.Vector; /** <p>Een slide. Deze klasse heeft tekenfunctionaliteit.</p> * @author Ian F. Darwin, ian@darwinsys.com, Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */ public class Slide { public final static int WIDTH = 1200; public final static int HEIGHT = 800; // De titel wordt apart bewaard private String title; // De slide-items worden in een Vector bewaard private Vector<SlideItem> items; public Slide() { this.items = new Vector<SlideItem>(); } // Voeg een SlideItem toe public void append(SlideItem anItem) { this.items.addElement(anItem); } // Geef de titel van de slide public String getTitle() { return this.title; } // Verander de titel van de slide public void setTitle(String newTitle) { this.title = newTitle; } public Vector<SlideItem> getItems() { return this.items; } public void setItems(Vector<SlideItem> items) { this.items = items; } // Maak een TextItem van String, en voeg het TextItem toe public void appendTextItem(int level, String message) { this.append(new TextItem(level, message)); } // Geef het betreffende SlideItem public SlideItem getSlideItem(int number) { return (SlideItem) this.items.elementAt(number); } // Geef alle SlideItems in een Vector public Vector<SlideItem> getSlideItems() { return this.items; } // Geef de afmeting van de Slide public int getSize() { return this.items.size(); } // Teken de slide public void draw(Graphics graphics, Rectangle area, ImageObserver view) { float scale = this.getScale(area); int y = area.y; // De titel wordt apart behandeld SlideItem slideItem = new TextItem(0, this.getTitle()); Style style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; for (int number = 0; number < this.getSize(); number++) { slideItem = (SlideItem) this.getSlideItems().elementAt(number); style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; } } // Geef de schaal om de slide te kunnen tekenen private float getScale(Rectangle area) { return Math.min(((float) area.width) / ((float) WIDTH), ((float) area.height) / ((float) HEIGHT)); } }
jariolyslager/SoftwareQuality
src/main/java/com/nhlstenden/JabberPoint/Slides/Slide.java
1,010
// De titel wordt apart behandeld
line_comment
nl
package com.nhlstenden.JabberPoint.Slides; import com.nhlstenden.JabberPoint.Styles.Style; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.ImageObserver; import java.util.Vector; /** <p>Een slide. Deze klasse heeft tekenfunctionaliteit.</p> * @author Ian F. Darwin, ian@darwinsys.com, Gert Florijn, Sylvia Stuurman * @version 1.1 2002/12/17 Gert Florijn * @version 1.2 2003/11/19 Sylvia Stuurman * @version 1.3 2004/08/17 Sylvia Stuurman * @version 1.4 2007/07/16 Sylvia Stuurman * @version 1.5 2010/03/03 Sylvia Stuurman * @version 1.6 2014/05/16 Sylvia Stuurman */ public class Slide { public final static int WIDTH = 1200; public final static int HEIGHT = 800; // De titel wordt apart bewaard private String title; // De slide-items worden in een Vector bewaard private Vector<SlideItem> items; public Slide() { this.items = new Vector<SlideItem>(); } // Voeg een SlideItem toe public void append(SlideItem anItem) { this.items.addElement(anItem); } // Geef de titel van de slide public String getTitle() { return this.title; } // Verander de titel van de slide public void setTitle(String newTitle) { this.title = newTitle; } public Vector<SlideItem> getItems() { return this.items; } public void setItems(Vector<SlideItem> items) { this.items = items; } // Maak een TextItem van String, en voeg het TextItem toe public void appendTextItem(int level, String message) { this.append(new TextItem(level, message)); } // Geef het betreffende SlideItem public SlideItem getSlideItem(int number) { return (SlideItem) this.items.elementAt(number); } // Geef alle SlideItems in een Vector public Vector<SlideItem> getSlideItems() { return this.items; } // Geef de afmeting van de Slide public int getSize() { return this.items.size(); } // Teken de slide public void draw(Graphics graphics, Rectangle area, ImageObserver view) { float scale = this.getScale(area); int y = area.y; // De titel<SUF> SlideItem slideItem = new TextItem(0, this.getTitle()); Style style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; for (int number = 0; number < this.getSize(); number++) { slideItem = (SlideItem) this.getSlideItems().elementAt(number); style = Style.getStyle(slideItem.getLevel()); slideItem.draw(area.x, y, scale, graphics, style, view); y += slideItem.getBoundingBox(graphics, view, scale, style).height; } } // Geef de schaal om de slide te kunnen tekenen private float getScale(Rectangle area) { return Math.min(((float) area.width) / ((float) WIDTH), ((float) area.height) / ((float) HEIGHT)); } }
True
828
8
1,003
9
949
8
1,003
9
1,070
9
false
false
false
false
false
true
4,444
75609_1
package nl.topicus.onderwijs.uwlr.shared.webservice.interceptors; import nl.topicus.onderwijs.generated.uwlr.v2_2.UwlrServiceInterfaceV2; import nl.topicus.onderwijs.uwlr.shared.webservice.SoapFault; import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; import org.apache.cxf.phase.Phase; /** * Interceptor die uitgaande berichten van de {@link UwlrServiceInterfaceV2} implementatie afvangt * en kijkt of er een {@link Exception} in het bericht verpakt zit. Als dit het geval is wordt de * {@link Exception} vervangen door een {@link SoapFault}, die voldoet aan de foutberichten uit de * UWLR afspraak. */ public class FaultInterceptor extends AbstractSoapInterceptor { public FaultInterceptor() { super(Phase.PRE_LOGICAL); } @Override public void handleMessage(final SoapMessage message) { // Kijk of in de message een Exception verpakt zit Object exception = message.getContent(Exception.class); // Als er een exception is die niet van het type SoapFault is, dan moet deze // vertaald worden naar een SoapFault. if (exception != null && (!(message.getContent(Exception.class) instanceof SoapFault))) message.setContent( Exception.class, SoapFault.createSoapFault(((Exception) exception).getCause())); } }
takirchjunger/uwlr-client-server
src/main/java/nl/topicus/onderwijs/uwlr/shared/webservice/interceptors/FaultInterceptor.java
431
// Kijk of in de message een Exception verpakt zit
line_comment
nl
package nl.topicus.onderwijs.uwlr.shared.webservice.interceptors; import nl.topicus.onderwijs.generated.uwlr.v2_2.UwlrServiceInterfaceV2; import nl.topicus.onderwijs.uwlr.shared.webservice.SoapFault; import org.apache.cxf.binding.soap.SoapMessage; import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; import org.apache.cxf.phase.Phase; /** * Interceptor die uitgaande berichten van de {@link UwlrServiceInterfaceV2} implementatie afvangt * en kijkt of er een {@link Exception} in het bericht verpakt zit. Als dit het geval is wordt de * {@link Exception} vervangen door een {@link SoapFault}, die voldoet aan de foutberichten uit de * UWLR afspraak. */ public class FaultInterceptor extends AbstractSoapInterceptor { public FaultInterceptor() { super(Phase.PRE_LOGICAL); } @Override public void handleMessage(final SoapMessage message) { // Kijk of<SUF> Object exception = message.getContent(Exception.class); // Als er een exception is die niet van het type SoapFault is, dan moet deze // vertaald worden naar een SoapFault. if (exception != null && (!(message.getContent(Exception.class) instanceof SoapFault))) message.setContent( Exception.class, SoapFault.createSoapFault(((Exception) exception).getCause())); } }
True
324
14
379
14
353
12
379
14
423
14
false
false
false
false
false
true
4,585
7319_3
package be.thomaswinters.similarreplacer; import be.thomaswinters.LambdaExceptionUtil; import be.thomaswinters.markov.model.data.bags.Bag; import be.thomaswinters.markov.model.data.bags.WriteableBag; import be.thomaswinters.markov.model.data.bags.impl.ExclusionBag; import be.thomaswinters.markov.model.data.bags.impl.MutableBag; import be.thomaswinters.random.Picker; import be.thomaswinters.replacement.Replacer; import be.thomaswinters.replacement.Replacers; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.language.Dutch; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class SimilarWordReplacer { /*-********************************************-* * STATIC TOOLS *-********************************************-*/ private static final JLanguageTool langTool = new JLanguageTool(new Dutch()); protected static final Random RANDOM = new Random(); /*-********************************************-*/ /*-********************************************-* * INSTANCE VARIABLES *-********************************************-*/ private Map<Set<String>, WriteableBag<String>> mappings = new HashMap<>(); /*-********************************************-*/ /*-********************************************-* * TAGS & TOKEN FILTERING *-********************************************-*/ protected Set<String> getTags(AnalyzedTokenReadings token) { return token.getReadings().stream().filter(e -> !e.hasNoTag()).map(e -> e.getPOSTag()) .filter(e -> e != null && !e.equals("SENT_END") && !e.equals("PARA_END")).collect(Collectors.toSet()); } private static final Set<String> REPLACEMENT_TOKEN_BLACKLIST = new HashSet<>(Arrays.asList( // Lidwoorden "de", "het", "een", // Algemene onderwerpen "ik", "jij", "je", "u", "wij", "we", "jullie", "hij", "zij", "ze", // Algemene persoonlijke voornaamwoorden "hen", "hem", "haar", "mijn", "uw", "jouw", "onze", "ons", // Algemene werkwoorden "ben", "bent", "is", "was", "waren", "geweest", "heb", "hebt", "heeft", "hebben", "gehad", "word", "wordt", "worden", "geworden", "werd", "werden", "laat", "laten", "liet", "lieten", "gelaten", "ga", "gaat", "gaan", "gegaan", "ging", "gingen", "moet", "moeten", "moest", "moesten", "gemoeten", "mag", "mogen", "mocht", "mochten", "gemogen", "zal", "zullen", "zult", "zou", "zouden", "kan", "kunnen", "gekunt", "gekunnen", "hoef", "hoeft", "hoeven", "hoefde", "hoefden", "gehoeven", // Veelgebruikte woorden "niet", "iets", "dan", "voort", "erna", "welke", "maar", "van", "voor", "met", "binnenkort", "in", "en", "teveel", "om", "alles", "elke", "al", "echt", "waar", "waarom", "hoe", "o.a.", "beetje", "enkel", "goed", "best", "werkende", "meer", "voor", "zit", "echt", "uit", "even", "wel")); private static final Set<String> REPLACEMENT_TAG_BLACKLIST = new HashSet<>( Arrays.asList("AVwaar", "AVwr", "DTh", "DTd", "DTe", "DTp", "PRte", "PRnaar", "PRvan", "PN2", "PRVoor", "PRmet", "PRop", "PRin", "PRom", "PRaan", "AVdr", "CJo")); private List<AnalyzedTokenReadings> filterTokens(List<AnalyzedTokenReadings> tokens) { return tokens.stream().filter(e -> e.getToken().trim().length() > 0).filter(e -> !e.getReadings().isEmpty()) .filter(token -> !getTags(token).isEmpty()) .filter(token -> getTags(token).stream().allMatch(tag -> !REPLACEMENT_TAG_BLACKLIST.contains(tag))) .filter(token -> !REPLACEMENT_TOKEN_BLACKLIST.contains(token.getToken().toLowerCase())) .collect(Collectors.toList()); } /*-********************************************-*/ /*-********************************************-* * PROCESSING KNOWLEDGE INPUT *-********************************************-*/ public void process(String line) throws IOException { List<AnalyzedSentence> answers = langTool.analyzeText(line); for (AnalyzedSentence analyzedSentence : answers) { List<AnalyzedTokenReadings> tokens = filterTokens(Arrays.asList(analyzedSentence.getTokens())); for (AnalyzedTokenReadings token : tokens) { if (token.getToken().trim().length() > 0) { Set<String> tags = getTags(token); // Add if valid if (tags != null && tags.size() > 0) { if (!mappings.containsKey(tags)) { mappings.put(tags, new MutableBag<String>()); } mappings.get(tags).add(token.getToken()); } } } } } public void process(List<String> lines) { lines.forEach(LambdaExceptionUtil.rethrowConsumer(this::process)); } /*-********************************************-*/ /*-********************************************-* * REPLACEABLE CALCULATION *-********************************************-*/ public int getReplaceableSize(Set<String> tags) { if (!mappings.containsKey(tags)) { return 0; } return mappings.get(tags).size(); } public List<AnalyzedTokenReadings> getReplaceableTokens(String line) { List<AnalyzedSentence> answers; try { answers = langTool.analyzeText(line); } catch (IOException e1) { throw new RuntimeException(e1); } List<AnalyzedTokenReadings> tokens = new ArrayList<>(); for (AnalyzedSentence analyzedSentence : answers) { tokens.addAll(Arrays.asList(analyzedSentence.getTokens())); } tokens = filterTokens(tokens).stream().filter(e -> getReplaceableSize(getTags(e)) > 1) .collect(Collectors.toList()); return tokens; } public Optional<Replacer> createReplacer(AnalyzedTokenReadings token, Bag<String> replacePossibilities) { // Check if there is another possibility than to replace with itself if (replacePossibilities.isEmpty() || (replacePossibilities.getAmountOfUniqueElements() == 1 && replacePossibilities.get(0).toLowerCase().equals(token.getToken().toLowerCase()))) { return Optional.empty(); } Bag<String> bag = new ExclusionBag<String>(replacePossibilities, Arrays.asList(token.getToken())); String replacement = pickReplacement(token.getToken(), bag); Replacer replacer = new Replacer(token.getToken(), replacement, false, true); return Optional.of(replacer); } public String pickReplacement(String replacement, Bag<String> bag) { return bag.get(RANDOM.nextInt(bag.getAmountOfElements())); } public List<Replacer> calculatePossibleReplacements(String line) { Set<AnalyzedTokenReadings> tokens = new LinkedHashSet<>(getReplaceableTokens(line)); List<Replacer> replacers = new ArrayList<>(); for (AnalyzedTokenReadings token : tokens) { Bag<String> replacePossibilities = mappings.get(getTags(token)); createReplacer(token, replacePossibilities).ifPresent(replacer -> replacers.add(replacer)); // System.out.println((createReplacer(token, replacePossibilities).isPresent()) + " mapping of " + token // + "\n=>" + replacePossibilities); } return replacers; } /*-********************************************-*/ public String replaceSomething(String line, int amountOfReplacements) { List<Replacer> replacers = calculatePossibleReplacements(line); Set<Replacer> chosenReplacers = new LinkedHashSet<>( Picker.pickRandomUniqueIndices(Math.min(replacers.size(), amountOfReplacements), replacers.size()) .stream().map(idx -> replacers.get(idx)).collect(Collectors.toList())); return (new Replacers(chosenReplacers)).replace(line); } }
twinters/torfs-bot
src/main/java/be/thomaswinters/similarreplacer/SimilarWordReplacer.java
2,514
// Algemene persoonlijke voornaamwoorden
line_comment
nl
package be.thomaswinters.similarreplacer; import be.thomaswinters.LambdaExceptionUtil; import be.thomaswinters.markov.model.data.bags.Bag; import be.thomaswinters.markov.model.data.bags.WriteableBag; import be.thomaswinters.markov.model.data.bags.impl.ExclusionBag; import be.thomaswinters.markov.model.data.bags.impl.MutableBag; import be.thomaswinters.random.Picker; import be.thomaswinters.replacement.Replacer; import be.thomaswinters.replacement.Replacers; import org.languagetool.AnalyzedSentence; import org.languagetool.AnalyzedTokenReadings; import org.languagetool.JLanguageTool; import org.languagetool.language.Dutch; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; public class SimilarWordReplacer { /*-********************************************-* * STATIC TOOLS *-********************************************-*/ private static final JLanguageTool langTool = new JLanguageTool(new Dutch()); protected static final Random RANDOM = new Random(); /*-********************************************-*/ /*-********************************************-* * INSTANCE VARIABLES *-********************************************-*/ private Map<Set<String>, WriteableBag<String>> mappings = new HashMap<>(); /*-********************************************-*/ /*-********************************************-* * TAGS & TOKEN FILTERING *-********************************************-*/ protected Set<String> getTags(AnalyzedTokenReadings token) { return token.getReadings().stream().filter(e -> !e.hasNoTag()).map(e -> e.getPOSTag()) .filter(e -> e != null && !e.equals("SENT_END") && !e.equals("PARA_END")).collect(Collectors.toSet()); } private static final Set<String> REPLACEMENT_TOKEN_BLACKLIST = new HashSet<>(Arrays.asList( // Lidwoorden "de", "het", "een", // Algemene onderwerpen "ik", "jij", "je", "u", "wij", "we", "jullie", "hij", "zij", "ze", // Algemene persoonlijke<SUF> "hen", "hem", "haar", "mijn", "uw", "jouw", "onze", "ons", // Algemene werkwoorden "ben", "bent", "is", "was", "waren", "geweest", "heb", "hebt", "heeft", "hebben", "gehad", "word", "wordt", "worden", "geworden", "werd", "werden", "laat", "laten", "liet", "lieten", "gelaten", "ga", "gaat", "gaan", "gegaan", "ging", "gingen", "moet", "moeten", "moest", "moesten", "gemoeten", "mag", "mogen", "mocht", "mochten", "gemogen", "zal", "zullen", "zult", "zou", "zouden", "kan", "kunnen", "gekunt", "gekunnen", "hoef", "hoeft", "hoeven", "hoefde", "hoefden", "gehoeven", // Veelgebruikte woorden "niet", "iets", "dan", "voort", "erna", "welke", "maar", "van", "voor", "met", "binnenkort", "in", "en", "teveel", "om", "alles", "elke", "al", "echt", "waar", "waarom", "hoe", "o.a.", "beetje", "enkel", "goed", "best", "werkende", "meer", "voor", "zit", "echt", "uit", "even", "wel")); private static final Set<String> REPLACEMENT_TAG_BLACKLIST = new HashSet<>( Arrays.asList("AVwaar", "AVwr", "DTh", "DTd", "DTe", "DTp", "PRte", "PRnaar", "PRvan", "PN2", "PRVoor", "PRmet", "PRop", "PRin", "PRom", "PRaan", "AVdr", "CJo")); private List<AnalyzedTokenReadings> filterTokens(List<AnalyzedTokenReadings> tokens) { return tokens.stream().filter(e -> e.getToken().trim().length() > 0).filter(e -> !e.getReadings().isEmpty()) .filter(token -> !getTags(token).isEmpty()) .filter(token -> getTags(token).stream().allMatch(tag -> !REPLACEMENT_TAG_BLACKLIST.contains(tag))) .filter(token -> !REPLACEMENT_TOKEN_BLACKLIST.contains(token.getToken().toLowerCase())) .collect(Collectors.toList()); } /*-********************************************-*/ /*-********************************************-* * PROCESSING KNOWLEDGE INPUT *-********************************************-*/ public void process(String line) throws IOException { List<AnalyzedSentence> answers = langTool.analyzeText(line); for (AnalyzedSentence analyzedSentence : answers) { List<AnalyzedTokenReadings> tokens = filterTokens(Arrays.asList(analyzedSentence.getTokens())); for (AnalyzedTokenReadings token : tokens) { if (token.getToken().trim().length() > 0) { Set<String> tags = getTags(token); // Add if valid if (tags != null && tags.size() > 0) { if (!mappings.containsKey(tags)) { mappings.put(tags, new MutableBag<String>()); } mappings.get(tags).add(token.getToken()); } } } } } public void process(List<String> lines) { lines.forEach(LambdaExceptionUtil.rethrowConsumer(this::process)); } /*-********************************************-*/ /*-********************************************-* * REPLACEABLE CALCULATION *-********************************************-*/ public int getReplaceableSize(Set<String> tags) { if (!mappings.containsKey(tags)) { return 0; } return mappings.get(tags).size(); } public List<AnalyzedTokenReadings> getReplaceableTokens(String line) { List<AnalyzedSentence> answers; try { answers = langTool.analyzeText(line); } catch (IOException e1) { throw new RuntimeException(e1); } List<AnalyzedTokenReadings> tokens = new ArrayList<>(); for (AnalyzedSentence analyzedSentence : answers) { tokens.addAll(Arrays.asList(analyzedSentence.getTokens())); } tokens = filterTokens(tokens).stream().filter(e -> getReplaceableSize(getTags(e)) > 1) .collect(Collectors.toList()); return tokens; } public Optional<Replacer> createReplacer(AnalyzedTokenReadings token, Bag<String> replacePossibilities) { // Check if there is another possibility than to replace with itself if (replacePossibilities.isEmpty() || (replacePossibilities.getAmountOfUniqueElements() == 1 && replacePossibilities.get(0).toLowerCase().equals(token.getToken().toLowerCase()))) { return Optional.empty(); } Bag<String> bag = new ExclusionBag<String>(replacePossibilities, Arrays.asList(token.getToken())); String replacement = pickReplacement(token.getToken(), bag); Replacer replacer = new Replacer(token.getToken(), replacement, false, true); return Optional.of(replacer); } public String pickReplacement(String replacement, Bag<String> bag) { return bag.get(RANDOM.nextInt(bag.getAmountOfElements())); } public List<Replacer> calculatePossibleReplacements(String line) { Set<AnalyzedTokenReadings> tokens = new LinkedHashSet<>(getReplaceableTokens(line)); List<Replacer> replacers = new ArrayList<>(); for (AnalyzedTokenReadings token : tokens) { Bag<String> replacePossibilities = mappings.get(getTags(token)); createReplacer(token, replacePossibilities).ifPresent(replacer -> replacers.add(replacer)); // System.out.println((createReplacer(token, replacePossibilities).isPresent()) + " mapping of " + token // + "\n=>" + replacePossibilities); } return replacers; } /*-********************************************-*/ public String replaceSomething(String line, int amountOfReplacements) { List<Replacer> replacers = calculatePossibleReplacements(line); Set<Replacer> chosenReplacers = new LinkedHashSet<>( Picker.pickRandomUniqueIndices(Math.min(replacers.size(), amountOfReplacements), replacers.size()) .stream().map(idx -> replacers.get(idx)).collect(Collectors.toList())); return (new Replacers(chosenReplacers)).replace(line); } }
True
1,930
12
2,171
13
2,124
7
2,171
13
2,557
12
false
false
false
false
false
true
4,802
83718_1
/* * Copyright (c) 2013-2015 Frank de Jonge * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.flysystem.core; /** * @author Zeger Hoogeboom */ public interface Adapter extends Read, Write { }
zegerhoogeboom/flysystem-java
src/main/java/com/flysystem/core/Adapter.java
351
/** * @author Zeger Hoogeboom */
block_comment
nl
/* * Copyright (c) 2013-2015 Frank de Jonge * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished * to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.flysystem.core; /** * @author Zeger Hoogeboom<SUF>*/ public interface Adapter extends Read, Write { }
False
270
11
290
13
295
12
290
13
404
14
false
false
false
false
false
true
4,468
21047_3
public class Student { // LOOPS ============================================== // Je belegt €1000 tegen 5%. Schrijf een functie invest(goal) die gegeven een doelbedrag goal, // uitrekent hoeveel jaar het duur eer je €1000 gegroeid zijn tot goal. // Ga ervan uit dat de intrest telkens toegevoegd wordt op het einde van elk jaar. // // Je kan dit in principe met logaritmes oplossen, maar dit valt buiten het bereik van dit vak. // Voor deze oefening is het de bedoeling dat je een lus gebruikt om herhaaldelijk 5% toe te voegen // aan het initieel bedrag tot het voldoende gegroeid is. }
testMJTesting/mj_test4
04-loops/Student.java
193
// Je kan dit in principe met logaritmes oplossen, maar dit valt buiten het bereik van dit vak.
line_comment
nl
public class Student { // LOOPS ============================================== // Je belegt €1000 tegen 5%. Schrijf een functie invest(goal) die gegeven een doelbedrag goal, // uitrekent hoeveel jaar het duur eer je €1000 gegroeid zijn tot goal. // Ga ervan uit dat de intrest telkens toegevoegd wordt op het einde van elk jaar. // // Je kan<SUF> // Voor deze oefening is het de bedoeling dat je een lus gebruikt om herhaaldelijk 5% toe te voegen // aan het initieel bedrag tot het voldoende gegroeid is. }
False
182
27
198
32
163
24
198
32
200
29
false
false
false
false
false
true
4,049
115703_5
package gruppe38.Bilder; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; /** * Initialisiert die Bilder -> Gleiche Groesse * * @author Gruppe38 * * */ public class BilderInit { public BufferedImage[] loadPics(String path, int pics) { BufferedImage[] anim = new BufferedImage[pics]; BufferedImage source = null; URL pic_url = getClass().getClassLoader().getResource(path); try { source = ImageIO.read(pic_url); } catch (IOException e) { e.printStackTrace(); } for (int x = 0; x < pics; x++) { anim[x] = source.getSubimage(x * source.getWidth() / pics, 0, source.getWidth() / pics, source.getHeight()); } return anim; } // Bild_reference wird ben�tigt um bei allein bildern die gleiche public BufferedImage mauer; public BufferedImage bombe; public BufferedImage explosion; public BufferedImage bombe_extra; public BufferedImage bombe_energie; public BufferedImage mauer_destroyable; public BufferedImage armor; public BufferedImage cake; public BufferedImage explosiv; public BufferedImage feuer; public BufferedImage exit; public BufferedImage spawn; public BufferedImage atom; public void init() { mauer = loadPics("mauer.png", 1)[0]; bombe = loadPics("pics/background.jpg", 1)[0]; explosion = loadPics("pics/background.jpg", 1)[0]; bombe_extra = loadPics("src/gruppe38/Bilder/bombe_energie.png", 1)[0]; bombe_energie = loadPics("src/gruppe38/Bilder/bombe_extra.png", 1)[0]; mauer_destroyable = loadPics( "src/gruppe38/Bilder/mauer_destroyable1.png", 1)[0]; armor = loadPics("pics/background.jpg", 1)[0]; cake = loadPics("src/gruppe38/Bilder/mauer_destroyable1.png", 1)[0]; explosiv = loadPics("pics/background.jpg", 1)[0]; feuer = loadPics("pics/background.jpg", 1)[0]; exit = loadPics("exit.png", 1)[0]; atom = loadPics("Bilder/Radioactive.png", 1)[0]; } // public Image bild_reference = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer.png"); // public static Image bombe = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/bombe_extra.png"); // public Image feuer = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/bombe_energie.png"); // public Image explosiv = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/bombe_extra.png"); // public Image mauer = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer.png"); // public Image mauer_destroyable = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer_destroyable1.png"); // public Image armor = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer_destroyable1.png"); // public Image cake = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer.png"); // public Image explosion = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/explosion2.png"); }
propra12-orga/gruppe38
Bilder/BilderInit.java
1,074
// public Image explosiv = Toolkit.getDefaultToolkit().getImage(
line_comment
nl
package gruppe38.Bilder; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; /** * Initialisiert die Bilder -> Gleiche Groesse * * @author Gruppe38 * * */ public class BilderInit { public BufferedImage[] loadPics(String path, int pics) { BufferedImage[] anim = new BufferedImage[pics]; BufferedImage source = null; URL pic_url = getClass().getClassLoader().getResource(path); try { source = ImageIO.read(pic_url); } catch (IOException e) { e.printStackTrace(); } for (int x = 0; x < pics; x++) { anim[x] = source.getSubimage(x * source.getWidth() / pics, 0, source.getWidth() / pics, source.getHeight()); } return anim; } // Bild_reference wird ben�tigt um bei allein bildern die gleiche public BufferedImage mauer; public BufferedImage bombe; public BufferedImage explosion; public BufferedImage bombe_extra; public BufferedImage bombe_energie; public BufferedImage mauer_destroyable; public BufferedImage armor; public BufferedImage cake; public BufferedImage explosiv; public BufferedImage feuer; public BufferedImage exit; public BufferedImage spawn; public BufferedImage atom; public void init() { mauer = loadPics("mauer.png", 1)[0]; bombe = loadPics("pics/background.jpg", 1)[0]; explosion = loadPics("pics/background.jpg", 1)[0]; bombe_extra = loadPics("src/gruppe38/Bilder/bombe_energie.png", 1)[0]; bombe_energie = loadPics("src/gruppe38/Bilder/bombe_extra.png", 1)[0]; mauer_destroyable = loadPics( "src/gruppe38/Bilder/mauer_destroyable1.png", 1)[0]; armor = loadPics("pics/background.jpg", 1)[0]; cake = loadPics("src/gruppe38/Bilder/mauer_destroyable1.png", 1)[0]; explosiv = loadPics("pics/background.jpg", 1)[0]; feuer = loadPics("pics/background.jpg", 1)[0]; exit = loadPics("exit.png", 1)[0]; atom = loadPics("Bilder/Radioactive.png", 1)[0]; } // public Image bild_reference = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer.png"); // public static Image bombe = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/bombe_extra.png"); // public Image feuer = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/bombe_energie.png"); // public Image<SUF> // "src/gruppe38/Bilder/bombe_extra.png"); // public Image mauer = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer.png"); // public Image mauer_destroyable = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer_destroyable1.png"); // public Image armor = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer_destroyable1.png"); // public Image cake = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/mauer.png"); // public Image explosion = Toolkit.getDefaultToolkit().getImage( // "src/gruppe38/Bilder/explosion2.png"); }
False
808
12
1,015
14
906
13
1,015
14
1,105
17
false
false
false
false
false
true
1,784
66585_36
/** * This file is part of TuCan Mobile. * * TuCan Mobile 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. * * TuCan Mobile 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 TuCan Mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.dalthed.tucan.scraper; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.util.Log; import android.widget.ListAdapter; import com.dalthed.tucan.R; import com.dalthed.tucan.TucanMobile; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.adapters.OneLineTwoColsAdapter; import com.dalthed.tucan.exceptions.LostSessionException; import com.dalthed.tucan.exceptions.TucanDownException; public class MainMenuScraper extends BasicScraper { /** * Set true if User has selected English */ public static boolean isEnglish = false; public String SessionArgument; public boolean noeventstoday = false; /** * Array an Links zu den Seiten der heutigen Veranstaltungen */ public String[] today_event_links; /** * Der Name des Users */ public String UserName; /** * URL zum Vorlesungsverzeichnis */ public String menu_link_vv; /** * URL zu den Prüfungen */ public String menu_link_ex; /** * URL zu den Nachrichten */ public String menu_link_msg; /** * Stores link of Event location overview */ public String load_link_ev_loc; /** * Last called URl */ public URL lcURL; /** * URL zu Stundenplan */ public String menu_link_month; /** * Gibt an, ob die Tucan-Webseite eine Bewerbungsseite darstellt. */ public boolean isApplication = false; public MainMenuScraper(Context context, AnswerObject result) { super(context, result); } /** * Getter and Setter */ public boolean getIsEnglish() { return isEnglish; } public void setIsEnglish(boolean isEnglish) { MainMenuScraper.isEnglish = isEnglish; } @Override public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { if (checkForLostSeesion()) { if(TucanMobile.CRASH) { //Crash with HTML ArrayList<String> crashList = new ArrayList<String>(); crashList.add("fail"); crashList.get(16); } getSessionArgument(); scrapeMenuLinks(); return getTodaysEvents(); } return null; } /** * Checks if Tucan is set to german. Otherwise, the App wont work * * @param context * Activity context * @since 2012-07-17 * @author Daniel Thiem */ public void checkForRightTucanLanguage(final Activity context) { // if (doc.select("li#link000326").select("a").attr("href").equals("")) { // Dialog wronglanguageDialog = new AlertDialog.Builder(context).setTitle("") // .setMessage(R.string.general_not_supported_lang) // .setPositiveButton("Okay", new DialogInterface.OnClickListener() { // // public void onClick(DialogInterface dialog, int which) { // context.finish(); // } // }).create(); // wronglanguageDialog.show(); // // } if (doc.select("li#link000326").select("a").attr("href").equals("")) { setIsEnglish(true); scrapeMenuLinks(); } } public void bufferLinks(Activity context, CookieManager localCookieManager) { try { FileOutputStream fos = context.openFileOutput(TucanMobile.LINK_FILE_NAME, Context.MODE_PRIVATE); StringBuilder cacheString = new StringBuilder(); cacheString.append(menu_link_vv).append(">>").append(menu_link_month).append(">>") .append(menu_link_ex).append(">>").append(menu_link_ex).append(">>") .append(menu_link_msg).append("<<") .append(localCookieManager.getCookieHTTPString(TucanMobile.TUCAN_HOST)) .append("<<").append(SessionArgument); fos.write(cacheString.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @return */ private ListAdapter getTodaysEvents() { // Tabelle mit den Terminen finden und Durchlaufen Element EventTable = doc.select("table.nb").first(); String[] Events; String[] Times; if (EventTable == null) { // Falls keine Events gefunden werden, wird das angezeigt Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { if (EventTable.select("tr.tbdata").first().select("td").size() == 5) { // Wen die Anzahl der Spalten der entsprechenden Tabelle 5 // ist, ist das ein Anzeichen dafür, dass heute keine // Veranstaltungen sind Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { // Nehme die einzelnen Event-Zeilen heraus und gehe diese durch Elements EventRows = EventTable.select("tr.tbdata"); Iterator<Element> RowIt = EventRows.iterator(); Events = new String[EventRows.size()]; Times = new String[EventRows.size()]; today_event_links = new String[EventRows.size()]; int i = 0; while (RowIt.hasNext()) { Element currentElement = (Element) RowIt.next(); // Informationen aus HTML parsen String EventString = currentElement.select("td[headers=Name]").select("a") .first().text(); today_event_links[i] = currentElement.select("td[headers=Name]").select("a") .first().attr("href"); // Zeit zusammenfügen String EventTimeString = currentElement.select("td").get(2).select("a").first() .text(); String EventTimeEndString = currentElement.select("td").get(3).select("a") .first().text(); Times[i] = EventTimeString + "-" + EventTimeEndString; Events[i] = EventString; i++; } } } ListAdapter returnAdapter = new OneLineTwoColsAdapter(context, Events, Times); return returnAdapter; } /** * */ private void scrapeMenuLinks() { UserName = doc.select("span#loginDataName").text().split(":")[1]; lcURL = null; try { lcURL = new URL(lastCalledUrl); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Malformed URL"); } Elements linkstoOuterWorld = doc.select("div.tb"); if(linkstoOuterWorld.size() > 1) { // Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); // menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000271").select("a").attr("href"); // menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000326").select("a").attr("href"); // menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000280").select("a").attr("href"); // menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // // Load special Location Information // load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST // + doc.select("li#link000269").select("a").attr("href"); if (!getIsEnglish()) { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000271").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000326").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000280").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000269").select("a").attr("href"); } else { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000057").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000352").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000360").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000055").select("a").attr("href"); } } else { //Bewerbungsmodus isApplication = true; } } /** * */ private void getSessionArgument() { // Die Session ID aus URL gewinnen if (!TucanMobile.TESTING) { try { lcURL = new URL(lastCalledUrl); SessionArgument = lcURL.getQuery().split("ARGUMENTS=")[1].split(",")[0]; } catch (MalformedURLException e) { e.printStackTrace(); } } } }
Tyde/TuCanMobile
app/src/main/java/com/dalthed/tucan/scraper/MainMenuScraper.java
3,398
//" + lcURL.getHost()
line_comment
nl
/** * This file is part of TuCan Mobile. * * TuCan Mobile 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. * * TuCan Mobile 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 TuCan Mobile. If not, see <http://www.gnu.org/licenses/>. */ package com.dalthed.tucan.scraper; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.util.Log; import android.widget.ListAdapter; import com.dalthed.tucan.R; import com.dalthed.tucan.TucanMobile; import com.dalthed.tucan.Connection.AnswerObject; import com.dalthed.tucan.Connection.CookieManager; import com.dalthed.tucan.adapters.OneLineTwoColsAdapter; import com.dalthed.tucan.exceptions.LostSessionException; import com.dalthed.tucan.exceptions.TucanDownException; public class MainMenuScraper extends BasicScraper { /** * Set true if User has selected English */ public static boolean isEnglish = false; public String SessionArgument; public boolean noeventstoday = false; /** * Array an Links zu den Seiten der heutigen Veranstaltungen */ public String[] today_event_links; /** * Der Name des Users */ public String UserName; /** * URL zum Vorlesungsverzeichnis */ public String menu_link_vv; /** * URL zu den Prüfungen */ public String menu_link_ex; /** * URL zu den Nachrichten */ public String menu_link_msg; /** * Stores link of Event location overview */ public String load_link_ev_loc; /** * Last called URl */ public URL lcURL; /** * URL zu Stundenplan */ public String menu_link_month; /** * Gibt an, ob die Tucan-Webseite eine Bewerbungsseite darstellt. */ public boolean isApplication = false; public MainMenuScraper(Context context, AnswerObject result) { super(context, result); } /** * Getter and Setter */ public boolean getIsEnglish() { return isEnglish; } public void setIsEnglish(boolean isEnglish) { MainMenuScraper.isEnglish = isEnglish; } @Override public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { if (checkForLostSeesion()) { if(TucanMobile.CRASH) { //Crash with HTML ArrayList<String> crashList = new ArrayList<String>(); crashList.add("fail"); crashList.get(16); } getSessionArgument(); scrapeMenuLinks(); return getTodaysEvents(); } return null; } /** * Checks if Tucan is set to german. Otherwise, the App wont work * * @param context * Activity context * @since 2012-07-17 * @author Daniel Thiem */ public void checkForRightTucanLanguage(final Activity context) { // if (doc.select("li#link000326").select("a").attr("href").equals("")) { // Dialog wronglanguageDialog = new AlertDialog.Builder(context).setTitle("") // .setMessage(R.string.general_not_supported_lang) // .setPositiveButton("Okay", new DialogInterface.OnClickListener() { // // public void onClick(DialogInterface dialog, int which) { // context.finish(); // } // }).create(); // wronglanguageDialog.show(); // // } if (doc.select("li#link000326").select("a").attr("href").equals("")) { setIsEnglish(true); scrapeMenuLinks(); } } public void bufferLinks(Activity context, CookieManager localCookieManager) { try { FileOutputStream fos = context.openFileOutput(TucanMobile.LINK_FILE_NAME, Context.MODE_PRIVATE); StringBuilder cacheString = new StringBuilder(); cacheString.append(menu_link_vv).append(">>").append(menu_link_month).append(">>") .append(menu_link_ex).append(">>").append(menu_link_ex).append(">>") .append(menu_link_msg).append("<<") .append(localCookieManager.getCookieHTTPString(TucanMobile.TUCAN_HOST)) .append("<<").append(SessionArgument); fos.write(cacheString.toString().getBytes()); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * @return */ private ListAdapter getTodaysEvents() { // Tabelle mit den Terminen finden und Durchlaufen Element EventTable = doc.select("table.nb").first(); String[] Events; String[] Times; if (EventTable == null) { // Falls keine Events gefunden werden, wird das angezeigt Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { if (EventTable.select("tr.tbdata").first().select("td").size() == 5) { // Wen die Anzahl der Spalten der entsprechenden Tabelle 5 // ist, ist das ein Anzeichen dafür, dass heute keine // Veranstaltungen sind Events = new String[1]; Times = new String[1]; // Events[0] = "Keine Heutigen Veranstaltungen"; Events[0] = context.getString(R.string.no_events_today); Times[0] = ""; noeventstoday = true; } else { // Nehme die einzelnen Event-Zeilen heraus und gehe diese durch Elements EventRows = EventTable.select("tr.tbdata"); Iterator<Element> RowIt = EventRows.iterator(); Events = new String[EventRows.size()]; Times = new String[EventRows.size()]; today_event_links = new String[EventRows.size()]; int i = 0; while (RowIt.hasNext()) { Element currentElement = (Element) RowIt.next(); // Informationen aus HTML parsen String EventString = currentElement.select("td[headers=Name]").select("a") .first().text(); today_event_links[i] = currentElement.select("td[headers=Name]").select("a") .first().attr("href"); // Zeit zusammenfügen String EventTimeString = currentElement.select("td").get(2).select("a").first() .text(); String EventTimeEndString = currentElement.select("td").get(3).select("a") .first().text(); Times[i] = EventTimeString + "-" + EventTimeEndString; Events[i] = EventString; i++; } } } ListAdapter returnAdapter = new OneLineTwoColsAdapter(context, Events, Times); return returnAdapter; } /** * */ private void scrapeMenuLinks() { UserName = doc.select("span#loginDataName").text().split(":")[1]; lcURL = null; try { lcURL = new URL(lastCalledUrl); } catch (MalformedURLException e) { Log.e(LOG_TAG, "Malformed URL"); } Elements linkstoOuterWorld = doc.select("div.tb"); if(linkstoOuterWorld.size() > 1) { // Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); // menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000271").select("a").attr("href"); // menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000326").select("a").attr("href"); // menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() // + doc.select("li#link000280").select("a").attr("href"); // menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // // Load special Location Information // load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST // + doc.select("li#link000269").select("a").attr("href"); if (!getIsEnglish()) { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000271").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000326").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" +<SUF> + doc.select("li#link000280").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000269").select("a").attr("href"); } else { Element ArchivLink = linkstoOuterWorld.get(1).select("a").first(); menu_link_month = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000057").select("a").attr("href"); menu_link_vv = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000352").select("a").attr("href"); menu_link_ex = lcURL.getProtocol() + "://" + lcURL.getHost() + doc.select("li#link000360").select("a").attr("href"); menu_link_msg = lcURL.getProtocol() + "://" + lcURL.getHost() + ArchivLink.attr("href"); // Load special Location Information load_link_ev_loc = TucanMobile.TUCAN_PROT + TucanMobile.TUCAN_HOST + doc.select("li#link000055").select("a").attr("href"); } } else { //Bewerbungsmodus isApplication = true; } } /** * */ private void getSessionArgument() { // Die Session ID aus URL gewinnen if (!TucanMobile.TESTING) { try { lcURL = new URL(lastCalledUrl); SessionArgument = lcURL.getQuery().split("ARGUMENTS=")[1].split(",")[0]; } catch (MalformedURLException e) { e.printStackTrace(); } } } }
False
2,692
6
3,186
8
3,071
7
3,186
8
3,782
10
false
false
false
false
false
true
588
14678_12
package nl.nijmegen.mule.agelimits;_x000D_ _x000D_ import java.time.LocalDate;_x000D_ import org.mule.api.MuleMessage;_x000D_ import org.mule.api.transformer.TransformerException;_x000D_ import org.mule.api.transport.PropertyScope;_x000D_ import org.mule.transformer.AbstractMessageTransformer;_x000D_ import org.apache.commons.logging.Log;_x000D_ import org.apache.commons.logging.LogFactory;_x000D_ _x000D_ public class calculateAgeLimits extends AbstractMessageTransformer{_x000D_ private static Log logger = LogFactory.getLog("nl.Nijmegen.brp.irma-api.calculateagelimits");_x000D_ _x000D_ _x000D_ @Override_x000D_ public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {_x000D_ _x000D_ //Zet geboortedatum_x000D_ //String bDay = "20000000";_x000D_ //String bDay = message.getInvocationProperty("sv_geboortedatum");_x000D_ String bDay = message.getProperty("sv_geboortedatum", PropertyScope.INVOCATION);_x000D_ //Code uit elkaar halen op jaar, maand en dag _x000D_ int lengteBDay = bDay.length();_x000D_ if (lengteBDay !=8) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ _x000D_ } _x000D_ //Code uit elkaar halen op jaar, maand en dag_x000D_ String bYear = (bDay.substring(0,4));_x000D_ String bMonth1= bDay.substring(bDay.length() - 4);_x000D_ String bMonth2 = (bMonth1.substring(0,2));_x000D_ String bDag = bDay.substring(bDay.length() - 2);_x000D_ _x000D_ _x000D_ //omzetten naar een int._x000D_ int bYearInt = Integer.parseInt(bYear);_x000D_ int bMonthInt = Integer.parseInt(bMonth2);_x000D_ int bDagInt = Integer.parseInt(bDag);_x000D_ logger.debug("jaar: " + bYearInt);_x000D_ logger.debug("maand: " + bMonthInt);_x000D_ logger.debug("dag: " + bDagInt);_x000D_ _x000D_ if (bYearInt ==0 || bYearInt <1850) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ }_x000D_ if (bMonthInt >12) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ if (bDagInt >31) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ _x000D_ //als maand null is dan 1 juli invullen_x000D_ if (bMonthInt == 0) {_x000D_ bMonthInt = 1;_x000D_ bMonthInt = 7;}_x000D_ //als dag null is, dan waarde op 1 zetten en vervolgens naar laatste dag van de maand_x000D_ if (bDagInt == 00) {_x000D_ _x000D_ LocalDate noDay = LocalDate.of(bYearInt,bMonthInt,1);_x000D_ LocalDate end = noDay.withDayOfMonth(noDay.lengthOfMonth());_x000D_ int dayOfMonth = end.getDayOfMonth();_x000D_ bDagInt = dayOfMonth;_x000D_ }_x000D_ if (bMonthInt == 2 & bDagInt == 29) {_x000D_ bDagInt=28;_x000D_ }_x000D_ _x000D_ String resultString = "";_x000D_ _x000D_ //geboortedag bepalen_x000D_ LocalDate currentTime = LocalDate.now();_x000D_ LocalDate birthday = LocalDate.of(bYearInt,bMonthInt,bDagInt);_x000D_ logger.debug("Huidige datum: " + currentTime);_x000D_ logger.debug("Geboortedatum: " + birthday);_x000D_ _x000D_ _x000D_ //array maken met alle jaren erin _x000D_ int[] jaar = new int[] {12,16,18,21,65};_x000D_ for (int i=0; i<jaar.length; i++)_x000D_ {_x000D_ //door array lopen_x000D_ //in de array current date bepalen_x000D_ //jaren van currentdate afhalen_x000D_ LocalDate date1 = LocalDate.now().minusYears(jaar[i]);_x000D_ _x000D_ String resultValue;_x000D_ String resultLabel;_x000D_ //vergelijken geboortedatum en currentdate_x000D_ if(date1.isBefore(birthday)) {_x000D_ resultValue = "No";_x000D_ }_x000D_ else {_x000D_ resultValue = "Yes";_x000D_ _x000D_ }_x000D_ //string met "isOver+jaar":'ja/nee'" vullen en concateren over loop heen_x000D_ resultLabel = "\"" +"over" + jaar[i]; _x000D_ resultString = resultString + resultLabel + "\"" +":"+ "\"" + resultValue + "\"" + ",";_x000D_ }_x000D_ //resultString teruggeven_x000D_ resultString = "{" + resultString.substring(0, resultString.length()-1) +"}";_x000D_ resultString = "{"+ "\""+"ageLimits"+"\""+": " + resultString +"}";_x000D_ logger.debug("resultString: " + resultString);_x000D_ return resultString;_x000D_ _x000D_ }_x000D_ _x000D_ };_x000D_ _x000D_ _x000D_ _x000D_
GemeenteNijmegen/irma-brp-opladen
src/api-source/calculateAgeLimits.java
1,510
//string met "isOver+jaar":'ja/nee'" vullen en concateren over loop heen_x000D_
line_comment
nl
package nl.nijmegen.mule.agelimits;_x000D_ _x000D_ import java.time.LocalDate;_x000D_ import org.mule.api.MuleMessage;_x000D_ import org.mule.api.transformer.TransformerException;_x000D_ import org.mule.api.transport.PropertyScope;_x000D_ import org.mule.transformer.AbstractMessageTransformer;_x000D_ import org.apache.commons.logging.Log;_x000D_ import org.apache.commons.logging.LogFactory;_x000D_ _x000D_ public class calculateAgeLimits extends AbstractMessageTransformer{_x000D_ private static Log logger = LogFactory.getLog("nl.Nijmegen.brp.irma-api.calculateagelimits");_x000D_ _x000D_ _x000D_ @Override_x000D_ public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {_x000D_ _x000D_ //Zet geboortedatum_x000D_ //String bDay = "20000000";_x000D_ //String bDay = message.getInvocationProperty("sv_geboortedatum");_x000D_ String bDay = message.getProperty("sv_geboortedatum", PropertyScope.INVOCATION);_x000D_ //Code uit elkaar halen op jaar, maand en dag _x000D_ int lengteBDay = bDay.length();_x000D_ if (lengteBDay !=8) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ _x000D_ } _x000D_ //Code uit elkaar halen op jaar, maand en dag_x000D_ String bYear = (bDay.substring(0,4));_x000D_ String bMonth1= bDay.substring(bDay.length() - 4);_x000D_ String bMonth2 = (bMonth1.substring(0,2));_x000D_ String bDag = bDay.substring(bDay.length() - 2);_x000D_ _x000D_ _x000D_ //omzetten naar een int._x000D_ int bYearInt = Integer.parseInt(bYear);_x000D_ int bMonthInt = Integer.parseInt(bMonth2);_x000D_ int bDagInt = Integer.parseInt(bDag);_x000D_ logger.debug("jaar: " + bYearInt);_x000D_ logger.debug("maand: " + bMonthInt);_x000D_ logger.debug("dag: " + bDagInt);_x000D_ _x000D_ if (bYearInt ==0 || bYearInt <1850) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd.");_x000D_ }_x000D_ if (bMonthInt >12) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ if (bDagInt >31) {_x000D_ throw new ArithmeticException("Geen valide geboortedatum ingevoerd."); _x000D_ }_x000D_ _x000D_ //als maand null is dan 1 juli invullen_x000D_ if (bMonthInt == 0) {_x000D_ bMonthInt = 1;_x000D_ bMonthInt = 7;}_x000D_ //als dag null is, dan waarde op 1 zetten en vervolgens naar laatste dag van de maand_x000D_ if (bDagInt == 00) {_x000D_ _x000D_ LocalDate noDay = LocalDate.of(bYearInt,bMonthInt,1);_x000D_ LocalDate end = noDay.withDayOfMonth(noDay.lengthOfMonth());_x000D_ int dayOfMonth = end.getDayOfMonth();_x000D_ bDagInt = dayOfMonth;_x000D_ }_x000D_ if (bMonthInt == 2 & bDagInt == 29) {_x000D_ bDagInt=28;_x000D_ }_x000D_ _x000D_ String resultString = "";_x000D_ _x000D_ //geboortedag bepalen_x000D_ LocalDate currentTime = LocalDate.now();_x000D_ LocalDate birthday = LocalDate.of(bYearInt,bMonthInt,bDagInt);_x000D_ logger.debug("Huidige datum: " + currentTime);_x000D_ logger.debug("Geboortedatum: " + birthday);_x000D_ _x000D_ _x000D_ //array maken met alle jaren erin _x000D_ int[] jaar = new int[] {12,16,18,21,65};_x000D_ for (int i=0; i<jaar.length; i++)_x000D_ {_x000D_ //door array lopen_x000D_ //in de array current date bepalen_x000D_ //jaren van currentdate afhalen_x000D_ LocalDate date1 = LocalDate.now().minusYears(jaar[i]);_x000D_ _x000D_ String resultValue;_x000D_ String resultLabel;_x000D_ //vergelijken geboortedatum en currentdate_x000D_ if(date1.isBefore(birthday)) {_x000D_ resultValue = "No";_x000D_ }_x000D_ else {_x000D_ resultValue = "Yes";_x000D_ _x000D_ }_x000D_ //string met<SUF> resultLabel = "\"" +"over" + jaar[i]; _x000D_ resultString = resultString + resultLabel + "\"" +":"+ "\"" + resultValue + "\"" + ",";_x000D_ }_x000D_ //resultString teruggeven_x000D_ resultString = "{" + resultString.substring(0, resultString.length()-1) +"}";_x000D_ resultString = "{"+ "\""+"ageLimits"+"\""+": " + resultString +"}";_x000D_ logger.debug("resultString: " + resultString);_x000D_ return resultString;_x000D_ _x000D_ }_x000D_ _x000D_ };_x000D_ _x000D_ _x000D_ _x000D_
True
1,812
31
2,014
33
1,987
30
2,004
33
2,509
34
false
false
false
false
false
true
790
66559_1
package com.example.jacco.tictactoe; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Switch; import android.widget.Toast; import java.util.Random; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { // variables Game game; int row; int column; String[] names = {"t1","t2","t3","t4","t5","t6","t7","t8","t9"}; int[] buttons = {R.id.t1, R.id.t2, R.id.t3, R.id.t4, R.id.t5, R.id.t6, R.id.t7, R.id.t8, R.id.t9}; int[][] coordinates = {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}}; boolean AIOn; int randTile; // saving state buttons @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet meer winnen na draaaien en X begint altijd na draaien Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } else { game = new Game(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("Game",game); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Game game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet meer winnen na draaaien en X begint altijd na draaien Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } public void tileClicked(View view) { // find clicked button int id = view.getId(); int length = buttons.length; for (int i=0; i<length; i++) { if (id == buttons[i]) { row = coordinates[i][0]; column = coordinates[i][1]; } } // find out what to draw Tile tile = game.draw(row, column); // print on board Button button = (Button) view; switch(tile) { case CROSS: button.setText("X"); break; case CIRCLE: button.setText("O"); break; case INVALID: // popup message from: // https://developer.android.com/guide/topics/ui/notifiers/toasts.html#Positioning Context context = getApplicationContext(); CharSequence text = "Invalid move!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); break; // check if AI has to play // if (AIOn && game.process() != GameState.PLAYER_ONE) { // // check if there's a good play // // if (game.prevent()<9) { // randTile = game.prevent(); // } else { // // find a random blank tile and find out what to draw // Tile tileTest; // do { // Random rand = new Random(); // randTile = rand.nextInt(9); // tileTest = game.test(coordinates[randTile][0], coordinates[randTile][1]); // } // while (tileTest == Tile.INVALID || row == coordinates[randTile][0] || column == coordinates[randTile][1]); // } // // game.draw(coordinates[randTile][0],coordinates[randTile][1]); // // // print on board // // Button button2 = findViewById(buttons[randTile]); // button2.setText("O"); // } } // find out who won and print message if (game.process() == GameState.DRAW) { Context context = getApplicationContext(); CharSequence text = "It's a draw! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_ONE) { Context context = getApplicationContext(); CharSequence text = "Player one wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_TWO) { Context context = getApplicationContext(); CharSequence text = "Player two wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } public void resetClicked(View view) { // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } public void switchCheck(View view) { Switch aSwitch = findViewById(R.id.switch1); if (aSwitch.isChecked()) { AIOn = true; // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } else { AIOn = false; } } }
JaccovanWijk/TicTacToe
app/src/main/java/com/example/jacco/tictactoe/MainActivity.java
1,795
// kan niet meer winnen na draaaien en X begint altijd na draaien
line_comment
nl
package com.example.jacco.tictactoe; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.Switch; import android.widget.Toast; import java.util.Random; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { // variables Game game; int row; int column; String[] names = {"t1","t2","t3","t4","t5","t6","t7","t8","t9"}; int[] buttons = {R.id.t1, R.id.t2, R.id.t3, R.id.t4, R.id.t5, R.id.t6, R.id.t7, R.id.t8, R.id.t9}; int[][] coordinates = {{0,0},{0,1},{0,2},{1,0},{1,1},{1,2},{2,0},{2,1},{2,2}}; boolean AIOn; int randTile; // saving state buttons @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet<SUF> Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } else { game = new Game(); } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("Game",game); } @Override public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Game game =(Game) savedInstanceState.getSerializable("Game"); for (int i=0; i<names.length; i++){ // kan niet meer winnen na draaaien en X begint altijd na draaien Tile tile = game.drawTile(i/3, i%3); Button button = findViewById(buttons[i]); if (tile == Tile.CROSS) { button.setText("X"); } else if (tile == Tile.CIRCLE) { button.setText("O"); } } } public void tileClicked(View view) { // find clicked button int id = view.getId(); int length = buttons.length; for (int i=0; i<length; i++) { if (id == buttons[i]) { row = coordinates[i][0]; column = coordinates[i][1]; } } // find out what to draw Tile tile = game.draw(row, column); // print on board Button button = (Button) view; switch(tile) { case CROSS: button.setText("X"); break; case CIRCLE: button.setText("O"); break; case INVALID: // popup message from: // https://developer.android.com/guide/topics/ui/notifiers/toasts.html#Positioning Context context = getApplicationContext(); CharSequence text = "Invalid move!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); break; // check if AI has to play // if (AIOn && game.process() != GameState.PLAYER_ONE) { // // check if there's a good play // // if (game.prevent()<9) { // randTile = game.prevent(); // } else { // // find a random blank tile and find out what to draw // Tile tileTest; // do { // Random rand = new Random(); // randTile = rand.nextInt(9); // tileTest = game.test(coordinates[randTile][0], coordinates[randTile][1]); // } // while (tileTest == Tile.INVALID || row == coordinates[randTile][0] || column == coordinates[randTile][1]); // } // // game.draw(coordinates[randTile][0],coordinates[randTile][1]); // // // print on board // // Button button2 = findViewById(buttons[randTile]); // button2.setText("O"); // } } // find out who won and print message if (game.process() == GameState.DRAW) { Context context = getApplicationContext(); CharSequence text = "It's a draw! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_ONE) { Context context = getApplicationContext(); CharSequence text = "Player one wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } else if (game.process() == GameState.PLAYER_TWO) { Context context = getApplicationContext(); CharSequence text = "Player two wins! Press new game"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } public void resetClicked(View view) { // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } public void switchCheck(View view) { Switch aSwitch = findViewById(R.id.switch1); if (aSwitch.isChecked()) { AIOn = true; // clear all buttons and start new game for (int i : buttons) { Button button = findViewById(i); button.setText(""); } game = new Game(); } else { AIOn = false; } } }
True
1,297
20
1,471
23
1,582
17
1,471
23
1,742
20
false
false
false
false
false
true
1,144
30920_1
package se.monstermannen.discordmonsterbot; import com.arsenarsen.lavaplayerbridge.PlayerManager; import com.arsenarsen.lavaplayerbridge.libraries.LibraryFactory; import com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException; import com.arsenarsen.lavaplayerbridge.player.Player; import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager; import se.monstermannen.discordmonsterbot.commands.Command; import se.monstermannen.discordmonsterbot.commands.CommandType; import se.monstermannen.discordmonsterbot.commands.admin.SetBotAvatarCommand; import se.monstermannen.discordmonsterbot.commands.admin.SetBotGameCommand; import se.monstermannen.discordmonsterbot.commands.admin.SetBotNameCommand; import se.monstermannen.discordmonsterbot.commands.admin.SetBotPrefixCommand; import se.monstermannen.discordmonsterbot.commands.general.*; import se.monstermannen.discordmonsterbot.commands.music.*; import se.monstermannen.discordmonsterbot.util.MonsterTimer; import se.monstermannen.discordmonsterbot.util.PropertyHandler; import sx.blah.discord.api.ClientBuilder; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.RateLimitException; import java.util.ArrayList; /** * Created by Viktor on 2017-01-12. * * main class */ public class DiscordMonsterBot { // default values public static String TOKEN = ""; // discord bot token public static String YT_APIKEY = ""; // youtube api key public static String PREFIX = "!"; // prefix for commands public static boolean LOOPPLAYLIST = false; // loop music players playlist // discord private static IDiscordClient client; private static MonsterTimer timer; private static PlayerManager manager; public static AddSongCommand addSong; // variables //public static Logger logger = LoggerFactory.getLogger(DiscordMonsterBot.class); private static ArrayList<Command> commands = new ArrayList<>(); public static int readMessages; public static int readCommands; private static long startTime; public static void main(String[] args){ try { DiscordMonsterBot bot = new DiscordMonsterBot(); DiscordMonsterBot.startTime = System.currentTimeMillis(); PropertyHandler.readProperties(); timer = new MonsterTimer(); client = new ClientBuilder().withToken(TOKEN).build(); // builds client manager = PlayerManager.getPlayerManager(LibraryFactory.getLibrary(client)); manager.getManager().registerSourceManager(new YoutubeAudioSourceManager()); // youtube client.getDispatcher().registerListener(new Events()); // add listener client.login(); // login :^) // logger test //BasicConfigurator.configure(); //logger.info("test log :D"); // general commands commands.add(new HelpCommand()); commands.add(new StatsCommand()); commands.add(new SayCommand()); commands.add(new VirusCommand()); commands.add(new FlipCommand()); commands.add(new UserInfoCommand()); commands.add(new WhoSpamsCommand()); commands.add(new ImdbCommand()); commands.add(new SwagCommand()); commands.add(new WarningCommand()); // music commands commands.add(new JoinCommand()); commands.add(new LeaveCommand()); commands.add(new AddSongCommand()); commands.add(new PlayCommand()); commands.add(new PauseCommand()); commands.add(new SkipCommand()); commands.add(new ClearCommand()); commands.add(new VolumeCommand()); commands.add(new SongCommand()); commands.add(new PlaylistCommand()); commands.add(new ShuffleCommand()); commands.add(new LoopCommand()); commands.add(new FwdCommand()); commands.add(new SavePlaylistCommand()); commands.add(new LoadPlaylistCommand()); // admin only commands (not listed when using help) commands.add(new SetBotGameCommand()); commands.add(new SetBotNameCommand()); commands.add(new SetBotAvatarCommand()); commands.add(new SetBotPrefixCommand()); addSong = new AddSongCommand(); // used by !play command } catch (DiscordException | RateLimitException | UnknownBindingException e) { e.printStackTrace(); } } // todo logger // todo fwd song // todo random song list? + random song add // todo rip (text on img) // todo warn user // todo aws amazon host? heroku? // help -admin commands +music guide // return time in seconds since program start public static long getUptime(){ return (System.currentTimeMillis() - startTime) / 1000; } public static int getReadmessages(){ return readMessages; } public static int getReadCommands(){ return readCommands; } public static void increaseReadMessages(){ readMessages++; } public static void increaseReadCommands(){ readCommands++; } // return commandlist public static ArrayList<Command> getCommands(){ return commands; } // return only commands of commandtype type public static ArrayList<Command> getCommandsByType(CommandType type){ ArrayList<Command> ret = new ArrayList<>(); for(Command cmd : commands){ if(cmd.getCommandType() == type){ ret.add(cmd); } } return ret; } // return lavaplayer public static Player getPlayer(IGuild guild){ return manager.getPlayer(guild.getID()); } }
MonsterMannen/DiscordMonsterBot
src/main/java/se/monstermannen/discordmonsterbot/DiscordMonsterBot.java
1,626
// discord bot token
line_comment
nl
package se.monstermannen.discordmonsterbot; import com.arsenarsen.lavaplayerbridge.PlayerManager; import com.arsenarsen.lavaplayerbridge.libraries.LibraryFactory; import com.arsenarsen.lavaplayerbridge.libraries.UnknownBindingException; import com.arsenarsen.lavaplayerbridge.player.Player; import com.sedmelluq.discord.lavaplayer.source.youtube.YoutubeAudioSourceManager; import se.monstermannen.discordmonsterbot.commands.Command; import se.monstermannen.discordmonsterbot.commands.CommandType; import se.monstermannen.discordmonsterbot.commands.admin.SetBotAvatarCommand; import se.monstermannen.discordmonsterbot.commands.admin.SetBotGameCommand; import se.monstermannen.discordmonsterbot.commands.admin.SetBotNameCommand; import se.monstermannen.discordmonsterbot.commands.admin.SetBotPrefixCommand; import se.monstermannen.discordmonsterbot.commands.general.*; import se.monstermannen.discordmonsterbot.commands.music.*; import se.monstermannen.discordmonsterbot.util.MonsterTimer; import se.monstermannen.discordmonsterbot.util.PropertyHandler; import sx.blah.discord.api.ClientBuilder; import sx.blah.discord.api.IDiscordClient; import sx.blah.discord.handle.obj.IGuild; import sx.blah.discord.util.DiscordException; import sx.blah.discord.util.RateLimitException; import java.util.ArrayList; /** * Created by Viktor on 2017-01-12. * * main class */ public class DiscordMonsterBot { // default values public static String TOKEN = ""; // discord bot<SUF> public static String YT_APIKEY = ""; // youtube api key public static String PREFIX = "!"; // prefix for commands public static boolean LOOPPLAYLIST = false; // loop music players playlist // discord private static IDiscordClient client; private static MonsterTimer timer; private static PlayerManager manager; public static AddSongCommand addSong; // variables //public static Logger logger = LoggerFactory.getLogger(DiscordMonsterBot.class); private static ArrayList<Command> commands = new ArrayList<>(); public static int readMessages; public static int readCommands; private static long startTime; public static void main(String[] args){ try { DiscordMonsterBot bot = new DiscordMonsterBot(); DiscordMonsterBot.startTime = System.currentTimeMillis(); PropertyHandler.readProperties(); timer = new MonsterTimer(); client = new ClientBuilder().withToken(TOKEN).build(); // builds client manager = PlayerManager.getPlayerManager(LibraryFactory.getLibrary(client)); manager.getManager().registerSourceManager(new YoutubeAudioSourceManager()); // youtube client.getDispatcher().registerListener(new Events()); // add listener client.login(); // login :^) // logger test //BasicConfigurator.configure(); //logger.info("test log :D"); // general commands commands.add(new HelpCommand()); commands.add(new StatsCommand()); commands.add(new SayCommand()); commands.add(new VirusCommand()); commands.add(new FlipCommand()); commands.add(new UserInfoCommand()); commands.add(new WhoSpamsCommand()); commands.add(new ImdbCommand()); commands.add(new SwagCommand()); commands.add(new WarningCommand()); // music commands commands.add(new JoinCommand()); commands.add(new LeaveCommand()); commands.add(new AddSongCommand()); commands.add(new PlayCommand()); commands.add(new PauseCommand()); commands.add(new SkipCommand()); commands.add(new ClearCommand()); commands.add(new VolumeCommand()); commands.add(new SongCommand()); commands.add(new PlaylistCommand()); commands.add(new ShuffleCommand()); commands.add(new LoopCommand()); commands.add(new FwdCommand()); commands.add(new SavePlaylistCommand()); commands.add(new LoadPlaylistCommand()); // admin only commands (not listed when using help) commands.add(new SetBotGameCommand()); commands.add(new SetBotNameCommand()); commands.add(new SetBotAvatarCommand()); commands.add(new SetBotPrefixCommand()); addSong = new AddSongCommand(); // used by !play command } catch (DiscordException | RateLimitException | UnknownBindingException e) { e.printStackTrace(); } } // todo logger // todo fwd song // todo random song list? + random song add // todo rip (text on img) // todo warn user // todo aws amazon host? heroku? // help -admin commands +music guide // return time in seconds since program start public static long getUptime(){ return (System.currentTimeMillis() - startTime) / 1000; } public static int getReadmessages(){ return readMessages; } public static int getReadCommands(){ return readCommands; } public static void increaseReadMessages(){ readMessages++; } public static void increaseReadCommands(){ readCommands++; } // return commandlist public static ArrayList<Command> getCommands(){ return commands; } // return only commands of commandtype type public static ArrayList<Command> getCommandsByType(CommandType type){ ArrayList<Command> ret = new ArrayList<>(); for(Command cmd : commands){ if(cmd.getCommandType() == type){ ret.add(cmd); } } return ret; } // return lavaplayer public static Player getPlayer(IGuild guild){ return manager.getPlayer(guild.getID()); } }
False
1,184
4
1,347
4
1,395
4
1,348
4
1,594
5
false
false
false
false
false
true
1,329
79590_1
/* * Copyright 2012 Stijn Seghers <stijn.seghers at ugent.be>. */ package bozels.units.factories.exception; /** * * @author Stijn Seghers <stijn.seghers at ugent.be> */ public class FactoryException extends Exception { protected FactoryException(String item) { super("Er werd geprobeerd " + item + " aan te maken."); } }
Procrat/bozels
src/bozels/units/factories/exception/FactoryException.java
110
/** * * @author Stijn Seghers <stijn.seghers at ugent.be> */
block_comment
nl
/* * Copyright 2012 Stijn Seghers <stijn.seghers at ugent.be>. */ package bozels.units.factories.exception; /** * * @author Stijn Seghers<SUF>*/ public class FactoryException extends Exception { protected FactoryException(String item) { super("Er werd geprobeerd " + item + " aan te maken."); } }
False
93
23
112
27
112
28
112
27
120
28
false
false
false
false
false
true
4,686
34051_3
package de.aitools.ie.uima.io; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * * An {@link InputStream} that can open {@link ClassLoader} resources, as well * as files. * * @author michael.voelske@uni-weimar.de * */ public class ResourceInputStream extends InputStream implements Closeable, AutoCloseable { private InputStream wrapped; /** * Creates an {@link InputStream} to the resource identified by the given * path, which can be either a {@link ClassLoader} system resource, or an * object on the local file system. * * @param resourcePath * a path to a {@link ClassLoader} resource with the lexicon * file, or a path on the local file system. If the parameter can * be interpreted as either, {@link ClassLoader} resources take * precedence * @throws FileNotFoundException */ public ResourceInputStream(String resourcePath) throws FileNotFoundException { wrapped = ClassLoader.getSystemResourceAsStream(resourcePath); if (wrapped == null) { String absolutePath = PathTools.getAbsolutePath(resourcePath); try { wrapped = new FileInputStream(absolutePath); } catch (Exception e) { throw new FileNotFoundException(String .format("Resource '%s' could not be located on the classpath or file system.", resourcePath)); } } } /** * @return * @throws IOException * @see java.io.InputStream#read() */ public int read() throws IOException { return wrapped.read(); } /** * @return * @see java.lang.Object#hashCode() */ public int hashCode() { return wrapped.hashCode(); } /** * @param b * @return * @throws IOException * @see java.io.InputStream#read(byte[]) */ public int read(byte[] b) throws IOException { return wrapped.read(b); } /** * @param obj * @return * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return wrapped.equals(obj); } /** * @param b * @param off * @param len * @return * @throws IOException * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte[] b, int off, int len) throws IOException { return wrapped.read(b, off, len); } /** * @param n * @return * @throws IOException * @see java.io.InputStream#skip(long) */ public long skip(long n) throws IOException { return wrapped.skip(n); } /** * @return * @see java.lang.Object#toString() */ public String toString() { return wrapped.toString(); } /** * @return * @throws IOException * @see java.io.InputStream#available() */ public int available() throws IOException { return wrapped.available(); } /** * @throws IOException * @see java.io.InputStream#close() */ public void close() throws IOException { wrapped.close(); } /** * @param readlimit * @see java.io.InputStream#mark(int) */ public void mark(int readlimit) { wrapped.mark(readlimit); } /** * @throws IOException * @see java.io.InputStream#reset() */ public void reset() throws IOException { wrapped.reset(); } /** * @return * @see java.io.InputStream#markSupported() */ public boolean markSupported() { return wrapped.markSupported(); } }
webis-de/argmining20-rhetorical-devices
src/de/aitools/ie/uima/io/ResourceInputStream.java
1,047
/** * @return * @see java.lang.Object#hashCode() */
block_comment
nl
package de.aitools.ie.uima.io; import java.io.Closeable; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * * An {@link InputStream} that can open {@link ClassLoader} resources, as well * as files. * * @author michael.voelske@uni-weimar.de * */ public class ResourceInputStream extends InputStream implements Closeable, AutoCloseable { private InputStream wrapped; /** * Creates an {@link InputStream} to the resource identified by the given * path, which can be either a {@link ClassLoader} system resource, or an * object on the local file system. * * @param resourcePath * a path to a {@link ClassLoader} resource with the lexicon * file, or a path on the local file system. If the parameter can * be interpreted as either, {@link ClassLoader} resources take * precedence * @throws FileNotFoundException */ public ResourceInputStream(String resourcePath) throws FileNotFoundException { wrapped = ClassLoader.getSystemResourceAsStream(resourcePath); if (wrapped == null) { String absolutePath = PathTools.getAbsolutePath(resourcePath); try { wrapped = new FileInputStream(absolutePath); } catch (Exception e) { throw new FileNotFoundException(String .format("Resource '%s' could not be located on the classpath or file system.", resourcePath)); } } } /** * @return * @throws IOException * @see java.io.InputStream#read() */ public int read() throws IOException { return wrapped.read(); } /** * @return <SUF>*/ public int hashCode() { return wrapped.hashCode(); } /** * @param b * @return * @throws IOException * @see java.io.InputStream#read(byte[]) */ public int read(byte[] b) throws IOException { return wrapped.read(b); } /** * @param obj * @return * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { return wrapped.equals(obj); } /** * @param b * @param off * @param len * @return * @throws IOException * @see java.io.InputStream#read(byte[], int, int) */ public int read(byte[] b, int off, int len) throws IOException { return wrapped.read(b, off, len); } /** * @param n * @return * @throws IOException * @see java.io.InputStream#skip(long) */ public long skip(long n) throws IOException { return wrapped.skip(n); } /** * @return * @see java.lang.Object#toString() */ public String toString() { return wrapped.toString(); } /** * @return * @throws IOException * @see java.io.InputStream#available() */ public int available() throws IOException { return wrapped.available(); } /** * @throws IOException * @see java.io.InputStream#close() */ public void close() throws IOException { wrapped.close(); } /** * @param readlimit * @see java.io.InputStream#mark(int) */ public void mark(int readlimit) { wrapped.mark(readlimit); } /** * @throws IOException * @see java.io.InputStream#reset() */ public void reset() throws IOException { wrapped.reset(); } /** * @return * @see java.io.InputStream#markSupported() */ public boolean markSupported() { return wrapped.markSupported(); } }
False
821
18
939
19
1,005
22
939
19
1,105
23
false
false
false
false
false
true
4,713
212230_2
/********************************************************************** * * Copyright (c) 2004 Olaf Willuhn * All rights reserved. * * This software is copyrighted work licensed under the terms of the * Jameica License. Please consult the file "LICENSE" for details. * **********************************************************************/ package de.willuhn.jameica.services; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import de.willuhn.boot.BootLoader; import de.willuhn.boot.Bootable; import de.willuhn.boot.SkipServiceException; import de.willuhn.jameica.security.JameicaHostnameVerifier; import de.willuhn.logging.Logger; /** * Initialisiert den Hostname-Verifier. */ public class HostnameVerifierService implements Bootable { /** * @see de.willuhn.boot.Bootable#depends() */ public Class[] depends() { return new Class[]{LogService.class, SecurityManagerService.class}; } /** * @see de.willuhn.boot.Bootable#init(de.willuhn.boot.BootLoader, de.willuhn.boot.Bootable) */ public void init(BootLoader loader, Bootable caller) throws SkipServiceException { HostnameVerifier parent = HttpsURLConnection.getDefaultHostnameVerifier(); Logger.info("applying jameica's hostname verifier"); HostnameVerifier verifier = new JameicaHostnameVerifier(parent); HttpsURLConnection.setDefaultHostnameVerifier(verifier); } /** * @see de.willuhn.boot.Bootable#shutdown() */ public void shutdown() { } } /********************************************************************** * $Log: HostnameVerifierService.java,v $ * Revision 1.1 2011/09/14 11:57:14 willuhn * @N HostnameVerifier in separate Klasse ausgelagert * @C Beim Erstellen eines neuen Master-Passwortes dieses sofort ververwenden und nicht nochmal mit getPasswort erfragen * **********************************************************************/
willuhn/jameica
src/de/willuhn/jameica/services/HostnameVerifierService.java
583
/** * @see de.willuhn.boot.Bootable#depends() */
block_comment
nl
/********************************************************************** * * Copyright (c) 2004 Olaf Willuhn * All rights reserved. * * This software is copyrighted work licensed under the terms of the * Jameica License. Please consult the file "LICENSE" for details. * **********************************************************************/ package de.willuhn.jameica.services; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import de.willuhn.boot.BootLoader; import de.willuhn.boot.Bootable; import de.willuhn.boot.SkipServiceException; import de.willuhn.jameica.security.JameicaHostnameVerifier; import de.willuhn.logging.Logger; /** * Initialisiert den Hostname-Verifier. */ public class HostnameVerifierService implements Bootable { /** * @see de.willuhn.boot.Bootable#depends() <SUF>*/ public Class[] depends() { return new Class[]{LogService.class, SecurityManagerService.class}; } /** * @see de.willuhn.boot.Bootable#init(de.willuhn.boot.BootLoader, de.willuhn.boot.Bootable) */ public void init(BootLoader loader, Bootable caller) throws SkipServiceException { HostnameVerifier parent = HttpsURLConnection.getDefaultHostnameVerifier(); Logger.info("applying jameica's hostname verifier"); HostnameVerifier verifier = new JameicaHostnameVerifier(parent); HttpsURLConnection.setDefaultHostnameVerifier(verifier); } /** * @see de.willuhn.boot.Bootable#shutdown() */ public void shutdown() { } } /********************************************************************** * $Log: HostnameVerifierService.java,v $ * Revision 1.1 2011/09/14 11:57:14 willuhn * @N HostnameVerifier in separate Klasse ausgelagert * @C Beim Erstellen eines neuen Master-Passwortes dieses sofort ververwenden und nicht nochmal mit getPasswort erfragen * **********************************************************************/
False
432
18
502
20
507
21
502
20
594
23
false
false
false
false
false
true
75
113361_5
package Main; import model.*; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import persistence.HibernateUtil; import persistence.TestData; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class Main { Scanner scanner = new Scanner(System.in); static Session session; static Transaction tx; public static void main(String[] args) throws ParseException { Main me = new Main(); me.askTestData(); //session and transaction placed here because if you do want testdata you will open 2 session which is not allowed by hibernate session = HibernateUtil.getSessionFactory().getCurrentSession(); tx = session.beginTransaction(); me.runConsole(); tx.commit(); } //ask for testdata private void askTestData() { System.out.println("Wilt u de testdata laden? (y/n)"); if (scanner.next().equals("y")) { TestData td = new TestData(); td.runTestData(); } } //start and run console app private void runConsole() throws ParseException { //init menu int menu = getOptionMainMenu(); while (menu != 5) { //print menu and returns the chosen option switch (menu) { case 1: //maak festivalganger System.out.println("Geef je naam:"); FestivalGanger buyer = new FestivalGanger(); buyer.setNaam(scanner.nextLine()); //getFestival Festival festival = getFestival(); //maak ticketverkoop TicketVerkoop sale = new TicketVerkoop(); sale.setFestivalGanger(buyer); sale.setTimestamp(new Date()); sale.setType(TicketVerkoop.VerkoopsType.WEB); sale.setFestival(festival); //get tickettypes System.out.println("Welk tickettype wil je?"); Query getticketTypes = session.createQuery("from TicketType where naam like :festivalname"); String festivalname = "%" + festival.getName() + "%"; getticketTypes.setString("festivalname", festivalname); List ticketTypes = getticketTypes.list(); //kies tickettype System.out.println("Kies je tickettype:"); for (int i = 0; i < ticketTypes.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((TicketType) ticketTypes.get(i)).getNaam()); } int typeChoice = scanner.nextInt(); scanner.nextLine(); TicketType tt = (TicketType) ticketTypes.get(typeChoice - 1); //kies aantal System.out.println("Hoeveel tickets wil je?:"); int aantalTickets = scanner.nextInt(); scanner.nextLine(); //maak tickets session.saveOrUpdate(buyer); session.saveOrUpdate(sale); for (int i = 0; i < aantalTickets; i++) { Ticket ticket = new Ticket(); ticket.setTicketType(tt); ticket.setTicketVerkoop(sale); session.saveOrUpdate(ticket); } System.out.print("Het totaal bedraagt:"); System.out.println("€" + (tt.getPrijs() * aantalTickets)); break; case 2: //getfestival Festival festival2 = getFestival(); //getZone Zone zone = getZone(festival2); //in out? System.out.println("In or out? (in = 1 / out = 0)"); int isInInt = scanner.nextInt(); scanner.nextLine(); Boolean isIn; //isIn = true if isInInt = 1 else false isIn = isInInt == 1; //poslbandID System.out.println("Geef de polsbandId:"); int polsbandID = scanner.nextInt(); scanner.nextLine(); //gentracking Tracking tracking = new Tracking(); tracking.setZone(zone); tracking.setTimestamp(new Date()); tracking.setDirection(isIn); tracking.setPolsbandId(polsbandID); session.saveOrUpdate(tracking); break; case 3: //get festivals Festival festival3 = getFestival(); //get zones Zone zone2 = getZone(festival3); //get date Query getDates = session.createQuery("select op.startTime from FestivalDag fd, Optreden op where fd.festival = :festival and op.festivalDag = fd"); getDates.setParameter("festival", festival3); List dates = getDates.list(); System.out.println("Kies de datum:"); for (int i = 0; i < dates.size(); i++) { System.out.print((i + 1) + ": "); System.out.println((dates.get(i)).toString()); } int datePick = scanner.nextInt(); scanner.nextLine(); //get optredens in zone where startdate < date > enddate Query getOptredens = session.createQuery("from Optreden op where :date > op.startTime and :date < op.endTime and op.zone = :zone"); //add 1 min Calendar cal = Calendar.getInstance(); cal.setTime((Date) dates.get(datePick - 1)); cal.add(Calendar.MINUTE, 1); getOptredens.setParameter("date", cal.getTime()); getOptredens.setParameter("zone", zone2); List optredens = getOptredens.list(); //output System.out.println(""); System.out.println("Optreden: "); for (Object o : optredens) { System.out.println(((Optreden) o).getArtiest().getNaam()); } break; case 4: //get artiests Query getArtiests = session.createQuery("from Artiest"); List artiests = getArtiests.list(); System.out.println("Kies je artiest"); for (int i = 0; i < artiests.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((Artiest) artiests.get(i)).getNaam()); } int artiestPick = scanner.nextInt(); scanner.nextLine(); //get dates SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy"); System.out.println("Geef datum 1 (mm/dd/yyyy):"); String date1 = scanner.next(); System.out.println("Geeft datum 2 (mm/dd/yyyy)"); String date2 = scanner.next(); Date d1 = df.parse(date1.trim()); Date d2 = df.parse(date2.trim()); //get festivals Query getFestivalDaysFromArtiest = session.createQuery("select o.festivalDag from Optreden o where o.artiest = :artiest "); getFestivalDaysFromArtiest.setParameter("artiest", artiests.get(artiestPick - 1)); List festivaldays = getFestivalDaysFromArtiest.list(); Set<Festival> setFestival = new HashSet<>(); for (Object festivalday1 : festivaldays) { FestivalDag festivalday = (FestivalDag) festivalday1; Query getFestivals = session.createQuery("select fd.festival from FestivalDag fd, Optreden o where fd = :festivaldag AND fd.date BETWEEN :date1 AND :date2"); getFestivals.setParameter("festivaldag", festivalday); getFestivals.setDate("date1", d1); getFestivals.setDate("date2", d2); setFestival.addAll(getFestivals.list()); } System.out.println("Festivals: "); for (Festival f : setFestival) { System.out.println(f.getName()); } break; } //gives the menu again menu = getOptionMainMenu(); } } private int getOptionMainMenu() { System.out.println(""); System.out.println("Kies welke opdracht je wilt uitvoeren:"); //options System.out.println("1: Registratie van een verkoop"); System.out.println("2: Opslaan passage"); System.out.println("3: Zoeken otreden"); System.out.println("4: Zoeken festival"); System.out.println("5: Stoppen"); int result = scanner.nextInt(); scanner.nextLine(); return result; } private Festival getFestival() { //get festivals Query getFestivals = session.createQuery("from Festival"); List festivals = getFestivals.list(); //kies festival System.out.println("Kies je festival:"); for (int i = 0; i < festivals.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((Festival) festivals.get(i)).getName()); } int festivalChoice = scanner.nextInt(); scanner.nextLine(); return (Festival) festivals.get(festivalChoice - 1); } private Zone getZone(Festival festival) { //getzones Query getZones = session.createQuery("from Zone zone where zone.festival = :festival and zone.naam like '%Stage%' "); getZones.setParameter("festival", festival); List zones = getZones.list(); //select zone System.out.println("Welke zone?"); for (int i = 0; i < zones.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((Zone) zones.get(i)).getNaam()); } int zone = scanner.nextInt(); scanner.nextLine(); return (Zone) zones.get(zone - 1); } }
AdriVanHoudt/D-M-Project
Project Deel 1/src/Main/Main.java
2,899
//get optredens in zone where startdate < date > enddate
line_comment
nl
package Main; import model.*; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import persistence.HibernateUtil; import persistence.TestData; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class Main { Scanner scanner = new Scanner(System.in); static Session session; static Transaction tx; public static void main(String[] args) throws ParseException { Main me = new Main(); me.askTestData(); //session and transaction placed here because if you do want testdata you will open 2 session which is not allowed by hibernate session = HibernateUtil.getSessionFactory().getCurrentSession(); tx = session.beginTransaction(); me.runConsole(); tx.commit(); } //ask for testdata private void askTestData() { System.out.println("Wilt u de testdata laden? (y/n)"); if (scanner.next().equals("y")) { TestData td = new TestData(); td.runTestData(); } } //start and run console app private void runConsole() throws ParseException { //init menu int menu = getOptionMainMenu(); while (menu != 5) { //print menu and returns the chosen option switch (menu) { case 1: //maak festivalganger System.out.println("Geef je naam:"); FestivalGanger buyer = new FestivalGanger(); buyer.setNaam(scanner.nextLine()); //getFestival Festival festival = getFestival(); //maak ticketverkoop TicketVerkoop sale = new TicketVerkoop(); sale.setFestivalGanger(buyer); sale.setTimestamp(new Date()); sale.setType(TicketVerkoop.VerkoopsType.WEB); sale.setFestival(festival); //get tickettypes System.out.println("Welk tickettype wil je?"); Query getticketTypes = session.createQuery("from TicketType where naam like :festivalname"); String festivalname = "%" + festival.getName() + "%"; getticketTypes.setString("festivalname", festivalname); List ticketTypes = getticketTypes.list(); //kies tickettype System.out.println("Kies je tickettype:"); for (int i = 0; i < ticketTypes.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((TicketType) ticketTypes.get(i)).getNaam()); } int typeChoice = scanner.nextInt(); scanner.nextLine(); TicketType tt = (TicketType) ticketTypes.get(typeChoice - 1); //kies aantal System.out.println("Hoeveel tickets wil je?:"); int aantalTickets = scanner.nextInt(); scanner.nextLine(); //maak tickets session.saveOrUpdate(buyer); session.saveOrUpdate(sale); for (int i = 0; i < aantalTickets; i++) { Ticket ticket = new Ticket(); ticket.setTicketType(tt); ticket.setTicketVerkoop(sale); session.saveOrUpdate(ticket); } System.out.print("Het totaal bedraagt:"); System.out.println("€" + (tt.getPrijs() * aantalTickets)); break; case 2: //getfestival Festival festival2 = getFestival(); //getZone Zone zone = getZone(festival2); //in out? System.out.println("In or out? (in = 1 / out = 0)"); int isInInt = scanner.nextInt(); scanner.nextLine(); Boolean isIn; //isIn = true if isInInt = 1 else false isIn = isInInt == 1; //poslbandID System.out.println("Geef de polsbandId:"); int polsbandID = scanner.nextInt(); scanner.nextLine(); //gentracking Tracking tracking = new Tracking(); tracking.setZone(zone); tracking.setTimestamp(new Date()); tracking.setDirection(isIn); tracking.setPolsbandId(polsbandID); session.saveOrUpdate(tracking); break; case 3: //get festivals Festival festival3 = getFestival(); //get zones Zone zone2 = getZone(festival3); //get date Query getDates = session.createQuery("select op.startTime from FestivalDag fd, Optreden op where fd.festival = :festival and op.festivalDag = fd"); getDates.setParameter("festival", festival3); List dates = getDates.list(); System.out.println("Kies de datum:"); for (int i = 0; i < dates.size(); i++) { System.out.print((i + 1) + ": "); System.out.println((dates.get(i)).toString()); } int datePick = scanner.nextInt(); scanner.nextLine(); //get optredens<SUF> Query getOptredens = session.createQuery("from Optreden op where :date > op.startTime and :date < op.endTime and op.zone = :zone"); //add 1 min Calendar cal = Calendar.getInstance(); cal.setTime((Date) dates.get(datePick - 1)); cal.add(Calendar.MINUTE, 1); getOptredens.setParameter("date", cal.getTime()); getOptredens.setParameter("zone", zone2); List optredens = getOptredens.list(); //output System.out.println(""); System.out.println("Optreden: "); for (Object o : optredens) { System.out.println(((Optreden) o).getArtiest().getNaam()); } break; case 4: //get artiests Query getArtiests = session.createQuery("from Artiest"); List artiests = getArtiests.list(); System.out.println("Kies je artiest"); for (int i = 0; i < artiests.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((Artiest) artiests.get(i)).getNaam()); } int artiestPick = scanner.nextInt(); scanner.nextLine(); //get dates SimpleDateFormat df = new SimpleDateFormat("mm/dd/yyyy"); System.out.println("Geef datum 1 (mm/dd/yyyy):"); String date1 = scanner.next(); System.out.println("Geeft datum 2 (mm/dd/yyyy)"); String date2 = scanner.next(); Date d1 = df.parse(date1.trim()); Date d2 = df.parse(date2.trim()); //get festivals Query getFestivalDaysFromArtiest = session.createQuery("select o.festivalDag from Optreden o where o.artiest = :artiest "); getFestivalDaysFromArtiest.setParameter("artiest", artiests.get(artiestPick - 1)); List festivaldays = getFestivalDaysFromArtiest.list(); Set<Festival> setFestival = new HashSet<>(); for (Object festivalday1 : festivaldays) { FestivalDag festivalday = (FestivalDag) festivalday1; Query getFestivals = session.createQuery("select fd.festival from FestivalDag fd, Optreden o where fd = :festivaldag AND fd.date BETWEEN :date1 AND :date2"); getFestivals.setParameter("festivaldag", festivalday); getFestivals.setDate("date1", d1); getFestivals.setDate("date2", d2); setFestival.addAll(getFestivals.list()); } System.out.println("Festivals: "); for (Festival f : setFestival) { System.out.println(f.getName()); } break; } //gives the menu again menu = getOptionMainMenu(); } } private int getOptionMainMenu() { System.out.println(""); System.out.println("Kies welke opdracht je wilt uitvoeren:"); //options System.out.println("1: Registratie van een verkoop"); System.out.println("2: Opslaan passage"); System.out.println("3: Zoeken otreden"); System.out.println("4: Zoeken festival"); System.out.println("5: Stoppen"); int result = scanner.nextInt(); scanner.nextLine(); return result; } private Festival getFestival() { //get festivals Query getFestivals = session.createQuery("from Festival"); List festivals = getFestivals.list(); //kies festival System.out.println("Kies je festival:"); for (int i = 0; i < festivals.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((Festival) festivals.get(i)).getName()); } int festivalChoice = scanner.nextInt(); scanner.nextLine(); return (Festival) festivals.get(festivalChoice - 1); } private Zone getZone(Festival festival) { //getzones Query getZones = session.createQuery("from Zone zone where zone.festival = :festival and zone.naam like '%Stage%' "); getZones.setParameter("festival", festival); List zones = getZones.list(); //select zone System.out.println("Welke zone?"); for (int i = 0; i < zones.size(); i++) { System.out.print((i + 1) + ": "); System.out.println(((Zone) zones.get(i)).getNaam()); } int zone = scanner.nextInt(); scanner.nextLine(); return (Zone) zones.get(zone - 1); } }
False
2,080
16
2,385
16
2,400
15
2,385
16
2,900
16
false
false
false
false
false
true
4,526
130365_1
package nl.thermans.whereis.auth; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import jakarta.servlet.*; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nl.thermans.whereis.user.Account; import nl.thermans.whereis.user.AccountRepository; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static nl.thermans.whereis.auth.AuthConstants.*; // based on https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/ public class AuthenticationFilter extends BasicAuthenticationFilter { private final AccountRepository accountRepository; public AuthenticationFilter(AuthenticationManager authenticationManager, AccountRepository accountRepository) { super(authenticationManager); this.accountRepository = accountRepository; } @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { String header = req.getHeader(HEADER_STRING); if (header == null || !header.startsWith(TOKEN_PREFIX)) { chain.doFilter(req, res); return; } UsernamePasswordAuthenticationToken authentication = getAuthentication(header); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(req, res); } private UsernamePasswordAuthenticationToken getAuthentication(String tokenWithPrefix) { // TODO: nadenken over token expiry enzo. Dus exceptions afvangen String tokenString = tokenWithPrefix.replace(TOKEN_PREFIX, ""); Token token = new Token(tokenString); String email = token.getEmail(); if (email == null) { return null; } Optional<Account> account = accountRepository.findByEmail(email); return account.map(a -> new UsernamePasswordAuthenticationToken(a, null, a.getAuthorities())) .orElseThrow(); } }
timohermans/whereis
api/src/main/java/nl/thermans/whereis/auth/AuthenticationFilter.java
650
// TODO: nadenken over token expiry enzo. Dus exceptions afvangen
line_comment
nl
package nl.thermans.whereis.auth; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import jakarta.servlet.*; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import nl.thermans.whereis.user.Account; import nl.thermans.whereis.user.AccountRepository; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static nl.thermans.whereis.auth.AuthConstants.*; // based on https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/ public class AuthenticationFilter extends BasicAuthenticationFilter { private final AccountRepository accountRepository; public AuthenticationFilter(AuthenticationManager authenticationManager, AccountRepository accountRepository) { super(authenticationManager); this.accountRepository = accountRepository; } @Override protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException { String header = req.getHeader(HEADER_STRING); if (header == null || !header.startsWith(TOKEN_PREFIX)) { chain.doFilter(req, res); return; } UsernamePasswordAuthenticationToken authentication = getAuthentication(header); SecurityContextHolder.getContext().setAuthentication(authentication); chain.doFilter(req, res); } private UsernamePasswordAuthenticationToken getAuthentication(String tokenWithPrefix) { // TODO: nadenken<SUF> String tokenString = tokenWithPrefix.replace(TOKEN_PREFIX, ""); Token token = new Token(tokenString); String email = token.getEmail(); if (email == null) { return null; } Optional<Account> account = accountRepository.findByEmail(email); return account.map(a -> new UsernamePasswordAuthenticationToken(a, null, a.getAuthorities())) .orElseThrow(); } }
False
433
18
548
19
564
15
548
19
627
19
false
false
false
false
false
true
2,123
98521_15
/** * Appia: Group communication and protocol composition framework library * Copyright 2006 University of Lisbon * * 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. * * Initial developer(s): Alexandre Pinto and Hugo Miranda. * Contributor(s): See Appia web page for a list of contributors. */ /* * Created on 27-Jan-2005 * */ package net.sf.appia.protocols.group.vsyncmultiplexer; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.sf.appia.core.AppiaEventException; import net.sf.appia.core.Channel; import net.sf.appia.core.Direction; import net.sf.appia.core.Event; import net.sf.appia.core.Layer; import net.sf.appia.core.Session; import net.sf.appia.core.events.channel.ChannelClose; import net.sf.appia.core.events.channel.ChannelInit; import net.sf.appia.core.events.channel.EchoEvent; import net.sf.appia.protocols.group.ViewState; import net.sf.appia.protocols.group.events.GroupSendableEvent; import net.sf.appia.protocols.group.intra.View; import net.sf.appia.protocols.group.sync.BlockOk; import org.apache.log4j.Logger; /** * @author nunomrc * */ public class VSyncMultiplexerSession extends Session { private static Logger log = Logger.getLogger(VSyncMultiplexerSession.class); private HashMap<Channel,Object> channels; private int blockOkCounter; private ViewState vs = null; private List<GroupSendableEvent> pendingEvents = null; /** * @param layer */ public VSyncMultiplexerSession(Layer layer) { super(layer); channels = new HashMap<Channel, Object>(); blockOkCounter = 0; pendingEvents = new LinkedList<GroupSendableEvent>(); } public void handle(Event e){ if(e instanceof GroupSendableEvent) handleGroupSendable((GroupSendableEvent)e); else if(e instanceof EchoEvent) handleEchoEvent((EchoEvent)e); else if (e instanceof View) handleView((View)e); else if(e instanceof BlockOk) handleBlockOk((BlockOk)e); else if (e instanceof ChannelInit) handleChannelInit((ChannelInit)e); else if (e instanceof ChannelClose) handleChannelClose((ChannelClose)e); else try { e.go(); } catch (AppiaEventException e1) { e1.printStackTrace(); } } /** * @param close */ private void handleChannelClose(ChannelClose close) { channels.put(close.getChannel(),null); try { close.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } /** * @param init */ private void handleChannelInit(ChannelInit init) { channels.put(init.getChannel(),null); try { init.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void handleGroupSendable(GroupSendableEvent ev){ // if(ev instanceof AckViewEvent && ev.getDir() == Direction.UP){ // System.out.println("Multiplexer: received event: "+ev+" FROM "+ev.orig); // System.out.println("ACK: "+ev.getChannel().getChannelID()+" "+ev.view_id); // } if(ev.getDir() == Direction.UP && (vs == null || !vs.id.equals(ev.view_id))){ // System.out.println("Multiplexer: holding event "+ev); pendingEvents.add(ev); } else try { ev.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } /** * @param ok */ private void handleBlockOk(BlockOk ok) { log.debug("Collecting blockok events :: counter = "+blockOkCounter); if((--blockOkCounter) == 0){ try { log.debug("Delivering blockok on channel: "+ok.getChannel().getChannelID()); ok.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } } /** * @param view */ private void handleView(View view) { log.debug("Replicating view to all channels view "+view.view_id+" with size "+view.vs.addresses.length); // System.out.println("Multiplexer: Replicating view to all channels view "+view.view_id+" with size "+view.vs.addresses.length); view.vs.version="MULTI"; vs = view.vs; Iterator<Channel> it = channels.keySet().iterator(); for ( ; it.hasNext() ; ){ Channel c = it.next(); if( ! c.equals(view.getChannel())){ try { // System.out.println("Multiplexer: sending to "+c.getChannelID()); View copy = new View(view.vs, view.ls, c, view.getDir(), this); copy.setPriority(copy.getPriority()+1); copy.go(); } catch (AppiaEventException e2) { e2.printStackTrace(); } } } try { // System.out.println("Multiplexer: sending to "+view.getChannel().getChannelID()); view.go(); } catch (AppiaEventException e1) { e1.printStackTrace(); } // dump pending events if(!pendingEvents.isEmpty()){ Iterator<GroupSendableEvent> eventIt = pendingEvents.iterator(); while(eventIt.hasNext()){ GroupSendableEvent ev = eventIt.next(); if(ev.view_id.equals(vs.id)){ eventIt.remove(); try { ev.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } else break; } } } /** * @param event */ private void handleEchoEvent(EchoEvent echo) { if(echo.getEvent() instanceof BlockOk){ log.debug("Replicating EchoEvent to all channels. Echo received on Channel: "+echo.getChannel().getChannelID()); blockOkCounter=0; BlockOk blockok=(BlockOk)echo.getEvent(); Iterator<Channel> it = channels.keySet().iterator(); for ( ; it.hasNext() ; ){ Channel c = it.next(); if( ! c.equals(echo.getChannel())){ try { EchoEvent copy = new EchoEvent(new BlockOk(blockok.group,blockok.view_id), c, echo.getDir(), this); copy.go(); blockOkCounter++; } catch (AppiaEventException e2) { e2.printStackTrace(); } } } try { echo.go(); blockOkCounter++; } catch (AppiaEventException e1) { e1.printStackTrace(); } } else { try { echo.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } } }
archie/appia-byzantine
src/groupcomm/net/sf/appia/protocols/group/vsyncmultiplexer/VSyncMultiplexerSession.java
2,263
// dump pending events
line_comment
nl
/** * Appia: Group communication and protocol composition framework library * Copyright 2006 University of Lisbon * * 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. * * Initial developer(s): Alexandre Pinto and Hugo Miranda. * Contributor(s): See Appia web page for a list of contributors. */ /* * Created on 27-Jan-2005 * */ package net.sf.appia.protocols.group.vsyncmultiplexer; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import net.sf.appia.core.AppiaEventException; import net.sf.appia.core.Channel; import net.sf.appia.core.Direction; import net.sf.appia.core.Event; import net.sf.appia.core.Layer; import net.sf.appia.core.Session; import net.sf.appia.core.events.channel.ChannelClose; import net.sf.appia.core.events.channel.ChannelInit; import net.sf.appia.core.events.channel.EchoEvent; import net.sf.appia.protocols.group.ViewState; import net.sf.appia.protocols.group.events.GroupSendableEvent; import net.sf.appia.protocols.group.intra.View; import net.sf.appia.protocols.group.sync.BlockOk; import org.apache.log4j.Logger; /** * @author nunomrc * */ public class VSyncMultiplexerSession extends Session { private static Logger log = Logger.getLogger(VSyncMultiplexerSession.class); private HashMap<Channel,Object> channels; private int blockOkCounter; private ViewState vs = null; private List<GroupSendableEvent> pendingEvents = null; /** * @param layer */ public VSyncMultiplexerSession(Layer layer) { super(layer); channels = new HashMap<Channel, Object>(); blockOkCounter = 0; pendingEvents = new LinkedList<GroupSendableEvent>(); } public void handle(Event e){ if(e instanceof GroupSendableEvent) handleGroupSendable((GroupSendableEvent)e); else if(e instanceof EchoEvent) handleEchoEvent((EchoEvent)e); else if (e instanceof View) handleView((View)e); else if(e instanceof BlockOk) handleBlockOk((BlockOk)e); else if (e instanceof ChannelInit) handleChannelInit((ChannelInit)e); else if (e instanceof ChannelClose) handleChannelClose((ChannelClose)e); else try { e.go(); } catch (AppiaEventException e1) { e1.printStackTrace(); } } /** * @param close */ private void handleChannelClose(ChannelClose close) { channels.put(close.getChannel(),null); try { close.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } /** * @param init */ private void handleChannelInit(ChannelInit init) { channels.put(init.getChannel(),null); try { init.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } private void handleGroupSendable(GroupSendableEvent ev){ // if(ev instanceof AckViewEvent && ev.getDir() == Direction.UP){ // System.out.println("Multiplexer: received event: "+ev+" FROM "+ev.orig); // System.out.println("ACK: "+ev.getChannel().getChannelID()+" "+ev.view_id); // } if(ev.getDir() == Direction.UP && (vs == null || !vs.id.equals(ev.view_id))){ // System.out.println("Multiplexer: holding event "+ev); pendingEvents.add(ev); } else try { ev.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } /** * @param ok */ private void handleBlockOk(BlockOk ok) { log.debug("Collecting blockok events :: counter = "+blockOkCounter); if((--blockOkCounter) == 0){ try { log.debug("Delivering blockok on channel: "+ok.getChannel().getChannelID()); ok.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } } /** * @param view */ private void handleView(View view) { log.debug("Replicating view to all channels view "+view.view_id+" with size "+view.vs.addresses.length); // System.out.println("Multiplexer: Replicating view to all channels view "+view.view_id+" with size "+view.vs.addresses.length); view.vs.version="MULTI"; vs = view.vs; Iterator<Channel> it = channels.keySet().iterator(); for ( ; it.hasNext() ; ){ Channel c = it.next(); if( ! c.equals(view.getChannel())){ try { // System.out.println("Multiplexer: sending to "+c.getChannelID()); View copy = new View(view.vs, view.ls, c, view.getDir(), this); copy.setPriority(copy.getPriority()+1); copy.go(); } catch (AppiaEventException e2) { e2.printStackTrace(); } } } try { // System.out.println("Multiplexer: sending to "+view.getChannel().getChannelID()); view.go(); } catch (AppiaEventException e1) { e1.printStackTrace(); } // dump pending<SUF> if(!pendingEvents.isEmpty()){ Iterator<GroupSendableEvent> eventIt = pendingEvents.iterator(); while(eventIt.hasNext()){ GroupSendableEvent ev = eventIt.next(); if(ev.view_id.equals(vs.id)){ eventIt.remove(); try { ev.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } else break; } } } /** * @param event */ private void handleEchoEvent(EchoEvent echo) { if(echo.getEvent() instanceof BlockOk){ log.debug("Replicating EchoEvent to all channels. Echo received on Channel: "+echo.getChannel().getChannelID()); blockOkCounter=0; BlockOk blockok=(BlockOk)echo.getEvent(); Iterator<Channel> it = channels.keySet().iterator(); for ( ; it.hasNext() ; ){ Channel c = it.next(); if( ! c.equals(echo.getChannel())){ try { EchoEvent copy = new EchoEvent(new BlockOk(blockok.group,blockok.view_id), c, echo.getDir(), this); copy.go(); blockOkCounter++; } catch (AppiaEventException e2) { e2.printStackTrace(); } } } try { echo.go(); blockOkCounter++; } catch (AppiaEventException e1) { e1.printStackTrace(); } } else { try { echo.go(); } catch (AppiaEventException e) { e.printStackTrace(); } } } }
False
1,588
4
1,909
4
2,110
4
1,909
4
2,272
4
false
false
false
false
false
true
4,015
98487_1
package nl.pietervanberkel.servlets; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import nl.pietervanberkel.model.Model; import nl.pietervanberkel.model.User; import nl.pietervanberkel.util.UserCookie; /** * Servlet implementation class Login */ @WebServlet(description = "controls the login proces", urlPatterns = { "/Login" }) public class Login extends HttpServlet { private static final long serialVersionUID = 1L; private Model model; /** * @see HttpServlet#HttpServlet() */ public Login() { super(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); model = (Model) config.getServletContext().getAttribute("Model"); // hoeven we hier maar een keer het model op te halen } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession s = request.getSession(false); if(s != null){ System.out.println("authorized"); String name = (String) s.getAttribute("name"); if(model.getUser(name).getRol() == User.HUURDER){ request.getServletContext().getRequestDispatcher("/WEB-INF/huurder.html").forward(request,response); }else if(model.getUser(name).getRol() == User.VERHUURDER){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowRoomsServlet"); }else if(model.getUser(name).getRol() == User.ADMIN){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowPersonServlet"); } }else{ System.out.println("not authorized"); response.sendRedirect("/Webtechnologie_Opdracht1/login.html"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("Login_Name"); String password = request.getParameter("Password"); System.out.println(name); System.out.println(password); User user = model.getUser(name); if(user != null){ if(user.getPassword().equals(password)){ HttpSession session = request.getSession(); if(!session.isNew()){ session.invalidate(); session = request.getSession(); } Cookie[] cookies = request.getCookies(); if (cookies != null){ if (containsCookie(cookies, name)){ for (Cookie cookie : cookies){ if (cookie.getName().equals(user.getName())){ cookie.setValue(null); } } System.out.println("old cookie: " + request.getCookies().length); } else { UserCookie cookie = new UserCookie(user.getName(),null); System.out.println("adding cookie with name: " + user.getName()); cookie.setMaxAge(99999); response.addCookie(cookie); System.out.println("new cookie: " + request.getCookies().length); } } session.setAttribute("name", name); if(user.getRol() == User.ADMIN){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowPersonServlet"); }else if(user.getRol() == User.HUURDER){ request.getServletContext().getRequestDispatcher("/WEB-INF/huurder.html").forward(request,response); }else if(user.getRol() == User.VERHUURDER){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowRoomsServlet"); } }else{ request.getServletContext().getRequestDispatcher("/WEB-INF/fouteInlog.html").forward(request,response); } }else{ request.getServletContext().getRequestDispatcher("/WEB-INF/fouteInlog.html").forward(request,response); } System.out.println(model == null); System.out.println(model.getUsers()); } private boolean containsCookie(Cookie[] cookies,String name){ for (Cookie cookie : cookies){ if (cookie.getName().equals(name)){ return true; } } return false; } }
pokyno/Webtechnologie
Webtechnologie_Opdracht1/src/nl/pietervanberkel/servlets/Login.java
1,380
/** * @see HttpServlet#HttpServlet() */
block_comment
nl
package nl.pietervanberkel.servlets; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import nl.pietervanberkel.model.Model; import nl.pietervanberkel.model.User; import nl.pietervanberkel.util.UserCookie; /** * Servlet implementation class Login */ @WebServlet(description = "controls the login proces", urlPatterns = { "/Login" }) public class Login extends HttpServlet { private static final long serialVersionUID = 1L; private Model model; /** * @see HttpServlet#HttpServlet() <SUF>*/ public Login() { super(); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); model = (Model) config.getServletContext().getAttribute("Model"); // hoeven we hier maar een keer het model op te halen } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession s = request.getSession(false); if(s != null){ System.out.println("authorized"); String name = (String) s.getAttribute("name"); if(model.getUser(name).getRol() == User.HUURDER){ request.getServletContext().getRequestDispatcher("/WEB-INF/huurder.html").forward(request,response); }else if(model.getUser(name).getRol() == User.VERHUURDER){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowRoomsServlet"); }else if(model.getUser(name).getRol() == User.ADMIN){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowPersonServlet"); } }else{ System.out.println("not authorized"); response.sendRedirect("/Webtechnologie_Opdracht1/login.html"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("Login_Name"); String password = request.getParameter("Password"); System.out.println(name); System.out.println(password); User user = model.getUser(name); if(user != null){ if(user.getPassword().equals(password)){ HttpSession session = request.getSession(); if(!session.isNew()){ session.invalidate(); session = request.getSession(); } Cookie[] cookies = request.getCookies(); if (cookies != null){ if (containsCookie(cookies, name)){ for (Cookie cookie : cookies){ if (cookie.getName().equals(user.getName())){ cookie.setValue(null); } } System.out.println("old cookie: " + request.getCookies().length); } else { UserCookie cookie = new UserCookie(user.getName(),null); System.out.println("adding cookie with name: " + user.getName()); cookie.setMaxAge(99999); response.addCookie(cookie); System.out.println("new cookie: " + request.getCookies().length); } } session.setAttribute("name", name); if(user.getRol() == User.ADMIN){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowPersonServlet"); }else if(user.getRol() == User.HUURDER){ request.getServletContext().getRequestDispatcher("/WEB-INF/huurder.html").forward(request,response); }else if(user.getRol() == User.VERHUURDER){ response.sendRedirect("/Webtechnologie_Opdracht1/ShowRoomsServlet"); } }else{ request.getServletContext().getRequestDispatcher("/WEB-INF/fouteInlog.html").forward(request,response); } }else{ request.getServletContext().getRequestDispatcher("/WEB-INF/fouteInlog.html").forward(request,response); } System.out.println(model == null); System.out.println(model.getUsers()); } private boolean containsCookie(Cookie[] cookies,String name){ for (Cookie cookie : cookies){ if (cookie.getName().equals(name)){ return true; } } return false; } }
False
917
12
1,159
11
1,174
13
1,159
11
1,503
15
false
false
false
false
false
true
2,961
19558_0
package nl.novi.javaprogrammeren; import nl.novi.javaprogrammeren.overerving.Rocket; public class Main { /* Bekijk onderstaande code. Er zijn twee klasse, twee objecten. FalconRocket extends Rocket. Deze opdracht bestaat uit twee elementen. Het eerste element is om te oefenen. Het tweede element is een uitdagende opdracht. Element 1: De FalconRocket heeft reserve brandstof (extraFuel). Wanneer de raket niet genoeg fuel lijkt te hebben, moet er gekeken worden of er genoeg fuel is in extraFuel om het tekort op te vangen. Als dat zo is, moet er alsnog `true` geretourneerd worden. Element 2 (Uitdaging): Nadat er extra fuel gebruikt is, moet deze natuurlijk ook verminderd worden. Voeg dit toe aan de code. */ public static void main(String[] args) { Rocket genericRocket = new Rocket(100); genericRocket.fly(10); System.out.println(genericRocket.toString()); } }
hogeschoolnovi/SD-BE-JP-Overerving-01c
src/nl/novi/javaprogrammeren/Main.java
305
/* Bekijk onderstaande code. Er zijn twee klasse, twee objecten. FalconRocket extends Rocket. Deze opdracht bestaat uit twee elementen. Het eerste element is om te oefenen. Het tweede element is een uitdagende opdracht. Element 1: De FalconRocket heeft reserve brandstof (extraFuel). Wanneer de raket niet genoeg fuel lijkt te hebben, moet er gekeken worden of er genoeg fuel is in extraFuel om het tekort op te vangen. Als dat zo is, moet er alsnog `true` geretourneerd worden. Element 2 (Uitdaging): Nadat er extra fuel gebruikt is, moet deze natuurlijk ook verminderd worden. Voeg dit toe aan de code. */
block_comment
nl
package nl.novi.javaprogrammeren; import nl.novi.javaprogrammeren.overerving.Rocket; public class Main { /* Bekijk onderstaande code.<SUF>*/ public static void main(String[] args) { Rocket genericRocket = new Rocket(100); genericRocket.fly(10); System.out.println(genericRocket.toString()); } }
False
255
183
289
201
255
168
289
201
311
206
false
false
false
false
false
true
1,466
31979_1
package Interfaces; public interface Event { /** * Deze functie voert het event uit. * @return Object - Het resultaat van het event. */ public Object Exucute(); /** * Dit event geeft het resultaat van het event terug. * @return Object - Het resultaat van het event. */ public Object GetResult(); }
RikkertTheDeveloper/Java-Structure-Template
Interfaces/Event.java
96
/** * Dit event geeft het resultaat van het event terug. * @return Object - Het resultaat van het event. */
block_comment
nl
package Interfaces; public interface Event { /** * Deze functie voert het event uit. * @return Object - Het resultaat van het event. */ public Object Exucute(); /** * Dit event geeft<SUF>*/ public Object GetResult(); }
True
80
30
89
33
88
30
89
33
101
35
false
false
false
false
false
true
4,009
113400_1
package com.github.pmoerenhout.jsmppmodem.smsc; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import com.github.pmoerenhout.jsmppmodem.util.Util; import net.freeutils.charset.gsm.CCPackedGSMCharset; class SmsUtilTest { @Test public void test_unpack() { // text is Test@0 final byte[] bytes = new byte[]{ (byte) 0xd4, (byte) 0xf2, (byte) 0x9c, (byte) 0x0e, (byte) 0x80, (byte) 0x01, }; assertArrayEquals(new byte[]{ (byte) 0x54, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x00, (byte) 0x30 }, SmsUtil.unpackGsm(bytes)); } @Test public void test_packed1() { // text is .com. Groet, KPN final String expected = "Beste klant. Uw tegoed bedraagt 0,00 euro en is houdbaar tot 11 nov 2020.\n" + "Uw extra registratie of prepaidkorting tegoed bedraagt 7,34 "; final int udhl = 6; final byte[] bytes = Util.hexToByteArray( "84E539BD0C5AB3C36EBA0B54BD83E8E5F3BB4C0689CB6479387CA683602C180C54AECBDFA0B21B949E83D0EF3A591C0ECB41F4371D148B81DC6F3B480693C15C8AEA1D54C6D3E56190BC7C4ECFE9F2303D5D06BDCD20B8BC0C0FA7C9EBB79C9E769F41F4F2F95D2683C465B23C1C3ED34137D68C0602"); final byte[] alignedBytes = SmsUtil.removeFillBits(bytes, SmsUtil.fillBits(udhl)); final byte[] ud = Util.hexToByteArray( StringUtils.repeat("0", udhl * 2) + Util.bytesToHexString(bytes)); System.out.println(Util.bytesToHexString(alignedBytes)); System.out.println(new String(alignedBytes, new CCPackedGSMCharset())); final String paddedString = StringUtils.substring(new String(ud, new CCPackedGSMCharset()), getLengthForUdhLength(udhl)); assertEquals(expected, paddedString); assertEquals(expected, new String(alignedBytes, new CCPackedGSMCharset())); } @Test public void test_packed2() { final byte[] bytes = Util.hexToByteArray( "CA75F9DBA5A8DE41737A584EA797CFEF3219242E93E5E1F0990E82B162A0725DFE7629AA77D012EA043DDDE232BC2C5FD3414F373BED2E83E0F277FB4D4F9741E2BA9B5C6683EC65B93DCCA683DE70102C0752D7DD20194C067329ACEFB71CD42E97E5A0B4DBFC96B7C3F47459076AA7D56ED71AEE06"); final byte[] bytes2 = Util.hexToByteArray( "75F9DBA5A8DE41737A584EA797CFEF3219242E93E5E1F0990E82B162A0725DFE7629AA77D012EA043DDDE232BC2C5FD3414F373BED2E83E0F277FB4D4F9741E2BA9B5C6683EC65B93DCCA683DE70102C0752D7DD20194C067329ACEFB71CD42E97E5A0B4DBFC96B7C3F47459076AA7D56ED71AEE06"); assertEquals("uro.\n" + "Uw starttegoed bedraagt 0,1 euro.\n" + "Uw KPN Onbeperkt Online promotie bundel vervalt op 09 jun 2020.\n" + "Voor meer informatie: mijn.kpn", new String(bytes2, new CCPackedGSMCharset())); } @Test public void test_packed3() { final String expected = ".com. Groet, KPN"; final byte[] bytes = Util.hexToByteArray("5CE377DB053ACADF653A0BB4843A01"); final int udhl = 6; final byte[] alignedBytes = SmsUtil.removeFillBits(bytes, SmsUtil.fillBits(udhl)); final byte[] ud = Util.hexToByteArray( StringUtils.repeat("0", udhl * 2) + Util.bytesToHexString(bytes)); System.out.println(Util.bytesToHexString(alignedBytes)); System.out.println(new String(alignedBytes, new CCPackedGSMCharset())); final String paddedString = StringUtils.substring(new String(ud, new CCPackedGSMCharset()), getLengthForUdhLength(udhl)); assertEquals(expected, paddedString); assertEquals(expected, new String(alignedBytes, new CCPackedGSMCharset())); } @Test public void test_packed_12345678() { assertEquals("12345678", new String(Util.hexToByteArray("31D98C56B3DD70"), new CCPackedGSMCharset())); assertEquals("31D98C56B3DD70", Util.bytesToHexString("12345678".getBytes(new CCPackedGSMCharset()))); } @Test public void test_packed_hellohello() { assertEquals("hellohello", new String(Util.hexToByteArray("E8329BFD4697D9EC37"), new CCPackedGSMCharset())); assertEquals("E8329BFD4697D9EC37", Util.bytesToHexString("hellohello".getBytes(new CCPackedGSMCharset()))); } @Test public void test_pack() { // text is .com. Groet, KPN final String text = ".com. Groet, KPN"; assertEquals("AEF1BBED021DE5EF329D055A429D", Util.bytesToHexString(text.getBytes(new CCPackedGSMCharset()))); final String filledText = "@@@@@@@.com. Groet, KPN"; assertEquals("0000000000005CE377DB053ACADF653A0BB4843A01", Util.bytesToHexString(filledText.getBytes(new CCPackedGSMCharset()))); } @Test public void test_length_for_udh_length() { for (int i = 0; i < 32; i++) { System.out.println(i + "\t=>\t" + getLengthForUdhLength(i)); } } private int getLengthForUdhLength(final int i) { int chars = (i * 8) / 7; final int reminder = ((i * 8) % 7); if (reminder != 0) { chars++; } return chars; } }
pmoerenhout/jsmpp-modem
src/test/java/com/github/pmoerenhout/jsmppmodem/smsc/SmsUtilTest.java
1,955
// text is .com. Groet, KPN
line_comment
nl
package com.github.pmoerenhout.jsmppmodem.smsc; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import org.apache.commons.lang3.StringUtils; import org.junit.jupiter.api.Test; import com.github.pmoerenhout.jsmppmodem.util.Util; import net.freeutils.charset.gsm.CCPackedGSMCharset; class SmsUtilTest { @Test public void test_unpack() { // text is Test@0 final byte[] bytes = new byte[]{ (byte) 0xd4, (byte) 0xf2, (byte) 0x9c, (byte) 0x0e, (byte) 0x80, (byte) 0x01, }; assertArrayEquals(new byte[]{ (byte) 0x54, (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x00, (byte) 0x30 }, SmsUtil.unpackGsm(bytes)); } @Test public void test_packed1() { // text is<SUF> final String expected = "Beste klant. Uw tegoed bedraagt 0,00 euro en is houdbaar tot 11 nov 2020.\n" + "Uw extra registratie of prepaidkorting tegoed bedraagt 7,34 "; final int udhl = 6; final byte[] bytes = Util.hexToByteArray( "84E539BD0C5AB3C36EBA0B54BD83E8E5F3BB4C0689CB6479387CA683602C180C54AECBDFA0B21B949E83D0EF3A591C0ECB41F4371D148B81DC6F3B480693C15C8AEA1D54C6D3E56190BC7C4ECFE9F2303D5D06BDCD20B8BC0C0FA7C9EBB79C9E769F41F4F2F95D2683C465B23C1C3ED34137D68C0602"); final byte[] alignedBytes = SmsUtil.removeFillBits(bytes, SmsUtil.fillBits(udhl)); final byte[] ud = Util.hexToByteArray( StringUtils.repeat("0", udhl * 2) + Util.bytesToHexString(bytes)); System.out.println(Util.bytesToHexString(alignedBytes)); System.out.println(new String(alignedBytes, new CCPackedGSMCharset())); final String paddedString = StringUtils.substring(new String(ud, new CCPackedGSMCharset()), getLengthForUdhLength(udhl)); assertEquals(expected, paddedString); assertEquals(expected, new String(alignedBytes, new CCPackedGSMCharset())); } @Test public void test_packed2() { final byte[] bytes = Util.hexToByteArray( "CA75F9DBA5A8DE41737A584EA797CFEF3219242E93E5E1F0990E82B162A0725DFE7629AA77D012EA043DDDE232BC2C5FD3414F373BED2E83E0F277FB4D4F9741E2BA9B5C6683EC65B93DCCA683DE70102C0752D7DD20194C067329ACEFB71CD42E97E5A0B4DBFC96B7C3F47459076AA7D56ED71AEE06"); final byte[] bytes2 = Util.hexToByteArray( "75F9DBA5A8DE41737A584EA797CFEF3219242E93E5E1F0990E82B162A0725DFE7629AA77D012EA043DDDE232BC2C5FD3414F373BED2E83E0F277FB4D4F9741E2BA9B5C6683EC65B93DCCA683DE70102C0752D7DD20194C067329ACEFB71CD42E97E5A0B4DBFC96B7C3F47459076AA7D56ED71AEE06"); assertEquals("uro.\n" + "Uw starttegoed bedraagt 0,1 euro.\n" + "Uw KPN Onbeperkt Online promotie bundel vervalt op 09 jun 2020.\n" + "Voor meer informatie: mijn.kpn", new String(bytes2, new CCPackedGSMCharset())); } @Test public void test_packed3() { final String expected = ".com. Groet, KPN"; final byte[] bytes = Util.hexToByteArray("5CE377DB053ACADF653A0BB4843A01"); final int udhl = 6; final byte[] alignedBytes = SmsUtil.removeFillBits(bytes, SmsUtil.fillBits(udhl)); final byte[] ud = Util.hexToByteArray( StringUtils.repeat("0", udhl * 2) + Util.bytesToHexString(bytes)); System.out.println(Util.bytesToHexString(alignedBytes)); System.out.println(new String(alignedBytes, new CCPackedGSMCharset())); final String paddedString = StringUtils.substring(new String(ud, new CCPackedGSMCharset()), getLengthForUdhLength(udhl)); assertEquals(expected, paddedString); assertEquals(expected, new String(alignedBytes, new CCPackedGSMCharset())); } @Test public void test_packed_12345678() { assertEquals("12345678", new String(Util.hexToByteArray("31D98C56B3DD70"), new CCPackedGSMCharset())); assertEquals("31D98C56B3DD70", Util.bytesToHexString("12345678".getBytes(new CCPackedGSMCharset()))); } @Test public void test_packed_hellohello() { assertEquals("hellohello", new String(Util.hexToByteArray("E8329BFD4697D9EC37"), new CCPackedGSMCharset())); assertEquals("E8329BFD4697D9EC37", Util.bytesToHexString("hellohello".getBytes(new CCPackedGSMCharset()))); } @Test public void test_pack() { // text is .com. Groet, KPN final String text = ".com. Groet, KPN"; assertEquals("AEF1BBED021DE5EF329D055A429D", Util.bytesToHexString(text.getBytes(new CCPackedGSMCharset()))); final String filledText = "@@@@@@@.com. Groet, KPN"; assertEquals("0000000000005CE377DB053ACADF653A0BB4843A01", Util.bytesToHexString(filledText.getBytes(new CCPackedGSMCharset()))); } @Test public void test_length_for_udh_length() { for (int i = 0; i < 32; i++) { System.out.println(i + "\t=>\t" + getLengthForUdhLength(i)); } } private int getLengthForUdhLength(final int i) { int chars = (i * 8) / 7; final int reminder = ((i * 8) % 7); if (reminder != 0) { chars++; } return chars; } }
False
1,911
11
2,058
11
2,056
11
2,058
11
2,250
11
false
false
false
false
false
true
2,606
1602_2
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en y staat voor de afstand tussen magazijncoordinaten, //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
dylandreimerink/magazijnrobot
src/asrsSystem/DrawPanel.java
1,864
// afstandx en y staat voor de afstand tussen magazijncoordinaten,
line_comment
nl
package asrsSystem; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; import javax.swing.JLabel; import javax.swing.JPanel; import shared.Product; /* * Authors: Richard en Steven, ICTM2A */ public class DrawPanel extends JPanel { private BufferedImage image; private BufferedImage robotImage; private int magazijnSize = 5; private int WIDTH = 650; private int HEIGHT = 650; private ArrayList<Location> route; private ArrayList<Product> product; private JLabel JLRoute; public boolean drawRoute = false; private int afstandX; private int afstandY; private int counter = 0; private Warningfunctions warning = new Warningfunctions(); public DrawPanel() { // in constructor images declareren, afstand tussen magazijnvakken declareren. try { image = ImageIO.read(new File("src/img/crate.png")); robotImage = ImageIO.read(new File("src/img/robot.png")); } catch (IOException ex) { warning.showCriticalError(null, "afbeelding lezen error! controleer de img folder!"); } afstandX = (WIDTH / magazijnSize); afstandY = (HEIGHT / magazijnSize); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // afstandx en<SUF> //bv: tussen vakje 3 en 4 zitten 100 x coords for (int j = 0; j <= HEIGHT; j += afstandX) { g.drawLine(j, 0, j, HEIGHT); } for (int j = 0; j <= WIDTH; j += afstandY) { g.drawLine(0, j, WIDTH, j); } //route tekenen als drawroute == true, if not, overslaan if(drawRoute == true) { int index = 0; int maxindex = route.size(); for(Location loc: route) { if(index < maxindex-1){ int beginX = route.get(index).getLocationX(); int beginY = route.get(index).getLocationY(); index++; int eindX = route.get(index).getLocationX(); int eindY = route.get(index).getLocationY(); drawRoute(g,beginX,beginY,eindX,eindY,afstandX,afstandY); } } //als drawroute == true, dan word(en) ook de producten en robot getekend drawProduct(g); drawRobot(g, afstandX, afstandY, counter); } } private void drawProduct(Graphics g) { int index = 0; for(Product l:product) { int x = product.get(index).getLocationX(); int y = product.get(index).getLocationY(); int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.drawImage(image, dX-64, dY-64, null); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.blue); g.drawString(product.get(index).getProductName(),dX-18,dY-18); index++; } int x = 6; int y = 5; int dX = (afstandX*x) - (afstandX/2); int dY = (afstandY*y) - (afstandY/2); g.setColor(Color.DARK_GRAY); g.fillOval(dX-8,dY-8,18,18); g.setColor(Color.RED); g.drawString("Lopende band",dX+18,dY); } private void drawRoute(Graphics g, int beginX, int beginY, int eindX, int eindY, int afstandX, int afstandY) { int bX = (afstandX*beginX) - (afstandX/2); int bY = (afstandY*beginY) - (afstandY/2); int eX = (afstandX*eindX) - (afstandX/2); int eY = (afstandY*eindY) - (afstandY/2); Graphics2D g2 = (Graphics2D) g; g2.setStroke(new BasicStroke(3)); g.setColor(Color.DARK_GRAY); g.drawLine(bX, bY, eX, eY); } //drawrobotimage aan de hand van een gegeven counter. private void drawRobot(Graphics g, int afstandX, int afstandY, int counter) { if(counter == 0) { int x = route.get(counter).getLocationX(); int y = route.get(counter).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); }else{ int x = route.get(counter-1).getLocationX(); int y = route.get(counter-1).getLocationY(); int bX = (afstandX*x) - (afstandX/2); int bY = (afstandY*y) - (afstandY/2); g.drawImage(robotImage, bX-32, bY-32, null); repaint(); } } // methode om resultaat van de gegenereerde route door te geven aan deze klasse. public void setResult(ArrayList<Location> route,ArrayList<Location> productLoc, ArrayList<Product> productlist) { drawRoute = true; this.route = route; this.product = productlist; repaint(); } //word aangeroepen in controller, verhoogt de robotcounter wanneer deze word aangeroepen. //aan de hand van deze counter bepaald de robotImage bij welk product hij nu moet zijn. public void setRobotCounter() { if(counter < route.size()) { counter++; }else{ counter = route.size(); } } }
True
1,465
20
1,745
23
1,727
17
1,745
23
2,049
20
false
false
false
false
false
true
4,106
180952_6
package com.example.ChallangeMe_v1; import android.app.Service; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.Criteria; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.widget.Toast; /** * Created by ConstantijnSchepens on 25/03/14. */ public class GPS extends Service implements LocationListener { /** Variables **/ private static final String TAG = "SensorApp"; public static final String BROADCAST_ACTION = "com.example.Sensor.broadcastGPS"; //identifies broadcast private final Handler handler = new Handler(); //handler to broadcast within thread Intent intent; boolean isGPSEnabled = false; //GPS status flag boolean isNetworkEnabled = false; //Network status flag boolean canGetLocation = false; //GPS status Location currentLoc; //stores full location double latitude; //lat double longitude; //long private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; //1m private static final long MIN_TIME_BW_UPDATES = 1; //1ms protected LocationManager locationManager; //location manager declaration Criteria c; /** Lifecyle Methods" **/ @Override public void onCreate(){ super.onCreate(); intent = new Intent(BROADCAST_ACTION); //startup code try { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); c = new Criteria(); c.setAccuracy(Criteria.ACCURACY_LOW); //TODO fine? isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); //TODO use pending intent? // locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,this); // locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 0,0.0F,this); locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),0,0.0F,this); Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show(); handler.removeCallbacks(sendUpdatesToUI); handler.postDelayed(sendUpdatesToUI, 1000); // 1 second // Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show(); } catch (Exception e){ Log.e(TAG, "Unable to start GPS", e); Toast.makeText(this, "Unable to start GPS: " + e.toString(), Toast.LENGTH_LONG).show(); } } @Override public int onStartCommand(Intent intent, int flags, int startId){ //called when started currentLoc = locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true)); if(currentLoc != null){ latitude = currentLoc.getLatitude(); longitude = currentLoc.getLongitude(); /** Ensure app doesn't crash on start with in first location **/ intent = new Intent(BROADCAST_ACTION); //clear intent intent.putExtra("latitude", (float)currentLoc.getLatitude()); intent.putExtra("longitude", (float)currentLoc.getLongitude()); sendBroadcast(intent); } else { Toast.makeText(this, "current==NULL", Toast.LENGTH_SHORT).show(); } return 1; } @Override public void onDestroy(){ super.onDestroy(); Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show(); } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider){ } @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onLocationChanged(Location location) { //TODO if(locationManager != null){ currentLoc = location; // locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true)); if(location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); } } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { if(status != 2){ //2 means available /** Always use the best provider**/ locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true), MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); } } /** Method to handle handler update**/ private Runnable sendUpdatesToUI = new Runnable() { public void run() { //sendData(); handler.postDelayed(this, 1000); // 1 seconds } }; private void sendData() { Log.d(TAG, "entered DisplayLoggingInfo"); if(currentLoc != null){ intent = new Intent(BROADCAST_ACTION); //clear intent intent.putExtra("latitude", (float)currentLoc.getLatitude()); intent.putExtra("longitude", (float)currentLoc.getLongitude()); //sendBroadcast(intent); } } }
ram535ii/ChallengeMe
ChallangeMe_integrated_v1/src/com/example/ChallangeMe_v1/GPS.java
1,553
//TODO use pending intent?
line_comment
nl
package com.example.ChallangeMe_v1; import android.app.Service; import android.content.Intent; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.Criteria; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.util.Log; import android.widget.Toast; /** * Created by ConstantijnSchepens on 25/03/14. */ public class GPS extends Service implements LocationListener { /** Variables **/ private static final String TAG = "SensorApp"; public static final String BROADCAST_ACTION = "com.example.Sensor.broadcastGPS"; //identifies broadcast private final Handler handler = new Handler(); //handler to broadcast within thread Intent intent; boolean isGPSEnabled = false; //GPS status flag boolean isNetworkEnabled = false; //Network status flag boolean canGetLocation = false; //GPS status Location currentLoc; //stores full location double latitude; //lat double longitude; //long private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; //1m private static final long MIN_TIME_BW_UPDATES = 1; //1ms protected LocationManager locationManager; //location manager declaration Criteria c; /** Lifecyle Methods" **/ @Override public void onCreate(){ super.onCreate(); intent = new Intent(BROADCAST_ACTION); //startup code try { locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); c = new Criteria(); c.setAccuracy(Criteria.ACCURACY_LOW); //TODO fine? isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); //TODO use<SUF> // locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES,this); // locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 0,0.0F,this); locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true),0,0.0F,this); Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show(); handler.removeCallbacks(sendUpdatesToUI); handler.postDelayed(sendUpdatesToUI, 1000); // 1 second // Toast.makeText(this, "GPS Service Started", Toast.LENGTH_LONG).show(); } catch (Exception e){ Log.e(TAG, "Unable to start GPS", e); Toast.makeText(this, "Unable to start GPS: " + e.toString(), Toast.LENGTH_LONG).show(); } } @Override public int onStartCommand(Intent intent, int flags, int startId){ //called when started currentLoc = locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true)); if(currentLoc != null){ latitude = currentLoc.getLatitude(); longitude = currentLoc.getLongitude(); /** Ensure app doesn't crash on start with in first location **/ intent = new Intent(BROADCAST_ACTION); //clear intent intent.putExtra("latitude", (float)currentLoc.getLatitude()); intent.putExtra("longitude", (float)currentLoc.getLongitude()); sendBroadcast(intent); } else { Toast.makeText(this, "current==NULL", Toast.LENGTH_SHORT).show(); } return 1; } @Override public void onDestroy(){ super.onDestroy(); Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show(); } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider){ } @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onLocationChanged(Location location) { //TODO if(locationManager != null){ currentLoc = location; // locationManager.getLastKnownLocation(locationManager.getBestProvider(c,true)); if(location != null){ latitude = location.getLatitude(); longitude = location.getLongitude(); } } } @Override public void onStatusChanged(String provider, int status, Bundle extras) { if(status != 2){ //2 means available /** Always use the best provider**/ locationManager.requestLocationUpdates(locationManager.getBestProvider(c,true), MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); } } /** Method to handle handler update**/ private Runnable sendUpdatesToUI = new Runnable() { public void run() { //sendData(); handler.postDelayed(this, 1000); // 1 seconds } }; private void sendData() { Log.d(TAG, "entered DisplayLoggingInfo"); if(currentLoc != null){ intent = new Intent(BROADCAST_ACTION); //clear intent intent.putExtra("latitude", (float)currentLoc.getLatitude()); intent.putExtra("longitude", (float)currentLoc.getLongitude()); //sendBroadcast(intent); } } }
False
1,076
6
1,248
6
1,318
6
1,248
6
1,515
7
false
false
false
false
false
true
2,345
34523_8
package imageProcessing; import generalStatPurpose.gpFrequencyDistributionStatFunctions; public class cmcProcKMeans { class kMeanItem { int value; int cluster; kMeanItem(int i) { value=i; cluster=-1; } } private kMeanItem[] kmset=null; private int aantalClusters=-1; private int[] centroids; // in feite MEAN private gpFrequencyDistributionStatFunctions pstat=null; //------------------------------------------------------------ cmcProcKMeans() //------------------------------------------------------------ { pstat = new gpFrequencyDistributionStatFunctions(); } //------------------------------------------------------------ public void populateSingleDimensionSet(int iaantal , int[] iset) //------------------------------------------------------------ { int aantal = iset.length; kmset = new kMeanItem[aantal]; for(int i=0;i<aantal;i++) kmset[i] = new kMeanItem(iset[i]); // aantalClusters=iaantal; centroids = new int[aantalClusters]; /* centroids[0] = 0; centroids[1] = pstat.getMode( iset ); for(int i=2;i<aantalClusters;i++) { int per = centroids[1] / (aantalClusters - 1); centroids[i] = centroids[i-1] - per; } */ // SEED - dit werkt best for(int i=0;i<aantalClusters;i++) { centroids[i] = (i+1) *10; } sho(); } //------------------------------------------------------------ private void sho() //------------------------------------------------------------ { String sLijn = "CENTROIDS : "; for(int i=0;i<aantalClusters;i++) { sLijn += "\n (" + i + ") " + centroids[i] + " "; sLijn += " OBS="+getNumberOfElementsPerCentroidViaIdx(i); } //System.out.println(sLijn); } //------------------------------------------------------------ public void doit() //------------------------------------------------------------ { startIteratie(); for(int i=0;i<10;i++) { if( itereer() == false) break; } } //------------------------------------------------------------ private void startIteratie() //------------------------------------------------------------ { int[] prevCentroids = new int[aantalClusters]; int[] afstand = new int[aantalClusters]; for(int i=0;i<aantalClusters;i++) prevCentroids[i] = centroids[i]; // loop doorheen alle waarden en alloceer for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[i].value; nn++; } centroids[idx] = som/nn; } sho(); } //------------------------------------------------------------ private boolean itereer() //------------------------------------------------------------ { boolean swap=false; int[] afstand = new int[aantalClusters]; // for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } if( idx != kmset[i].cluster ) { swap=true; int oldidx = kmset[i].cluster; kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } centroids[idx] = som/nn; // de mean op de vrorgere cluster aanpassen som=0; nn=0; idx = oldidx; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } } } sho(); return swap; } //------------------------------------------------------------ public int[] getClusters() //------------------------------------------------------------ { int[] clusterlist = new int[kmset.length]; for(int i=0;i<kmset.length;i++ ) clusterlist[i] = kmset[i].cluster; return clusterlist; } //------------------------------------------------------------ public int getClusterViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= kmset.length) || (idx<0) ) return -1; return kmset[idx].cluster; } //------------------------------------------------------------ public int getCentroidValueViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= centroids.length) || (idx<0) ) return -1; return centroids[idx]; } //------------------------------------------------------------ public int getNumberOfElementsPerCentroidViaIdx(int idx) //------------------------------------------------------------ { int teller=0; if( (idx >= centroids.length) || (idx<0) ) return -1; for(int j=0;j<kmset.length;j++) { if( kmset[j].cluster == idx) teller++; } return teller; } }
cbrtekstraktor/cbrTekStraktor
src/imageProcessing/cmcProcKMeans.java
2,016
// de mean op de vrorgere cluster aanpassen
line_comment
nl
package imageProcessing; import generalStatPurpose.gpFrequencyDistributionStatFunctions; public class cmcProcKMeans { class kMeanItem { int value; int cluster; kMeanItem(int i) { value=i; cluster=-1; } } private kMeanItem[] kmset=null; private int aantalClusters=-1; private int[] centroids; // in feite MEAN private gpFrequencyDistributionStatFunctions pstat=null; //------------------------------------------------------------ cmcProcKMeans() //------------------------------------------------------------ { pstat = new gpFrequencyDistributionStatFunctions(); } //------------------------------------------------------------ public void populateSingleDimensionSet(int iaantal , int[] iset) //------------------------------------------------------------ { int aantal = iset.length; kmset = new kMeanItem[aantal]; for(int i=0;i<aantal;i++) kmset[i] = new kMeanItem(iset[i]); // aantalClusters=iaantal; centroids = new int[aantalClusters]; /* centroids[0] = 0; centroids[1] = pstat.getMode( iset ); for(int i=2;i<aantalClusters;i++) { int per = centroids[1] / (aantalClusters - 1); centroids[i] = centroids[i-1] - per; } */ // SEED - dit werkt best for(int i=0;i<aantalClusters;i++) { centroids[i] = (i+1) *10; } sho(); } //------------------------------------------------------------ private void sho() //------------------------------------------------------------ { String sLijn = "CENTROIDS : "; for(int i=0;i<aantalClusters;i++) { sLijn += "\n (" + i + ") " + centroids[i] + " "; sLijn += " OBS="+getNumberOfElementsPerCentroidViaIdx(i); } //System.out.println(sLijn); } //------------------------------------------------------------ public void doit() //------------------------------------------------------------ { startIteratie(); for(int i=0;i<10;i++) { if( itereer() == false) break; } } //------------------------------------------------------------ private void startIteratie() //------------------------------------------------------------ { int[] prevCentroids = new int[aantalClusters]; int[] afstand = new int[aantalClusters]; for(int i=0;i<aantalClusters;i++) prevCentroids[i] = centroids[i]; // loop doorheen alle waarden en alloceer for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[i].value; nn++; } centroids[idx] = som/nn; } sho(); } //------------------------------------------------------------ private boolean itereer() //------------------------------------------------------------ { boolean swap=false; int[] afstand = new int[aantalClusters]; // for(int i=0;i<kmset.length;i++) { for(int j=0;j<aantalClusters;j++) { afstand[j] = centroids[j] - kmset[i].value; if( afstand[j] < 0 ) afstand[j] = 0 - afstand[j]; } // zoek kleinste afstand int idx=0; int min=afstand[idx]; for(int j=1;j<aantalClusters;j++) { if( afstand[j] < min ) { min = afstand[j]; idx=j; } } if( idx != kmset[i].cluster ) { swap=true; int oldidx = kmset[i].cluster; kmset[i].cluster = idx; // nu de MEAN op die cluster aanpassen -> andere centroid int som=0; int nn=0; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } centroids[idx] = som/nn; // de mean<SUF> som=0; nn=0; idx = oldidx; for(int z=0;z<kmset.length;z++) { if( kmset[z].cluster != idx ) continue; som += kmset[z].value; nn++; } } } sho(); return swap; } //------------------------------------------------------------ public int[] getClusters() //------------------------------------------------------------ { int[] clusterlist = new int[kmset.length]; for(int i=0;i<kmset.length;i++ ) clusterlist[i] = kmset[i].cluster; return clusterlist; } //------------------------------------------------------------ public int getClusterViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= kmset.length) || (idx<0) ) return -1; return kmset[idx].cluster; } //------------------------------------------------------------ public int getCentroidValueViaIdx(int idx) //------------------------------------------------------------ { if( (idx >= centroids.length) || (idx<0) ) return -1; return centroids[idx]; } //------------------------------------------------------------ public int getNumberOfElementsPerCentroidViaIdx(int idx) //------------------------------------------------------------ { int teller=0; if( (idx >= centroids.length) || (idx<0) ) return -1; for(int j=0;j<kmset.length;j++) { if( kmset[j].cluster == idx) teller++; } return teller; } }
True
1,399
12
1,578
12
1,787
11
1,578
12
1,940
13
false
false
false
false
false
true
842
113783_7
package com.baiduMap; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 根据订单的经纬度归属所在的商业区域 * @author lee * @date: 2017年2月6日 下午2:12:02 */ public class Polygon { public static void main(String[] args) { // 被检测的经纬度点 Map<String, String> orderLocation = new HashMap<String, String>(); orderLocation.put("X", "217.228117"); orderLocation.put("Y", "31.830429"); // 商业区域(百度多边形区域经纬度集合) String partitionLocation = "31.839064_117.219116,31.83253_117.219403,31.828511_117.218146,31.826763_117.219259,31.826118_117.220517,31.822713_117.23586,31.822958_117.238375,31.838512_117.23798,31.839617_117.226194,31.839586_117.222925"; System.out.println(isInPolygon(orderLocation, partitionLocation)); } /** * 判断当前位置是否在多边形区域内 * @param orderLocation 当前点 * @param partitionLocation 区域顶点 * @return */ public static boolean isInPolygon(Map orderLocation,String partitionLocation){ double p_x =Double.parseDouble((String) orderLocation.get("X")); double p_y =Double.parseDouble((String) orderLocation.get("Y")); Point2D.Double point = new Point2D.Double(p_x, p_y); List<Point2D.Double> pointList= new ArrayList<Point2D.Double>(); String[] strList = partitionLocation.split(","); for (String str : strList){ String[] points = str.split("_"); double polygonPoint_x=Double.parseDouble(points[1]); double polygonPoint_y=Double.parseDouble(points[0]); Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x,polygonPoint_y); pointList.add(polygonPoint); } return IsPtInPoly(point,pointList); } /** * 返回一个点是否在一个多边形区域内, 如果点位于多边形的顶点或边上,不算做点在多边形内,返回false * @param point * @param polygon * @return */ public static boolean checkWithJdkGeneralPath(Point2D.Double point, List<Point2D.Double> polygon) { java.awt.geom.GeneralPath p = new java.awt.geom.GeneralPath(); Point2D.Double first = polygon.get(0); p.moveTo(first.x, first.y); polygon.remove(0); for (Point2D.Double d : polygon) { p.lineTo(d.x, d.y); } p.lineTo(first.x, first.y); p.closePath(); return p.contains(point); } /** * 判断点是否在多边形内,如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true * @param point 检测点 * @param pts 多边形的顶点 * @return 点在多边形内返回true,否则返回false */ public static boolean IsPtInPoly(Point2D.Double point, List<Point2D.Double> pts){ int N = pts.size(); boolean boundOrVertex = true; //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true int intersectCount = 0;//cross points count of x double precision = 2e-10; //浮点类型计算时候与0比较时候的容差 Point2D.Double p1, p2;//neighbour bound vertices Point2D.Double p = point; //当前点 p1 = pts.get(0);//left vertex for(int i = 1; i <= N; ++i){//check all rays if(p.equals(p1)){ return boundOrVertex;//p is an vertex } p2 = pts.get(i % N);//right vertex if(p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)){//ray is outside of our interests p1 = p2; continue;//next ray left point } if(p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)){//ray is crossing over by the algorithm (common part of) if(p.y <= Math.max(p1.y, p2.y)){//x is before of ray if(p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)){//overlies on a horizontal ray return boundOrVertex; } if(p1.y == p2.y){//ray is vertical if(p1.y == p.y){//overlies on a vertical ray return boundOrVertex; }else{//before ray ++intersectCount; } }else{//cross point on the left side double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;//cross point of y if(Math.abs(p.y - xinters) < precision){//overlies on a ray return boundOrVertex; } if(p.y < xinters){//before ray ++intersectCount; } } } }else{//special case when ray is crossing through the vertex if(p.x == p2.x && p.y <= p2.y){//p crossing over p2 Point2D.Double p3 = pts.get((i+1) % N); //next vertex if(p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)){//p.x lies between p1.x & p3.x ++intersectCount; }else{ intersectCount += 2; } } } p1 = p2;//next ray left point } if(intersectCount % 2 == 0){//偶数在多边形外 return false; } else { //奇数在多边形内 return true; } } }
JimmyYangMJ/MyJAVA_DS
src/com/baiduMap/Polygon.java
1,775
//p is an vertex
line_comment
nl
package com.baiduMap; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 根据订单的经纬度归属所在的商业区域 * @author lee * @date: 2017年2月6日 下午2:12:02 */ public class Polygon { public static void main(String[] args) { // 被检测的经纬度点 Map<String, String> orderLocation = new HashMap<String, String>(); orderLocation.put("X", "217.228117"); orderLocation.put("Y", "31.830429"); // 商业区域(百度多边形区域经纬度集合) String partitionLocation = "31.839064_117.219116,31.83253_117.219403,31.828511_117.218146,31.826763_117.219259,31.826118_117.220517,31.822713_117.23586,31.822958_117.238375,31.838512_117.23798,31.839617_117.226194,31.839586_117.222925"; System.out.println(isInPolygon(orderLocation, partitionLocation)); } /** * 判断当前位置是否在多边形区域内 * @param orderLocation 当前点 * @param partitionLocation 区域顶点 * @return */ public static boolean isInPolygon(Map orderLocation,String partitionLocation){ double p_x =Double.parseDouble((String) orderLocation.get("X")); double p_y =Double.parseDouble((String) orderLocation.get("Y")); Point2D.Double point = new Point2D.Double(p_x, p_y); List<Point2D.Double> pointList= new ArrayList<Point2D.Double>(); String[] strList = partitionLocation.split(","); for (String str : strList){ String[] points = str.split("_"); double polygonPoint_x=Double.parseDouble(points[1]); double polygonPoint_y=Double.parseDouble(points[0]); Point2D.Double polygonPoint = new Point2D.Double(polygonPoint_x,polygonPoint_y); pointList.add(polygonPoint); } return IsPtInPoly(point,pointList); } /** * 返回一个点是否在一个多边形区域内, 如果点位于多边形的顶点或边上,不算做点在多边形内,返回false * @param point * @param polygon * @return */ public static boolean checkWithJdkGeneralPath(Point2D.Double point, List<Point2D.Double> polygon) { java.awt.geom.GeneralPath p = new java.awt.geom.GeneralPath(); Point2D.Double first = polygon.get(0); p.moveTo(first.x, first.y); polygon.remove(0); for (Point2D.Double d : polygon) { p.lineTo(d.x, d.y); } p.lineTo(first.x, first.y); p.closePath(); return p.contains(point); } /** * 判断点是否在多边形内,如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true * @param point 检测点 * @param pts 多边形的顶点 * @return 点在多边形内返回true,否则返回false */ public static boolean IsPtInPoly(Point2D.Double point, List<Point2D.Double> pts){ int N = pts.size(); boolean boundOrVertex = true; //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true int intersectCount = 0;//cross points count of x double precision = 2e-10; //浮点类型计算时候与0比较时候的容差 Point2D.Double p1, p2;//neighbour bound vertices Point2D.Double p = point; //当前点 p1 = pts.get(0);//left vertex for(int i = 1; i <= N; ++i){//check all rays if(p.equals(p1)){ return boundOrVertex;//p is<SUF> } p2 = pts.get(i % N);//right vertex if(p.x < Math.min(p1.x, p2.x) || p.x > Math.max(p1.x, p2.x)){//ray is outside of our interests p1 = p2; continue;//next ray left point } if(p.x > Math.min(p1.x, p2.x) && p.x < Math.max(p1.x, p2.x)){//ray is crossing over by the algorithm (common part of) if(p.y <= Math.max(p1.y, p2.y)){//x is before of ray if(p1.x == p2.x && p.y >= Math.min(p1.y, p2.y)){//overlies on a horizontal ray return boundOrVertex; } if(p1.y == p2.y){//ray is vertical if(p1.y == p.y){//overlies on a vertical ray return boundOrVertex; }else{//before ray ++intersectCount; } }else{//cross point on the left side double xinters = (p.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x) + p1.y;//cross point of y if(Math.abs(p.y - xinters) < precision){//overlies on a ray return boundOrVertex; } if(p.y < xinters){//before ray ++intersectCount; } } } }else{//special case when ray is crossing through the vertex if(p.x == p2.x && p.y <= p2.y){//p crossing over p2 Point2D.Double p3 = pts.get((i+1) % N); //next vertex if(p.x >= Math.min(p1.x, p3.x) && p.x <= Math.max(p1.x, p3.x)){//p.x lies between p1.x & p3.x ++intersectCount; }else{ intersectCount += 2; } } } p1 = p2;//next ray left point } if(intersectCount % 2 == 0){//偶数在多边形外 return false; } else { //奇数在多边形内 return true; } } }
False
1,553
5
1,729
5
1,793
5
1,729
5
2,013
5
false
false
false
false
false
true
1,535
161618_1
// =========================================================================== // // // // Copyright 2008-2011 Andrew Casey, Jun Li, Jesse Doherty, // // Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed, // // Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger, // // Laurie Hendren, Clark Verbrugge and McGill University. // // // // 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 natlab; import natlab.backends.vrirGen.VRIRGenerator; import natlab.options.VRIROptions; /** * Main entry point for McLab compiler. Includes a main method that deals with * command line options and performs the desired functions. */ public class Main { /** * Main method deals with command line options and execution of desired * functions. */ public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("No options given\nTry -help for usage"); return; } VRIROptions options = new VRIROptions(); options.parse(args); run(options); } public static void run(VRIROptions options) throws Exception { // VRIR options if (options.vrir() || options.mex()) { if (options.files().isEmpty()) { if (!options.main().isEmpty()) { /* * If the user provided an entry point function and did not * provide a separate file, Use the main file as the input * file. */ options.files().add(options.main()); } else { System.err .println("No files provided, must have at least one file."); } } if (options.main() == null || options.main().length() == 0) { options.setMain(options.files().get(0)); } VRIRGenerator.compile(options); } else { McLabCore.run(options); } } }
Sable/VRIRGenerator
languages/Natlab/src/Main.java
758
// Maxime Chevalier-Boisvert, Toheed Aslam, Anton Dubrau, Nurudeen Lameed, //
line_comment
nl
// =========================================================================== // // // // Copyright 2008-2011 Andrew Casey, Jun Li, Jesse Doherty, // // Maxime Chevalier-Boisvert,<SUF> // Amina Aslam, Rahul Garg, Soroush Radpour, Olivier Savary Belanger, // // Laurie Hendren, Clark Verbrugge and McGill University. // // // // 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 natlab; import natlab.backends.vrirGen.VRIRGenerator; import natlab.options.VRIROptions; /** * Main entry point for McLab compiler. Includes a main method that deals with * command line options and performs the desired functions. */ public class Main { /** * Main method deals with command line options and execution of desired * functions. */ public static void main(String[] args) throws Exception { if (args.length == 0) { System.err.println("No options given\nTry -help for usage"); return; } VRIROptions options = new VRIROptions(); options.parse(args); run(options); } public static void run(VRIROptions options) throws Exception { // VRIR options if (options.vrir() || options.mex()) { if (options.files().isEmpty()) { if (!options.main().isEmpty()) { /* * If the user provided an entry point function and did not * provide a separate file, Use the main file as the input * file. */ options.files().add(options.main()); } else { System.err .println("No files provided, must have at least one file."); } } if (options.main() == null || options.main().length() == 0) { options.setMain(options.files().get(0)); } VRIRGenerator.compile(options); } else { McLabCore.run(options); } } }
False
594
31
694
36
690
26
694
36
837
32
false
false
false
false
false
true
4,414
23990_0
package eu.insertcode.wordgames; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import eu.insertcode.wordgames.games.WordGame; import static org.bukkit.ChatColor.translateAlternateColorCodes; /** * @author Maarten de Goede - insertCode.eu * Main class */ public class Main extends JavaPlugin implements Listener { ArrayList<WordGame> wordGames = new ArrayList<>(); private Reflection reflection; /** * Gets a message from the config and puts it in an array. * @param path The path to the message. * @return A coloured String array. */ public static String[] getMessages(String path) { FileConfiguration msgConfig = ConfigManager.getMessages(); String[] messages; messages = ConfigManager.getMessages().isList(path) ? msgConfig.getStringList(path).toArray(new String[0]) : new String[]{msgConfig.getString(path)}; for (int i = 0; i < messages.length; i++) { messages[i] = messages[i].replace("{plugin}", msgConfig.getString("variables.plugin")); } return messages; } public static String[] getColouredMessages(String path) { String[] messages = getMessages(path); for (int i = 0; i < messages.length; i++) { messages[i] = translateAlternateColorCodes('&', messages[i]); } return messages; } private boolean setup() { try { reflection = new Reflection(); getLogger().info("[WordGames+, insertCode] Your server is running " + reflection.getVersion()); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } void reload() { ConfigManager.reloadMessages(); reloadConfig(); } public Reflection getReflection() { return reflection; } public void removeGame(WordGame game) { wordGames.remove(game); } @Override public void onEnable() { if (setup()) { // Register the plugin events in this class getServer().getPluginManager().registerEvents(this, this); ConfigManager.createFiles(this); getCommand("wordgame").setExecutor(new CommandHandler(this)); AutoStart.setPlugin(this); AutoStart.autoStart(); // Start the autoStart scheduler. } else { getLogger().severe("Failed to setup WordGames+!"); getLogger().severe("Your server version is not compatible with this plugin!"); Bukkit.getPluginManager().disablePlugin(this); } } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent e) { Player p = e.getPlayer(); for (WordGame game : wordGames) { if (Permission.PLAY_ALL.forPlayer(p, game.getPlayPermission())) game.onPlayerChat(e); else for (String message : getColouredMessages("error.noPlayPermissions")) p.sendMessage(message); } } }
supertassu/WordGamesPlus
src/main/java/eu/insertcode/wordgames/Main.java
929
/** * @author Maarten de Goede - insertCode.eu * Main class */
block_comment
nl
package eu.insertcode.wordgames; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import eu.insertcode.wordgames.games.WordGame; import static org.bukkit.ChatColor.translateAlternateColorCodes; /** * @author Maarten de<SUF>*/ public class Main extends JavaPlugin implements Listener { ArrayList<WordGame> wordGames = new ArrayList<>(); private Reflection reflection; /** * Gets a message from the config and puts it in an array. * @param path The path to the message. * @return A coloured String array. */ public static String[] getMessages(String path) { FileConfiguration msgConfig = ConfigManager.getMessages(); String[] messages; messages = ConfigManager.getMessages().isList(path) ? msgConfig.getStringList(path).toArray(new String[0]) : new String[]{msgConfig.getString(path)}; for (int i = 0; i < messages.length; i++) { messages[i] = messages[i].replace("{plugin}", msgConfig.getString("variables.plugin")); } return messages; } public static String[] getColouredMessages(String path) { String[] messages = getMessages(path); for (int i = 0; i < messages.length; i++) { messages[i] = translateAlternateColorCodes('&', messages[i]); } return messages; } private boolean setup() { try { reflection = new Reflection(); getLogger().info("[WordGames+, insertCode] Your server is running " + reflection.getVersion()); return true; } catch (Exception ex) { ex.printStackTrace(); return false; } } void reload() { ConfigManager.reloadMessages(); reloadConfig(); } public Reflection getReflection() { return reflection; } public void removeGame(WordGame game) { wordGames.remove(game); } @Override public void onEnable() { if (setup()) { // Register the plugin events in this class getServer().getPluginManager().registerEvents(this, this); ConfigManager.createFiles(this); getCommand("wordgame").setExecutor(new CommandHandler(this)); AutoStart.setPlugin(this); AutoStart.autoStart(); // Start the autoStart scheduler. } else { getLogger().severe("Failed to setup WordGames+!"); getLogger().severe("Your server version is not compatible with this plugin!"); Bukkit.getPluginManager().disablePlugin(this); } } @EventHandler public void onPlayerChat(AsyncPlayerChatEvent e) { Player p = e.getPlayer(); for (WordGame game : wordGames) { if (Permission.PLAY_ALL.forPlayer(p, game.getPlayPermission())) game.onPlayerChat(e); else for (String message : getColouredMessages("error.noPlayPermissions")) p.sendMessage(message); } } }
False
675
19
810
21
843
20
810
21
980
21
false
false
false
false
false
true
1,933
127224_1
package com.stickercamera.app.ui; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.github.skykai.stickercamera.R; import com.stickercamera.base.util.Constants; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import cn.jarlen.photoedit.operate.ImageObject; import cn.jarlen.photoedit.operate.OperateUtils; import cn.jarlen.photoedit.operate.OperateView; ; /** * 添加水印 */ public class AddWatermarkActivity extends Activity implements View.OnClickListener { private LinearLayout content_layout; private OperateView operateView; private String camera_path; private String mPath = null; OperateUtils operateUtils; private ImageButton btn_ok, btn_cancel; private TextView chunvzuo, shenhuifu, qiugouda, guaishushu, haoxingzuo, wanhuaile, xiangsi, xingzuokong, xinnian, zaoan, zuile, jiuyaozuo,zui; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.addwatermark); Intent intent = getIntent(); camera_path = intent.getStringExtra("camera_path"); operateUtils = new OperateUtils(this); //初始化布局方法 initView(); // 延迟每次延迟10 毫秒 隔1秒执行一次 timer.schedule(task, 10, 1000); } //获取图片显示框content-layout final Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { if (content_layout.getWidth() != 0) { Log.i("LinearLayoutW", content_layout.getWidth() + ""); Log.i("LinearLayoutH", content_layout.getHeight() + ""); // 取消定时器 timer.cancel(); //添加水印方法 fillContent(); } } } }; Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { Message message = new Message(); message.what = 1; myHandler.sendMessage(message); } }; //初始化布局 private void initView() { content_layout = (LinearLayout) findViewById(R.id.mainLayout); btn_ok = (ImageButton) findViewById(R.id.btn_ok); btn_cancel = (ImageButton) findViewById(R.id.btn_cancel); btn_ok.setOnClickListener(this); btn_cancel.setOnClickListener(this); chunvzuo = (TextView) findViewById(R.id.chunvzuo); shenhuifu = (TextView) findViewById(R.id.shenhuifu); qiugouda = (TextView) findViewById(R.id.qiugouda); guaishushu = (TextView) findViewById(R.id.guaishushu); haoxingzuo = (TextView) findViewById(R.id.haoxingzuo); wanhuaile = (TextView) findViewById(R.id.wanhuaile); xiangsi = (TextView) findViewById(R.id.xiangsi); xingzuokong = (TextView) findViewById(R.id.xingzuokong); xinnian = (TextView) findViewById(R.id.xinnian); zaoan = (TextView) findViewById(R.id.zaoan); zuile = (TextView) findViewById(R.id.zuile); jiuyaozuo = (TextView) findViewById(R.id.jiuyaozuo); zui = (TextView) findViewById(R.id.zui); chunvzuo.setOnClickListener(this); shenhuifu.setOnClickListener(this); qiugouda.setOnClickListener(this); guaishushu.setOnClickListener(this); haoxingzuo.setOnClickListener(this); wanhuaile.setOnClickListener(this); xiangsi.setOnClickListener(this); xingzuokong.setOnClickListener(this); xinnian.setOnClickListener(this); zaoan.setOnClickListener(this); zuile.setOnClickListener(this); jiuyaozuo.setOnClickListener(this); zui.setOnClickListener(this); } //添加水印的方法 private void fillContent() { Bitmap resizeBmp = BitmapFactory.decodeFile(camera_path);//取到传过来的图片位置 operateView = new OperateView(AddWatermarkActivity.this, resizeBmp); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( resizeBmp.getWidth(), resizeBmp.getHeight());//设置要添加的View的高和宽 operateView.setLayoutParams(layoutParams); content_layout.addView(operateView);//在原图上添加view,使用operateView类 operateView.setMultiAdd(true); // 设置此参数,可以添加多个图片 } //保存改后的图片 private void btnSave() { //添加的水印保存到图片上 operateView.save(); Bitmap bmp = getBitmapByView(operateView); if (bmp != null) { mPath = saveBitmap(bmp, "saveTemp"); //把修改过后保存的图片传给首页修改UI Intent okData = new Intent(); okData.putExtra("camera_path", mPath); setResult(RESULT_OK, okData); this.finish(); } } // 将模板View的图片转化为Bitmap public Bitmap getBitmapByView(View v) { Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); return bitmap; } // 将生成的图片保存到内存中 public String saveBitmap(Bitmap bitmap, String name) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(Constants.filePath); if (!dir.exists()) dir.mkdir(); File file = new File(Constants.filePath + name + ".jpg"); FileOutputStream out; try { out = new FileOutputStream(file); if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) { out.flush(); out.close(); } return file.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } } return null; } //添加水印方法 private void addpic(int position) { Bitmap bmp = BitmapFactory.decodeResource(getResources(), position); // ImageObject imgObject = operateUtils.getImageObject(bmp); ImageObject imgObject = operateUtils.getImageObject(bmp, operateView, 5, 150, 100); operateView.addItem(imgObject); } int watermark[] = {R.drawable.watermark_chunvzuo, R.drawable.comment, R.drawable.gouda, R.drawable.guaishushu, R.drawable.haoxingzuop, R.drawable.wanhuaile, R.drawable.xiangsi, R.drawable.xingzuokong, R.drawable.xinnian, R.drawable.zaoan, R.drawable.zuile, R.drawable.zuo,R.drawable.zui}; //通过点击不同的item菜单添加不同的水印 @Override public void onClick(View v) { switch (v.getId()) { case R.id.chunvzuo : addpic(watermark[0]); break; case R.id.shenhuifu : addpic(watermark[1]); break; case R.id.qiugouda : addpic(watermark[2]); break; case R.id.guaishushu : addpic(watermark[3]); break; case R.id.haoxingzuo : addpic(watermark[4]); break; case R.id.wanhuaile : addpic(watermark[5]); break; case R.id.xiangsi : addpic(watermark[6]); break; case R.id.xingzuokong : addpic(watermark[7]); break; case R.id.xinnian : addpic(watermark[8]); break; case R.id.zaoan : addpic(watermark[9]); break; case R.id.zuile : addpic(watermark[10]); break; case R.id.jiuyaozuo : addpic(watermark[11]); break; case R.id.zui : addpic(watermark[12]); break; case R.id.btn_ok : btnSave(); break; case R.id.btn_cancel : finish(); break; default : break; } } }
Zhengtianqi/MengpaiCamera-master
app/src/main/java/com/stickercamera/app/ui/AddWatermarkActivity.java
2,731
// ImageObject imgObject = operateUtils.getImageObject(bmp);
line_comment
nl
package com.stickercamera.app.ui; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.github.skykai.stickercamera.R; import com.stickercamera.base.util.Constants; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Timer; import java.util.TimerTask; import cn.jarlen.photoedit.operate.ImageObject; import cn.jarlen.photoedit.operate.OperateUtils; import cn.jarlen.photoedit.operate.OperateView; ; /** * 添加水印 */ public class AddWatermarkActivity extends Activity implements View.OnClickListener { private LinearLayout content_layout; private OperateView operateView; private String camera_path; private String mPath = null; OperateUtils operateUtils; private ImageButton btn_ok, btn_cancel; private TextView chunvzuo, shenhuifu, qiugouda, guaishushu, haoxingzuo, wanhuaile, xiangsi, xingzuokong, xinnian, zaoan, zuile, jiuyaozuo,zui; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.addwatermark); Intent intent = getIntent(); camera_path = intent.getStringExtra("camera_path"); operateUtils = new OperateUtils(this); //初始化布局方法 initView(); // 延迟每次延迟10 毫秒 隔1秒执行一次 timer.schedule(task, 10, 1000); } //获取图片显示框content-layout final Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 1) { if (content_layout.getWidth() != 0) { Log.i("LinearLayoutW", content_layout.getWidth() + ""); Log.i("LinearLayoutH", content_layout.getHeight() + ""); // 取消定时器 timer.cancel(); //添加水印方法 fillContent(); } } } }; Timer timer = new Timer(); TimerTask task = new TimerTask() { public void run() { Message message = new Message(); message.what = 1; myHandler.sendMessage(message); } }; //初始化布局 private void initView() { content_layout = (LinearLayout) findViewById(R.id.mainLayout); btn_ok = (ImageButton) findViewById(R.id.btn_ok); btn_cancel = (ImageButton) findViewById(R.id.btn_cancel); btn_ok.setOnClickListener(this); btn_cancel.setOnClickListener(this); chunvzuo = (TextView) findViewById(R.id.chunvzuo); shenhuifu = (TextView) findViewById(R.id.shenhuifu); qiugouda = (TextView) findViewById(R.id.qiugouda); guaishushu = (TextView) findViewById(R.id.guaishushu); haoxingzuo = (TextView) findViewById(R.id.haoxingzuo); wanhuaile = (TextView) findViewById(R.id.wanhuaile); xiangsi = (TextView) findViewById(R.id.xiangsi); xingzuokong = (TextView) findViewById(R.id.xingzuokong); xinnian = (TextView) findViewById(R.id.xinnian); zaoan = (TextView) findViewById(R.id.zaoan); zuile = (TextView) findViewById(R.id.zuile); jiuyaozuo = (TextView) findViewById(R.id.jiuyaozuo); zui = (TextView) findViewById(R.id.zui); chunvzuo.setOnClickListener(this); shenhuifu.setOnClickListener(this); qiugouda.setOnClickListener(this); guaishushu.setOnClickListener(this); haoxingzuo.setOnClickListener(this); wanhuaile.setOnClickListener(this); xiangsi.setOnClickListener(this); xingzuokong.setOnClickListener(this); xinnian.setOnClickListener(this); zaoan.setOnClickListener(this); zuile.setOnClickListener(this); jiuyaozuo.setOnClickListener(this); zui.setOnClickListener(this); } //添加水印的方法 private void fillContent() { Bitmap resizeBmp = BitmapFactory.decodeFile(camera_path);//取到传过来的图片位置 operateView = new OperateView(AddWatermarkActivity.this, resizeBmp); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( resizeBmp.getWidth(), resizeBmp.getHeight());//设置要添加的View的高和宽 operateView.setLayoutParams(layoutParams); content_layout.addView(operateView);//在原图上添加view,使用operateView类 operateView.setMultiAdd(true); // 设置此参数,可以添加多个图片 } //保存改后的图片 private void btnSave() { //添加的水印保存到图片上 operateView.save(); Bitmap bmp = getBitmapByView(operateView); if (bmp != null) { mPath = saveBitmap(bmp, "saveTemp"); //把修改过后保存的图片传给首页修改UI Intent okData = new Intent(); okData.putExtra("camera_path", mPath); setResult(RESULT_OK, okData); this.finish(); } } // 将模板View的图片转化为Bitmap public Bitmap getBitmapByView(View v) { Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); v.draw(canvas); return bitmap; } // 将生成的图片保存到内存中 public String saveBitmap(Bitmap bitmap, String name) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(Constants.filePath); if (!dir.exists()) dir.mkdir(); File file = new File(Constants.filePath + name + ".jpg"); FileOutputStream out; try { out = new FileOutputStream(file); if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out)) { out.flush(); out.close(); } return file.getAbsolutePath(); } catch (IOException e) { e.printStackTrace(); } } return null; } //添加水印方法 private void addpic(int position) { Bitmap bmp = BitmapFactory.decodeResource(getResources(), position); // ImageObject imgObject<SUF> ImageObject imgObject = operateUtils.getImageObject(bmp, operateView, 5, 150, 100); operateView.addItem(imgObject); } int watermark[] = {R.drawable.watermark_chunvzuo, R.drawable.comment, R.drawable.gouda, R.drawable.guaishushu, R.drawable.haoxingzuop, R.drawable.wanhuaile, R.drawable.xiangsi, R.drawable.xingzuokong, R.drawable.xinnian, R.drawable.zaoan, R.drawable.zuile, R.drawable.zuo,R.drawable.zui}; //通过点击不同的item菜单添加不同的水印 @Override public void onClick(View v) { switch (v.getId()) { case R.id.chunvzuo : addpic(watermark[0]); break; case R.id.shenhuifu : addpic(watermark[1]); break; case R.id.qiugouda : addpic(watermark[2]); break; case R.id.guaishushu : addpic(watermark[3]); break; case R.id.haoxingzuo : addpic(watermark[4]); break; case R.id.wanhuaile : addpic(watermark[5]); break; case R.id.xiangsi : addpic(watermark[6]); break; case R.id.xingzuokong : addpic(watermark[7]); break; case R.id.xinnian : addpic(watermark[8]); break; case R.id.zaoan : addpic(watermark[9]); break; case R.id.zuile : addpic(watermark[10]); break; case R.id.jiuyaozuo : addpic(watermark[11]); break; case R.id.zui : addpic(watermark[12]); break; case R.id.btn_ok : btnSave(); break; case R.id.btn_cancel : finish(); break; default : break; } } }
False
1,927
13
2,221
14
2,345
14
2,221
14
2,710
16
false
false
false
false
false
true
4,518
43907_0
package nl.timgoes.transactionservice.transactionservice.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class TransactionServiceConfig { @LoadBalanced //Moet gebeuren voor euruka anders werkt het niet @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
timgoes1997/CapitaSelectaJEA6SpringBoot
transaction-service/src/main/java/nl/timgoes/transactionservice/transactionservice/config/TransactionServiceConfig.java
130
//Moet gebeuren voor euruka anders werkt het niet
line_comment
nl
package nl.timgoes.transactionservice.transactionservice.config; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class TransactionServiceConfig { @LoadBalanced //Moet gebeuren<SUF> @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } }
True
93
15
124
16
116
13
124
16
133
16
false
false
false
false
false
true
3,720
49250_3
//Given an array and a value, remove all instances of that value in-place and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. //The order of elements can be changed. It doesn't matter what you leave beyond the new length. //Example: //Given nums = [3,2,2,3], val = 3, //Your function should return length = 2, with the first two elements of nums being 2. class RemoveElement { public int removeElement(int[] nums, int val) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != val) { nums[index++] = nums[i]; } } return index; } }
mostofashakib/Core-Interview-Preparation
Interview Preparation University/Resources/leetcode/two-pointers/RemoveElement.java
222
//Given nums = [3,2,2,3], val = 3,
line_comment
nl
//Given an array and a value, remove all instances of that value in-place and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. //The order of elements can be changed. It doesn't matter what you leave beyond the new length. //Example: //Given nums<SUF> //Your function should return length = 2, with the first two elements of nums being 2. class RemoveElement { public int removeElement(int[] nums, int val) { int index = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != val) { nums[index++] = nums[i]; } } return index; } }
False
183
18
201
18
211
18
201
18
224
20
false
false
false
false
false
true
968
22405_2
package hamhamdash.states; import hamhamdash.*; /** * * @author Serhan Uygur */ public class StatePause extends State { private String toDrawImage = ""; // Pause Screens // [ Main Screen Name ][ Sub Screens ][ Pages ] private String[][][] pauseScreens = { // Item 0, zonder submenu's { {"pause_res_game"}, {""}, {""} }, // Item 1, met submenu's { {"pause_help"}, {"game_goal", "game_controls", "game_objects", "game_back"}, {"2", "2", "8", "0"} }, // Item 2, zonder submenu's { {"pause_exit_title"}, {""}, {""} }, // Item 3, zonder submenu's { {"pause_exit_windows"}, {""}, {""} } }; // Counters for the screens private int currentMainScreen = 0; private int currentSubScreen = 0; private int currentPage = 0; // Checkers for sub or not private boolean inSub = false; private boolean arePages = false; public StatePause() { super("pauze"); toDrawImage = pauseScreens[0][0][0]; game.stopTimer(); started = true; } @Override public void start() { } @Override public void doFrame() { if(started) { if(game.getKey(Game.KeyEsc)) { game.clearKey(Game.KeyEsc); if(inSub) //Go back to previous menu { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } else //Exit pause state { game.recoverState(); game.startTimer(); game.repaint(); // game.removeGameState("Pause"); } } //navigate between options else if(game.getKey(Game.KeyUp)) // Moves selection up { game.clearKey(Game.KeyUp); currentPage = 1; prevScreen(pauseScreens); } else if(game.getKey(Game.KeyDown)) // Moves selection down { game.clearKey(Game.KeyDown); currentPage = 1; nextScreen(pauseScreens); } else if(game.getKey(Game.KeyEnter)) // Confirm selection { game.clearKey(Game.KeyEnter); if(toDrawImage.equals(pauseScreens[0][0][0])) { game.recoverState(); // game.removeGameState("Pause"); } else if(toDrawImage.equals(pauseScreens[1][0][0])) // Help item has subs { inSub = true; toDrawImage = pauseScreens[1][1][0] + 1; // select 1st sub page } else if(toDrawImage.equals(pauseScreens[2][0][0])) { game.setCurrentState("Title"); } else if(toDrawImage.equals(pauseScreens[3][0][0])) { game.exitEngine("Thank you for playing!"); } if(toDrawImage.equals(pauseScreens[1][1][3] + 1)) { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } } //Cycle through pages else if(game.getKey(Game.KeyRight) && inSub) //Go page forward { game.clearKey(Game.KeyRight); nextPage(pauseScreens); } else if(game.getKey(Game.KeyLeft) && inSub) //Go back a page { game.clearKey(Game.KeyLeft); prevPage(pauseScreens); } } } @Override public void paintFrame() { if(started) { game.drawImage(game.viewWidth() / 2 - (256 / 2), game.viewHeight() / 2 - (250 / 2), toDrawImage, false); } } public void nextScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen < screens.length - 1) // -1 because we start with 0 { currentMainScreen++; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen < screens[currentMainScreen].length) { currentSubScreen++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void prevScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen > 0) { currentMainScreen--; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen > 0) { currentSubScreen--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void nextPage(String[][][] screens) { String toDrawImage = ""; if(currentPage < Integer.parseInt(screens[currentMainScreen][2][currentSubScreen])) { currentPage++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } public void prevPage(String[][][] screens) { String toDrawImage = ""; if(currentPage > 1) { currentPage--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } }
Lenrocexe/HamHamDash
src/hamhamdash/states/StatePause.java
1,709
// Item 0, zonder submenu's
line_comment
nl
package hamhamdash.states; import hamhamdash.*; /** * * @author Serhan Uygur */ public class StatePause extends State { private String toDrawImage = ""; // Pause Screens // [ Main Screen Name ][ Sub Screens ][ Pages ] private String[][][] pauseScreens = { // Item 0,<SUF> { {"pause_res_game"}, {""}, {""} }, // Item 1, met submenu's { {"pause_help"}, {"game_goal", "game_controls", "game_objects", "game_back"}, {"2", "2", "8", "0"} }, // Item 2, zonder submenu's { {"pause_exit_title"}, {""}, {""} }, // Item 3, zonder submenu's { {"pause_exit_windows"}, {""}, {""} } }; // Counters for the screens private int currentMainScreen = 0; private int currentSubScreen = 0; private int currentPage = 0; // Checkers for sub or not private boolean inSub = false; private boolean arePages = false; public StatePause() { super("pauze"); toDrawImage = pauseScreens[0][0][0]; game.stopTimer(); started = true; } @Override public void start() { } @Override public void doFrame() { if(started) { if(game.getKey(Game.KeyEsc)) { game.clearKey(Game.KeyEsc); if(inSub) //Go back to previous menu { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } else //Exit pause state { game.recoverState(); game.startTimer(); game.repaint(); // game.removeGameState("Pause"); } } //navigate between options else if(game.getKey(Game.KeyUp)) // Moves selection up { game.clearKey(Game.KeyUp); currentPage = 1; prevScreen(pauseScreens); } else if(game.getKey(Game.KeyDown)) // Moves selection down { game.clearKey(Game.KeyDown); currentPage = 1; nextScreen(pauseScreens); } else if(game.getKey(Game.KeyEnter)) // Confirm selection { game.clearKey(Game.KeyEnter); if(toDrawImage.equals(pauseScreens[0][0][0])) { game.recoverState(); // game.removeGameState("Pause"); } else if(toDrawImage.equals(pauseScreens[1][0][0])) // Help item has subs { inSub = true; toDrawImage = pauseScreens[1][1][0] + 1; // select 1st sub page } else if(toDrawImage.equals(pauseScreens[2][0][0])) { game.setCurrentState("Title"); } else if(toDrawImage.equals(pauseScreens[3][0][0])) { game.exitEngine("Thank you for playing!"); } if(toDrawImage.equals(pauseScreens[1][1][3] + 1)) { inSub = false; toDrawImage = pauseScreens[1][0][0]; currentSubScreen = 0; } } //Cycle through pages else if(game.getKey(Game.KeyRight) && inSub) //Go page forward { game.clearKey(Game.KeyRight); nextPage(pauseScreens); } else if(game.getKey(Game.KeyLeft) && inSub) //Go back a page { game.clearKey(Game.KeyLeft); prevPage(pauseScreens); } } } @Override public void paintFrame() { if(started) { game.drawImage(game.viewWidth() / 2 - (256 / 2), game.viewHeight() / 2 - (250 / 2), toDrawImage, false); } } public void nextScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen < screens.length - 1) // -1 because we start with 0 { currentMainScreen++; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen < screens[currentMainScreen].length) { currentSubScreen++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void prevScreen(String[][][] screens) { String toDrawImage = ""; if(!inSub) { if(currentMainScreen > 0) { currentMainScreen--; } toDrawImage = screens[currentMainScreen][0][0]; } else { if(currentSubScreen > 0) { currentSubScreen--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + 1; } this.toDrawImage = toDrawImage; } public void nextPage(String[][][] screens) { String toDrawImage = ""; if(currentPage < Integer.parseInt(screens[currentMainScreen][2][currentSubScreen])) { currentPage++; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } public void prevPage(String[][][] screens) { String toDrawImage = ""; if(currentPage > 1) { currentPage--; } toDrawImage = screens[currentMainScreen][1][currentSubScreen] + currentPage; this.toDrawImage = toDrawImage; } }
True
1,290
8
1,405
10
1,560
9
1,405
10
1,692
11
false
false
false
false
false
true
4,520
46693_0
package com.github.timgoes1997.jms.serializer; import com.github.timgoes1997.jms.messaging.StandardMessage; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class ObjectSerializer<OBJECT> { private Gson gson; //gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund private final Class<OBJECT> objectClass; public ObjectSerializer(Class<OBJECT> objectClass){ this.objectClass = objectClass; gson = new GsonBuilder().create(); } public String objectToString(OBJECT object){ return gson.toJson(object); } public OBJECT objectFromString(String str){ return gson.fromJson(str, objectClass); } public StandardMessage standardMessageFromString(String str){ return gson.fromJson(str, TypeToken.getParameterized(StandardMessage.class, objectClass).getType()); } public String standardMessageToString(StandardMessage standardMessage){ return gson.toJson(standardMessage); } }
timgoes1997/DPI-KilometerRijden
Tim-JMS/src/main/com/github/timgoes1997/jms/serializer/ObjectSerializer.java
313
//gebruikte eerst genson maar die heeft slechte ondersteuning voor generics zoals RequestReply, terwijl gson dit met gemak ondersteund
line_comment
nl
package com.github.timgoes1997.jms.serializer; import com.github.timgoes1997.jms.messaging.StandardMessage; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class ObjectSerializer<OBJECT> { private Gson gson; //gebruikte eerst<SUF> private final Class<OBJECT> objectClass; public ObjectSerializer(Class<OBJECT> objectClass){ this.objectClass = objectClass; gson = new GsonBuilder().create(); } public String objectToString(OBJECT object){ return gson.toJson(object); } public OBJECT objectFromString(String str){ return gson.fromJson(str, objectClass); } public StandardMessage standardMessageFromString(String str){ return gson.fromJson(str, TypeToken.getParameterized(StandardMessage.class, objectClass).getType()); } public String standardMessageToString(StandardMessage standardMessage){ return gson.toJson(standardMessage); } }
False
228
34
274
40
275
27
274
40
325
36
false
false
false
false
false
true
1,281
68362_0
package be.pxl.ja; import be.pxl.ja.command.*; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class GameEngine { private static final Random RANDOM = new Random(); public static Detective detective; private Scanner scanner; public static boolean murderSolved; public static Envelope<Part> envelope; private HelpCommand helpCommand = new HelpCommand(); private SuspectsCommand suspectsCommand = new SuspectsCommand(); private RoomsCommand roomsCommand = new RoomsCommand(); private WeaponsCommand weaponsCommand = new WeaponsCommand(); private ClueCommand clueCommand = new ClueCommand(); private GoToCommand goToCommand = new GoToCommand(); private DescribeCommand describeCommand = new DescribeCommand(); private UnlockCommand unlockCommand = new UnlockCommand(); private AccuseCommand accuseCommand = new AccuseCommand(); public static List<Room> rooms; public static List<Weapon> weapons; public static List<Suspect> suspects; public static Mansion mansion; public static List<Part> parts; public static List<Anagram> anagrams; public static List<CrackTheCode> crackTheCodes; public GameEngine(Scanner scanner) { this.scanner = scanner; } public void initialize(String playerName) throws FileNotFoundException { murderSolved = false; File file = new File("src/main/resources/cluedo.txt"); File anagram = new File("src/main/resources/anagrams.txt"); File crackTheCode = new File("src/main/resources/crackthecode.txt"); scanner = new Scanner(file); rooms = new ArrayList<>(); weapons = new ArrayList<>(); suspects = new ArrayList<>(); parts = new ArrayList<>(); String objectType = null; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if ("#ROOMS".equals(line) || "#WEAPONS".equals(line) || "#SUSPECTS".equals(line)) { objectType = line; } else { if ("#ROOMS".equals(objectType)) { Room room = new Room(line); if (!rooms.contains(room)) { rooms.add(room); parts.add(room); } } else if ("#WEAPONS".equals(objectType)) { Weapon weapon = new Weapon(line); if (!weapons.contains(weapon)) { weapons.add(weapon); parts.add(weapon); } } else if ("#SUSPECTS".equals(objectType)) { String[] params = line.split(";"); String name = params[0].substring(params[0].indexOf(" ")).strip(); String title = params[0].substring(0, params[0].indexOf(" ")); Suspect suspect = new Suspect(name); suspect.setAge(Integer.parseInt(params[1])); suspect.setNationality(params[2]); suspect.setOccupation(params[2]); suspect.setTitle(title); if (!suspects.contains(suspect)) { suspects.add(suspect); parts.add(suspect); } } } } detective = new Detective(playerName); Room crimeScene = rooms.stream() .skip(RANDOM.nextInt(rooms.size())) .findFirst() .orElseThrow(() -> new CluedoException("No rooms found from game file")); crimeScene.setCrimeScene(true); Weapon murderWeapon = weapons.stream() .skip(RANDOM.nextInt(weapons.size())) .findFirst() .orElseThrow(() -> new CluedoException("No weapons found from game file")); Suspect murderer = suspects.stream() .skip(RANDOM.nextInt(suspects.size())) .findFirst() .orElseThrow(() -> new CluedoException("No suspects found from game file")); envelope = new Envelope<>(); envelope.addSecret(crimeScene); envelope.addSecret(murderWeapon); envelope.addSecret(murderer); // overige wapens en suspects verdelen over de kamers List<Weapon> roomWeapons = new ArrayList<>(); for (Weapon weapon : weapons){ if (!weapon.equals(murderWeapon)){ roomWeapons.add(weapon); } } List<Suspect> roomSuspects = new ArrayList<>(); for (Suspect suspect : suspects){ if (!suspect.equals(murderer)){ roomSuspects.add(suspect); } } for (Room room : rooms) { if (roomWeapons.size() != 0){ Weapon weapon = roomWeapons.get(RANDOM.nextInt(roomWeapons.size())); roomWeapons.remove(weapon); room.setWeapon(weapon); } if (roomSuspects.size() != 0){ Suspect suspect = roomSuspects.get(RANDOM.nextInt(roomSuspects.size())); roomSuspects.remove(suspect); room.setSuspect(suspect); } } mansion = new Mansion(new ArrayList<>(rooms)); detective.moveTo(mansion.getHall()); anagrams = new ArrayList<>(); scanner = new Scanner(anagram); while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] anagramPieces = line.split(";"); Anagram anagramConstruct = new Anagram(anagramPieces[0], anagramPieces[1], anagramPieces[2]); anagrams.add(anagramConstruct); } crackTheCodes = new ArrayList<>(); scanner = new Scanner(crackTheCode); int counter = 0; while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] questions = new String[5]; String answer; if ("#".equals(line.substring(0, 1))){ counter = 0; } else if (line.contains("ANSWER")){ String[] crackTheCodePieces = line.split(":"); answer = crackTheCodePieces[1].strip(); CrackTheCode crackTheCodeConstruct = new CrackTheCode(questions, answer); crackTheCodes.add(crackTheCodeConstruct); } else { questions[counter] = line; counter++; } } //--------------------------------------------------- scanner.close(); // einde van init, alle code voor deze lijn } public void start() { System.out.println("Who murdered Dr. Black? Where did the crime took place, and which weapon was used?"); System.out.println("Type 'help' for information..."); } public void executeCommand(String command) { if ("suspects".equals(command)){ suspectsCommand.execute(command); } else if ("rooms".equals(command)){ roomsCommand.execute(command); } else if ("weapons".equals(command)){ weaponsCommand.execute(command); } else if ("describe".equals(command)){ describeCommand.execute(command); } else if ("unlock".equals(command)){ unlockCommand.execute(command); } else if (command.contains("clue")){ //voorlopig clueCommand.execute(command.substring(5)); } else if ("help".equals(command)){ helpCommand.execute(command); } else if (command.contains("accuse")){ //voorlopig accuseCommand.execute(command.substring(7)); } else if (command.contains("goto")){ goToCommand.execute(command.substring(5)); } } public void printLocation() { System.out.println("You are in the " + detective.getCurrentRoom().getName()); } public boolean isMurderSolved() { return murderSolved; } }
PXLJavaAdvanced/java-adv-pe-cluedo-team-goud
src/main/java/be/pxl/ja/GameEngine.java
2,220
// overige wapens en suspects verdelen over de kamers
line_comment
nl
package be.pxl.ja; import be.pxl.ja.command.*; import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class GameEngine { private static final Random RANDOM = new Random(); public static Detective detective; private Scanner scanner; public static boolean murderSolved; public static Envelope<Part> envelope; private HelpCommand helpCommand = new HelpCommand(); private SuspectsCommand suspectsCommand = new SuspectsCommand(); private RoomsCommand roomsCommand = new RoomsCommand(); private WeaponsCommand weaponsCommand = new WeaponsCommand(); private ClueCommand clueCommand = new ClueCommand(); private GoToCommand goToCommand = new GoToCommand(); private DescribeCommand describeCommand = new DescribeCommand(); private UnlockCommand unlockCommand = new UnlockCommand(); private AccuseCommand accuseCommand = new AccuseCommand(); public static List<Room> rooms; public static List<Weapon> weapons; public static List<Suspect> suspects; public static Mansion mansion; public static List<Part> parts; public static List<Anagram> anagrams; public static List<CrackTheCode> crackTheCodes; public GameEngine(Scanner scanner) { this.scanner = scanner; } public void initialize(String playerName) throws FileNotFoundException { murderSolved = false; File file = new File("src/main/resources/cluedo.txt"); File anagram = new File("src/main/resources/anagrams.txt"); File crackTheCode = new File("src/main/resources/crackthecode.txt"); scanner = new Scanner(file); rooms = new ArrayList<>(); weapons = new ArrayList<>(); suspects = new ArrayList<>(); parts = new ArrayList<>(); String objectType = null; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if ("#ROOMS".equals(line) || "#WEAPONS".equals(line) || "#SUSPECTS".equals(line)) { objectType = line; } else { if ("#ROOMS".equals(objectType)) { Room room = new Room(line); if (!rooms.contains(room)) { rooms.add(room); parts.add(room); } } else if ("#WEAPONS".equals(objectType)) { Weapon weapon = new Weapon(line); if (!weapons.contains(weapon)) { weapons.add(weapon); parts.add(weapon); } } else if ("#SUSPECTS".equals(objectType)) { String[] params = line.split(";"); String name = params[0].substring(params[0].indexOf(" ")).strip(); String title = params[0].substring(0, params[0].indexOf(" ")); Suspect suspect = new Suspect(name); suspect.setAge(Integer.parseInt(params[1])); suspect.setNationality(params[2]); suspect.setOccupation(params[2]); suspect.setTitle(title); if (!suspects.contains(suspect)) { suspects.add(suspect); parts.add(suspect); } } } } detective = new Detective(playerName); Room crimeScene = rooms.stream() .skip(RANDOM.nextInt(rooms.size())) .findFirst() .orElseThrow(() -> new CluedoException("No rooms found from game file")); crimeScene.setCrimeScene(true); Weapon murderWeapon = weapons.stream() .skip(RANDOM.nextInt(weapons.size())) .findFirst() .orElseThrow(() -> new CluedoException("No weapons found from game file")); Suspect murderer = suspects.stream() .skip(RANDOM.nextInt(suspects.size())) .findFirst() .orElseThrow(() -> new CluedoException("No suspects found from game file")); envelope = new Envelope<>(); envelope.addSecret(crimeScene); envelope.addSecret(murderWeapon); envelope.addSecret(murderer); // overige wapens<SUF> List<Weapon> roomWeapons = new ArrayList<>(); for (Weapon weapon : weapons){ if (!weapon.equals(murderWeapon)){ roomWeapons.add(weapon); } } List<Suspect> roomSuspects = new ArrayList<>(); for (Suspect suspect : suspects){ if (!suspect.equals(murderer)){ roomSuspects.add(suspect); } } for (Room room : rooms) { if (roomWeapons.size() != 0){ Weapon weapon = roomWeapons.get(RANDOM.nextInt(roomWeapons.size())); roomWeapons.remove(weapon); room.setWeapon(weapon); } if (roomSuspects.size() != 0){ Suspect suspect = roomSuspects.get(RANDOM.nextInt(roomSuspects.size())); roomSuspects.remove(suspect); room.setSuspect(suspect); } } mansion = new Mansion(new ArrayList<>(rooms)); detective.moveTo(mansion.getHall()); anagrams = new ArrayList<>(); scanner = new Scanner(anagram); while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] anagramPieces = line.split(";"); Anagram anagramConstruct = new Anagram(anagramPieces[0], anagramPieces[1], anagramPieces[2]); anagrams.add(anagramConstruct); } crackTheCodes = new ArrayList<>(); scanner = new Scanner(crackTheCode); int counter = 0; while(scanner.hasNextLine()){ String line = scanner.nextLine(); String[] questions = new String[5]; String answer; if ("#".equals(line.substring(0, 1))){ counter = 0; } else if (line.contains("ANSWER")){ String[] crackTheCodePieces = line.split(":"); answer = crackTheCodePieces[1].strip(); CrackTheCode crackTheCodeConstruct = new CrackTheCode(questions, answer); crackTheCodes.add(crackTheCodeConstruct); } else { questions[counter] = line; counter++; } } //--------------------------------------------------- scanner.close(); // einde van init, alle code voor deze lijn } public void start() { System.out.println("Who murdered Dr. Black? Where did the crime took place, and which weapon was used?"); System.out.println("Type 'help' for information..."); } public void executeCommand(String command) { if ("suspects".equals(command)){ suspectsCommand.execute(command); } else if ("rooms".equals(command)){ roomsCommand.execute(command); } else if ("weapons".equals(command)){ weaponsCommand.execute(command); } else if ("describe".equals(command)){ describeCommand.execute(command); } else if ("unlock".equals(command)){ unlockCommand.execute(command); } else if (command.contains("clue")){ //voorlopig clueCommand.execute(command.substring(5)); } else if ("help".equals(command)){ helpCommand.execute(command); } else if (command.contains("accuse")){ //voorlopig accuseCommand.execute(command.substring(7)); } else if (command.contains("goto")){ goToCommand.execute(command.substring(5)); } } public void printLocation() { System.out.println("You are in the " + detective.getCurrentRoom().getName()); } public boolean isMurderSolved() { return murderSolved; } }
True
1,564
14
1,823
17
1,868
13
1,823
17
2,197
15
false
false
false
false
false
true
225
111889_1
package org.ijsberg.iglu.util.misc; import org.ijsberg.iglu.util.io.FSFileCollection; import org.ijsberg.iglu.util.io.FileCollection; import org.ijsberg.iglu.util.io.FileFilterRuleSet; import org.ijsberg.iglu.util.io.FileSupport; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; /** * Created by J Meetsma on 4-12-2015. */ public class SearchAndReplace { /* <xs:simpleType name="RijKarakteristiekOmschrijvingType"> <xs:annotation> <xs:documentation>Waardes: Eurocity/Europese Unit Cargo/Goederen/Intercity/Intercity Expres/Internationaal/Meetwagen/Losse Loc/Losse Loc Reizigers/Leeg Materieel/Lege Motorpost/Motorpost/Onderhoud Materieel/Proef Goederen/Snelananas/Stopananas/Stoomananas Materieel/TGV/Ultrasoon/Meetwagen/Werkananas/Thalys/Sprinter/Tram */ private static Properties replacements = new Properties(); static { replacements.put("Trein","Ananas"); replacements.put("Prorail","Acme"); replacements.put("ProRail","AcMe"); replacements.put("Spoorweg", "Transportband"); replacements.put("Spoor", "Transport"); replacements.put("Goederen", "Transport"); replacements.put("Cargo", "Motion"); replacements.put("Eurocity", "Telstar"); replacements.put("Tgv", "Btw"); replacements.put("Thalys", "Aardbei"); replacements.put("Spoor", "Transport"); replacements.put("Wagen", "Krat"); replacements.put("Sprinter", "Colli"); replacements.put("Intercity", "Pallet"); replacements.put("Wissel", "Hefboom"); replacements.put("RijKarakteristiek", "Opname"); replacements.put("Reiziger", "Fruit"); replacements.put("Perron", "Steiger"); replacements.put("Baanvak", "Productielijn"); replacements.put("Kilometer", "Staffel"); replacements.put("Kilometrering", "Gradatie"); replacements.put("Dienst", "Weegschaal"); replacements.put("Ces_ovgs", "Xyz"); } private static final String BASE_DIR = "C:\\repository\\TibcoBW\\CES_OVGS_TreinNummerReeks_v1.0.2"; private static final String TARGET_DIR = "C:\\repository\\TibcoBW\\clean"; private static String[] originalNames; private static String[] destinationNames; private static void populateKeysAndValues(Properties properties) { ArrayList<String> keyList = new ArrayList<String>(); ArrayList<String> valueList = new ArrayList<String>(); for(String key : properties.stringPropertyNames()) { keyList.add(key); keyList.add(key.toLowerCase()); keyList.add(key.toUpperCase()); String value = properties.getProperty(key); valueList.add(value); valueList.add(value.toLowerCase()); valueList.add(value.toUpperCase()); } originalNames = keyList.toArray(new String[0]); destinationNames = valueList.toArray(new String[0]); } /* create new dir struct */ public static void main(String[] args) throws IOException{ populateKeysAndValues(replacements); File newDir = new File(TARGET_DIR); newDir.mkdirs(); FileSupport.emptyDirectory(newDir); FileCollection fileCollection = new FSFileCollection( BASE_DIR, new FileFilterRuleSet().setIncludeFilesWithNameMask("*.process|*.wsdl|*.xsd|*.substvar")); for(String fileName : fileCollection.getFileNames()) { String newFileName = StringSupport.replaceAll(fileName, originalNames, destinationNames); String fileContents = FileSupport.getTextFileFromFS(new File(BASE_DIR + "/" + fileName)); String newFileContents = StringSupport.replaceAll(fileContents, originalNames, destinationNames); FileSupport.saveTextFile(newFileContents, FileSupport.createFile(TARGET_DIR + "/" + newFileName)); } FileSupport.zip(newDir.listFiles()[0].getPath(), newDir.listFiles()[0].getPath() + ".zip", "*"); } }
Boncode/Iglu-Util
src/main/java/org/ijsberg/iglu/util/misc/SearchAndReplace.java
1,280
/* <xs:simpleType name="RijKarakteristiekOmschrijvingType"> <xs:annotation> <xs:documentation>Waardes: Eurocity/Europese Unit Cargo/Goederen/Intercity/Intercity Expres/Internationaal/Meetwagen/Losse Loc/Losse Loc Reizigers/Leeg Materieel/Lege Motorpost/Motorpost/Onderhoud Materieel/Proef Goederen/Snelananas/Stopananas/Stoomananas Materieel/TGV/Ultrasoon/Meetwagen/Werkananas/Thalys/Sprinter/Tram */
block_comment
nl
package org.ijsberg.iglu.util.misc; import org.ijsberg.iglu.util.io.FSFileCollection; import org.ijsberg.iglu.util.io.FileCollection; import org.ijsberg.iglu.util.io.FileFilterRuleSet; import org.ijsberg.iglu.util.io.FileSupport; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Properties; /** * Created by J Meetsma on 4-12-2015. */ public class SearchAndReplace { /* <xs:simpleType name="RijKarakteristiekOmschrijvingType"> <SUF>*/ private static Properties replacements = new Properties(); static { replacements.put("Trein","Ananas"); replacements.put("Prorail","Acme"); replacements.put("ProRail","AcMe"); replacements.put("Spoorweg", "Transportband"); replacements.put("Spoor", "Transport"); replacements.put("Goederen", "Transport"); replacements.put("Cargo", "Motion"); replacements.put("Eurocity", "Telstar"); replacements.put("Tgv", "Btw"); replacements.put("Thalys", "Aardbei"); replacements.put("Spoor", "Transport"); replacements.put("Wagen", "Krat"); replacements.put("Sprinter", "Colli"); replacements.put("Intercity", "Pallet"); replacements.put("Wissel", "Hefboom"); replacements.put("RijKarakteristiek", "Opname"); replacements.put("Reiziger", "Fruit"); replacements.put("Perron", "Steiger"); replacements.put("Baanvak", "Productielijn"); replacements.put("Kilometer", "Staffel"); replacements.put("Kilometrering", "Gradatie"); replacements.put("Dienst", "Weegschaal"); replacements.put("Ces_ovgs", "Xyz"); } private static final String BASE_DIR = "C:\\repository\\TibcoBW\\CES_OVGS_TreinNummerReeks_v1.0.2"; private static final String TARGET_DIR = "C:\\repository\\TibcoBW\\clean"; private static String[] originalNames; private static String[] destinationNames; private static void populateKeysAndValues(Properties properties) { ArrayList<String> keyList = new ArrayList<String>(); ArrayList<String> valueList = new ArrayList<String>(); for(String key : properties.stringPropertyNames()) { keyList.add(key); keyList.add(key.toLowerCase()); keyList.add(key.toUpperCase()); String value = properties.getProperty(key); valueList.add(value); valueList.add(value.toLowerCase()); valueList.add(value.toUpperCase()); } originalNames = keyList.toArray(new String[0]); destinationNames = valueList.toArray(new String[0]); } /* create new dir struct */ public static void main(String[] args) throws IOException{ populateKeysAndValues(replacements); File newDir = new File(TARGET_DIR); newDir.mkdirs(); FileSupport.emptyDirectory(newDir); FileCollection fileCollection = new FSFileCollection( BASE_DIR, new FileFilterRuleSet().setIncludeFilesWithNameMask("*.process|*.wsdl|*.xsd|*.substvar")); for(String fileName : fileCollection.getFileNames()) { String newFileName = StringSupport.replaceAll(fileName, originalNames, destinationNames); String fileContents = FileSupport.getTextFileFromFS(new File(BASE_DIR + "/" + fileName)); String newFileContents = StringSupport.replaceAll(fileContents, originalNames, destinationNames); FileSupport.saveTextFile(newFileContents, FileSupport.createFile(TARGET_DIR + "/" + newFileName)); } FileSupport.zip(newDir.listFiles()[0].getPath(), newDir.listFiles()[0].getPath() + ".zip", "*"); } }
False
957
149
1,124
164
1,120
131
1,124
164
1,272
166
false
false
false
false
false
true
4,227
26602_0
package nl.computerhuys.tabnavui;_x000D_ _x000D_ import java.util.Map;_x000D_ _x000D_ import android.app.Activity;_x000D_ import android.app.AlertDialog;_x000D_ import android.app.Dialog;_x000D_ import android.content.ComponentName;_x000D_ import android.content.DialogInterface;_x000D_ import android.content.SharedPreferences;_x000D_ import android.os.Bundle;_x000D_ import android.support.v4.app.DialogFragment;_x000D_ import android.support.v4.app.FragmentActivity;_x000D_ import android.view.LayoutInflater;_x000D_ import android.view.View;_x000D_ import android.widget.EditText;_x000D_ _x000D_ public class VraagBanenDialogFragment extends DialogFragment {_x000D_ _x000D_ private View v;_x000D_ private EditText editText1; _x000D_ private EditText editText2; _x000D_ //private ArrayList<Baan> banen;_x000D_ private int[] oldBanen;_x000D_ private int[] currentBanen;_x000D_ private SharedPreferences prefs;_x000D_ private int baan1;_x000D_ private int baan2;_x000D_ private int aantalParallel;_x000D_ _x000D_ /* public VraagBanenDialogFragment(ArrayList<Baan> banen) {_x000D_ this.baanNummers = banen;_x000D_ }_x000D_ */_x000D_ @Override_x000D_ public Dialog onCreateDialog(Bundle savedInstanceState) {_x000D_ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());_x000D_ // Restore preferences_x000D_ _x000D_ // Dit zou ook kunnen:_x000D_ // prefs = InitSpel.prefsBanen; _x000D_ // en dan verderop InitSpel.addPreference(prefs, "BAAN_01", baan1); om te bewaren_x000D_ prefs = getActivity().getSharedPreferences("numberPicker.preferences", 0);_x000D_ baan1 = prefs.getInt( "BAAN_01", 0 );_x000D_ baan2 = prefs.getInt( "BAAN_02", 0 );_x000D_ //aantalParallel = InitSpel.prefs.getInt( "AANTAL_PARALLEL", 0 );_x000D_ aantalParallel = prefs.getInt( "AANTAL_PARALLEL", 0 );_x000D_ //oldBanen = new int[InitSpel.aantalParallel];_x000D_ oldBanen = new int[aantalParallel]; _x000D_ oldBanen[0] = baan1;_x000D_ oldBanen[1] = baan2;_x000D_ _x000D_ // Get the layout inflater_x000D_ LayoutInflater inflater = getActivity().getLayoutInflater();_x000D_ _x000D_ // Inflate and set the layout for the dialog_x000D_ // Pass null as the parent view because its going in the dialog layout_x000D_ v = inflater.inflate(R.layout.vraag_banen, null);_x000D_ // velden vullen met opgeslagen waarden_x000D_ editText1 = (EditText) v.findViewById(R.id.editText1); _x000D_ editText2 = (EditText) v.findViewById(R.id.editText2); _x000D_ editText1.setText(String.valueOf(baan1));_x000D_ editText2.setText(String.valueOf(baan2));_x000D_ //editText1.setText(String.valueOf(banen.get(0).getBaanNummer()));_x000D_ //editText2.setText(String.valueOf(banen.get(1).getBaanNummer()));_x000D_ builder.setView(v)_x000D_ // Add action buttons_x000D_ .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {_x000D_ @Override_x000D_ public void onClick(DialogInterface dialog, int id) {_x000D_ _x000D_ baan1 = Integer.valueOf(editText1.getText().toString());_x000D_ baan2 = Integer.valueOf(editText2.getText().toString());_x000D_ InitSpel.setBaanNummer(0, baan1);_x000D_ InitSpel.setBaanNummer(1, baan2);_x000D_ _x000D_ // en banen nog bij de preferences op schijf opslaan._x000D_ prefs.edit()_x000D_ .putInt("BAAN_01", baan1)_x000D_ .putInt("BAAN_02", baan2)_x000D_ .commit();_x000D_ }_x000D_ })_x000D_ .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {_x000D_ public void onClick(DialogInterface dialog, int id) {_x000D_ // TODO cancel;_x000D_ }_x000D_ }); _x000D_ return builder.create();_x000D_ } _x000D_ }_x000D_
ruud00000/KegelApp
TabNavUI/src/nl/computerhuys/tabnavui/VraagBanenDialogFragment.java
1,202
//private ArrayList<Baan> banen;_x000D_
line_comment
nl
package nl.computerhuys.tabnavui;_x000D_ _x000D_ import java.util.Map;_x000D_ _x000D_ import android.app.Activity;_x000D_ import android.app.AlertDialog;_x000D_ import android.app.Dialog;_x000D_ import android.content.ComponentName;_x000D_ import android.content.DialogInterface;_x000D_ import android.content.SharedPreferences;_x000D_ import android.os.Bundle;_x000D_ import android.support.v4.app.DialogFragment;_x000D_ import android.support.v4.app.FragmentActivity;_x000D_ import android.view.LayoutInflater;_x000D_ import android.view.View;_x000D_ import android.widget.EditText;_x000D_ _x000D_ public class VraagBanenDialogFragment extends DialogFragment {_x000D_ _x000D_ private View v;_x000D_ private EditText editText1; _x000D_ private EditText editText2; _x000D_ //private ArrayList<Baan><SUF> private int[] oldBanen;_x000D_ private int[] currentBanen;_x000D_ private SharedPreferences prefs;_x000D_ private int baan1;_x000D_ private int baan2;_x000D_ private int aantalParallel;_x000D_ _x000D_ /* public VraagBanenDialogFragment(ArrayList<Baan> banen) {_x000D_ this.baanNummers = banen;_x000D_ }_x000D_ */_x000D_ @Override_x000D_ public Dialog onCreateDialog(Bundle savedInstanceState) {_x000D_ AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());_x000D_ // Restore preferences_x000D_ _x000D_ // Dit zou ook kunnen:_x000D_ // prefs = InitSpel.prefsBanen; _x000D_ // en dan verderop InitSpel.addPreference(prefs, "BAAN_01", baan1); om te bewaren_x000D_ prefs = getActivity().getSharedPreferences("numberPicker.preferences", 0);_x000D_ baan1 = prefs.getInt( "BAAN_01", 0 );_x000D_ baan2 = prefs.getInt( "BAAN_02", 0 );_x000D_ //aantalParallel = InitSpel.prefs.getInt( "AANTAL_PARALLEL", 0 );_x000D_ aantalParallel = prefs.getInt( "AANTAL_PARALLEL", 0 );_x000D_ //oldBanen = new int[InitSpel.aantalParallel];_x000D_ oldBanen = new int[aantalParallel]; _x000D_ oldBanen[0] = baan1;_x000D_ oldBanen[1] = baan2;_x000D_ _x000D_ // Get the layout inflater_x000D_ LayoutInflater inflater = getActivity().getLayoutInflater();_x000D_ _x000D_ // Inflate and set the layout for the dialog_x000D_ // Pass null as the parent view because its going in the dialog layout_x000D_ v = inflater.inflate(R.layout.vraag_banen, null);_x000D_ // velden vullen met opgeslagen waarden_x000D_ editText1 = (EditText) v.findViewById(R.id.editText1); _x000D_ editText2 = (EditText) v.findViewById(R.id.editText2); _x000D_ editText1.setText(String.valueOf(baan1));_x000D_ editText2.setText(String.valueOf(baan2));_x000D_ //editText1.setText(String.valueOf(banen.get(0).getBaanNummer()));_x000D_ //editText2.setText(String.valueOf(banen.get(1).getBaanNummer()));_x000D_ builder.setView(v)_x000D_ // Add action buttons_x000D_ .setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {_x000D_ @Override_x000D_ public void onClick(DialogInterface dialog, int id) {_x000D_ _x000D_ baan1 = Integer.valueOf(editText1.getText().toString());_x000D_ baan2 = Integer.valueOf(editText2.getText().toString());_x000D_ InitSpel.setBaanNummer(0, baan1);_x000D_ InitSpel.setBaanNummer(1, baan2);_x000D_ _x000D_ // en banen nog bij de preferences op schijf opslaan._x000D_ prefs.edit()_x000D_ .putInt("BAAN_01", baan1)_x000D_ .putInt("BAAN_02", baan2)_x000D_ .commit();_x000D_ }_x000D_ })_x000D_ .setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {_x000D_ public void onClick(DialogInterface dialog, int id) {_x000D_ // TODO cancel;_x000D_ }_x000D_ }); _x000D_ return builder.create();_x000D_ } _x000D_ }_x000D_
False
1,391
16
1,565
16
1,615
17
1,565
16
1,776
18
false
false
false
false
false
true
3,273
13783_18
package company.taskMan; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import company.BranchView; import company.taskMan.project.TaskView; import company.taskMan.task.DelegatingTask; import company.taskMan.task.DelegatingTaskProxy; import company.taskMan.task.OriginalTaskProxy; import company.taskMan.task.Task; /** * The Branch Representative is responsible for communication between branches. * When a branch tries to do something that would impact the consistency of * another branch, their representatives will negotiate the terms and * synchronize the necessary information. * * @author Tim Van Den Broecke, Joran Van de Woestijne, Vincent Van Gestel and * Eli Vangrieken * */ public class BranchRepresentative { private Map<Task,DelegatingTaskProxy> delegationProxies; private Map<Task,OriginalTaskProxy> originalProxies; private LinkedList<DelegationData> buffer; private boolean bufferMode; public BranchRepresentative() { delegationProxies = new HashMap<>(); originalProxies = new HashMap<>(); buffer = new LinkedList<DelegationData>(); bufferMode = false; } /** * Schedules a delegation for task to the branch toBranch. FromBranch * must be this representative's own branch. * If the delegation happens to its own branch, the task will end in * the Unavailable state. * If the representative is in buffer mode, the delegation will be * scheduled for later execution. If it isn't in buffer mode, the * delegation will be executed immediately. * A delegation typically happens in three steps: * 1) A local DelegatingTaskProxy is made and the task-to-delegate * is informed that it is being delegated * Note: If the delegation is to its own branch, the task * will be informed that it is no longer being delegated * 2) The remote branch creates a Delegating Task and links it to * a local OriginalTaskProxy * 3) The two proxies are linked to each other * @param task the task to be delegated * @param fromBranch the branch from where the task is delegated * @param toBranch the branch where the task is delegated to * @throws IllegalArgumentException * | If null arguments are supplied */ public void delegateTask(Task task, Branch fromBranch, Branch toBranch) throws IllegalArgumentException { if(task == null || fromBranch == null || toBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } // Delegation came back to the original branch if (toBranch == fromBranch) { delegationProxies.remove(task); task.delegate(false); } else { // Add new delegation to buffer buffer.add(new DelegationData(task, fromBranch, toBranch)); if (!bufferMode) { executeBuffer(); } } } /** * Accepts the delegation of a task from the branch delegatingBranch. It will * use newTask as a delegator that has delProxy as a remote proxy (in the * original branch). It will create a local Original Task Proxy that is linked * with delProxy so that communication is synchronized and ready for use. * @param delProxy the delegatingTaskProxy for the original task * @param newTask the task that is actually delegating for the original task * @param delegatingBranch the branch that is delegating the original task * @throws IllegalArgumentException * | If the supplied parameters are null */ public void delegateAccept(DelegatingTaskProxy delProxy, DelegatingTask newTask, Branch delegatingBranch) throws IllegalArgumentException { if(delProxy == null || newTask == null || delegatingBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } OriginalTaskProxy origiProxy = new OriginalTaskProxy(newTask, delegatingBranch); delProxy.link(origiProxy); // origiProxy.link(delProxy); originalProxies.put(newTask, origiProxy); } /** * Executes the delegations that were scheduled for executuion in the buffer. * 1) If a delegating task is being delegated, this method will release the delegation * form this branch and give the delegation to the branch of the original task. That * branch will then schedule the delegation that will result in case 2) * 2) If an already-delegated task is being delegated, this method will reset the * Task to a non-delegated state and its delegatingTaskProxy is removed. The * delegation is then rescheduled and will result in case 3) * 3) If A task hasn't been delegated before, this method will create a new delegatingTaskProxy * for the task and tell the toBranch to accept the delegation. * */ private void executeBuffer(){ // For every delegation ready in the buffer while (!buffer.isEmpty()) { DelegationData deleg = buffer.poll(); // Next delegation to commit (a TO request) Task task = deleg.delegatedTask; // Task to delegate Branch fromBranch = deleg.originalBranch; // Branch to delegate FROM Branch toBranch = deleg.newBranch; // Branch to delegate TO if (originalProxies.containsKey(task)) { // A. this task is already delegating another task OriginalTaskProxy origiProxy = originalProxies.get(task); Branch origiFromBranch = origiProxy.getOriginalBranch().get(); // A.1 Remove previous delegation information originalProxies.remove(task); fromBranch.removeDelegatedTask(task); // A.2 (re-)delegate the original task in its respective delegator origiFromBranch.delegateTask(origiProxy.getOriginalTask(), toBranch); } else if(delegationProxies.containsKey(task)) { // B. The original task is being re-delegated: remove its previous delegation and schedule a new one DelegatingTaskProxy delProxy = delegationProxies.get(task); Task origiTask = delProxy.getTask(); origiTask.delegate(false); delegationProxies.remove(task); buffer.add(new DelegationData(task, fromBranch, toBranch)); } else { // C. The task is delegated for the first time DelegatingTaskProxy delProxy = new DelegatingTaskProxy(task, fromBranch); toBranch.delegateAccept(delProxy); delegationProxies.put(task, delProxy); task.delegate(true); } } } /** * Sets the buffer mode of this representative. If set to false, it will * execute its scheduled delegations. * @param active whether the buffer should be set to active (true) or inactive (false) */ public void setBufferMode(boolean active) { bufferMode = active; if(!bufferMode) { executeBuffer(); } } /** * Returns the BranchView of the Branch that is repsonsible for task, * IF it is being delegated * @param task the task of which to get the responsible branch * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<BranchView> getResponsibleBranch(Task task) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(task)); if(delProxy.isPresent()) { if(delProxy.get().getDelegatingBranch().isPresent()) { return Optional.of(new BranchView(delProxy.get().getDelegatingBranch().get())); } else { return Optional.empty(); } } else { //kijk eens in de buffer Iterator<DelegationData> i = buffer.iterator(); DelegationData d; while(i.hasNext()) { d = i.next(); if(d.delegatedTask == task) { return Optional.of(new BranchView(d.newBranch)); } } return Optional.empty(); } } /** * Returns the TaskView of the Task that is delegating task, * IF it is being delegated * @param t the task of which to get the delegating task * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<TaskView> getDelegatingTask(Task t) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(t)); if(delProxy.isPresent()) { return Optional.of(new TaskView(delProxy.get().getDelegatingTask())); } else { return Optional.empty(); } } private class DelegationData { private Task delegatedTask; private Branch originalBranch, newBranch; private DelegationData(Task task,Branch origBranch, Branch newBranch){ delegatedTask = task; originalBranch = origBranch; this.newBranch = newBranch; } } /** * @return the current Task-Proxy pairings (original) */ protected Map<Task, OriginalTaskProxy> getOriginalProxies() { return originalProxies; } /** * @return the current Task-Proxy pairings (delegating) */ protected Map<Task, DelegatingTaskProxy> getDelegatingProxies() { return delegationProxies; } /** * A method to allow the Branch to offer new task and (original) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerOriginalTaskProxies(Map<Task, OriginalTaskProxy> proxies) { originalProxies = proxies; } /** * A method to allow the Branch to offer new task and (delegating) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerDelegatingTaskProxies( Map<Task, DelegatingTaskProxy> proxies) { delegationProxies = proxies; } }
jorreee/SWOP
src/company/taskMan/BranchRepresentative.java
2,833
//kijk eens in de buffer
line_comment
nl
package company.taskMan; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Optional; import company.BranchView; import company.taskMan.project.TaskView; import company.taskMan.task.DelegatingTask; import company.taskMan.task.DelegatingTaskProxy; import company.taskMan.task.OriginalTaskProxy; import company.taskMan.task.Task; /** * The Branch Representative is responsible for communication between branches. * When a branch tries to do something that would impact the consistency of * another branch, their representatives will negotiate the terms and * synchronize the necessary information. * * @author Tim Van Den Broecke, Joran Van de Woestijne, Vincent Van Gestel and * Eli Vangrieken * */ public class BranchRepresentative { private Map<Task,DelegatingTaskProxy> delegationProxies; private Map<Task,OriginalTaskProxy> originalProxies; private LinkedList<DelegationData> buffer; private boolean bufferMode; public BranchRepresentative() { delegationProxies = new HashMap<>(); originalProxies = new HashMap<>(); buffer = new LinkedList<DelegationData>(); bufferMode = false; } /** * Schedules a delegation for task to the branch toBranch. FromBranch * must be this representative's own branch. * If the delegation happens to its own branch, the task will end in * the Unavailable state. * If the representative is in buffer mode, the delegation will be * scheduled for later execution. If it isn't in buffer mode, the * delegation will be executed immediately. * A delegation typically happens in three steps: * 1) A local DelegatingTaskProxy is made and the task-to-delegate * is informed that it is being delegated * Note: If the delegation is to its own branch, the task * will be informed that it is no longer being delegated * 2) The remote branch creates a Delegating Task and links it to * a local OriginalTaskProxy * 3) The two proxies are linked to each other * @param task the task to be delegated * @param fromBranch the branch from where the task is delegated * @param toBranch the branch where the task is delegated to * @throws IllegalArgumentException * | If null arguments are supplied */ public void delegateTask(Task task, Branch fromBranch, Branch toBranch) throws IllegalArgumentException { if(task == null || fromBranch == null || toBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } // Delegation came back to the original branch if (toBranch == fromBranch) { delegationProxies.remove(task); task.delegate(false); } else { // Add new delegation to buffer buffer.add(new DelegationData(task, fromBranch, toBranch)); if (!bufferMode) { executeBuffer(); } } } /** * Accepts the delegation of a task from the branch delegatingBranch. It will * use newTask as a delegator that has delProxy as a remote proxy (in the * original branch). It will create a local Original Task Proxy that is linked * with delProxy so that communication is synchronized and ready for use. * @param delProxy the delegatingTaskProxy for the original task * @param newTask the task that is actually delegating for the original task * @param delegatingBranch the branch that is delegating the original task * @throws IllegalArgumentException * | If the supplied parameters are null */ public void delegateAccept(DelegatingTaskProxy delProxy, DelegatingTask newTask, Branch delegatingBranch) throws IllegalArgumentException { if(delProxy == null || newTask == null || delegatingBranch == null) { throw new IllegalArgumentException("Parameters cannot be null"); } OriginalTaskProxy origiProxy = new OriginalTaskProxy(newTask, delegatingBranch); delProxy.link(origiProxy); // origiProxy.link(delProxy); originalProxies.put(newTask, origiProxy); } /** * Executes the delegations that were scheduled for executuion in the buffer. * 1) If a delegating task is being delegated, this method will release the delegation * form this branch and give the delegation to the branch of the original task. That * branch will then schedule the delegation that will result in case 2) * 2) If an already-delegated task is being delegated, this method will reset the * Task to a non-delegated state and its delegatingTaskProxy is removed. The * delegation is then rescheduled and will result in case 3) * 3) If A task hasn't been delegated before, this method will create a new delegatingTaskProxy * for the task and tell the toBranch to accept the delegation. * */ private void executeBuffer(){ // For every delegation ready in the buffer while (!buffer.isEmpty()) { DelegationData deleg = buffer.poll(); // Next delegation to commit (a TO request) Task task = deleg.delegatedTask; // Task to delegate Branch fromBranch = deleg.originalBranch; // Branch to delegate FROM Branch toBranch = deleg.newBranch; // Branch to delegate TO if (originalProxies.containsKey(task)) { // A. this task is already delegating another task OriginalTaskProxy origiProxy = originalProxies.get(task); Branch origiFromBranch = origiProxy.getOriginalBranch().get(); // A.1 Remove previous delegation information originalProxies.remove(task); fromBranch.removeDelegatedTask(task); // A.2 (re-)delegate the original task in its respective delegator origiFromBranch.delegateTask(origiProxy.getOriginalTask(), toBranch); } else if(delegationProxies.containsKey(task)) { // B. The original task is being re-delegated: remove its previous delegation and schedule a new one DelegatingTaskProxy delProxy = delegationProxies.get(task); Task origiTask = delProxy.getTask(); origiTask.delegate(false); delegationProxies.remove(task); buffer.add(new DelegationData(task, fromBranch, toBranch)); } else { // C. The task is delegated for the first time DelegatingTaskProxy delProxy = new DelegatingTaskProxy(task, fromBranch); toBranch.delegateAccept(delProxy); delegationProxies.put(task, delProxy); task.delegate(true); } } } /** * Sets the buffer mode of this representative. If set to false, it will * execute its scheduled delegations. * @param active whether the buffer should be set to active (true) or inactive (false) */ public void setBufferMode(boolean active) { bufferMode = active; if(!bufferMode) { executeBuffer(); } } /** * Returns the BranchView of the Branch that is repsonsible for task, * IF it is being delegated * @param task the task of which to get the responsible branch * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<BranchView> getResponsibleBranch(Task task) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(task)); if(delProxy.isPresent()) { if(delProxy.get().getDelegatingBranch().isPresent()) { return Optional.of(new BranchView(delProxy.get().getDelegatingBranch().get())); } else { return Optional.empty(); } } else { //kijk eens<SUF> Iterator<DelegationData> i = buffer.iterator(); DelegationData d; while(i.hasNext()) { d = i.next(); if(d.delegatedTask == task) { return Optional.of(new BranchView(d.newBranch)); } } return Optional.empty(); } } /** * Returns the TaskView of the Task that is delegating task, * IF it is being delegated * @param t the task of which to get the delegating task * @return * | BranchView of the task's responsible branch * | empty Optional otherwise */ public Optional<TaskView> getDelegatingTask(Task t) { Optional<DelegatingTaskProxy> delProxy = Optional.ofNullable(delegationProxies.get(t)); if(delProxy.isPresent()) { return Optional.of(new TaskView(delProxy.get().getDelegatingTask())); } else { return Optional.empty(); } } private class DelegationData { private Task delegatedTask; private Branch originalBranch, newBranch; private DelegationData(Task task,Branch origBranch, Branch newBranch){ delegatedTask = task; originalBranch = origBranch; this.newBranch = newBranch; } } /** * @return the current Task-Proxy pairings (original) */ protected Map<Task, OriginalTaskProxy> getOriginalProxies() { return originalProxies; } /** * @return the current Task-Proxy pairings (delegating) */ protected Map<Task, DelegatingTaskProxy> getDelegatingProxies() { return delegationProxies; } /** * A method to allow the Branch to offer new task and (original) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerOriginalTaskProxies(Map<Task, OriginalTaskProxy> proxies) { originalProxies = proxies; } /** * A method to allow the Branch to offer new task and (delegating) proxy * pairings to the representative * * @param proxies * | The new task-proxy pairings present in the system */ protected void offerDelegatingTaskProxies( Map<Task, DelegatingTaskProxy> proxies) { delegationProxies = proxies; } }
True
2,302
7
2,493
8
2,551
6
2,493
8
3,041
8
false
false
false
false
false
true
3,459
160881_4
/** * PacketWrapper - ProtocolLib wrappers for Minecraft packets * Copyright (C) dmulloy2 <http://dmulloy2.net> * Copyright (C) Kristian S. Strangeland * * 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 fr.leomelki.com.comphenix.packetwrapper; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.EnumWrappers.ScoreboardAction; public class WrapperPlayServerScoreboardScore extends AbstractPacket { public static final PacketType TYPE = PacketType.Play.Server.SCOREBOARD_SCORE; public WrapperPlayServerScoreboardScore() { super(new PacketContainer(TYPE), TYPE); handle.getModifier().writeDefaults(); } public WrapperPlayServerScoreboardScore(PacketContainer packet) { super(packet, TYPE); } /** * Retrieve Score name. * <p> * Notes: the name of the score to be updated or removed. * * @return The current Score name */ public String getScoreName() { return handle.getStrings().read(0); } /** * Set Score name. * * @param value - new value. */ public void setScoreName(String value) { handle.getStrings().write(0, value); } /** * Retrieve Objective Name. * <p> * Notes: the name of the objective the score belongs to. * * @return The current Objective Name */ public String getObjectiveName() { return handle.getStrings().read(1); } /** * Set Objective Name. * * @param value - new value. */ public void setObjectiveName(String value) { handle.getStrings().write(1, value); } /** * Retrieve Value. * <p> * Notes: the score to be displayed next to the entry. Only sent when * Update/Remove does not equal 1. * * @return The current Value */ public int getValue() { return handle.getIntegers().read(0); } /** * Set Value. * * @param value - new value. */ public void setValue(int value) { handle.getIntegers().write(0, value); } public ScoreboardAction getAction() { return handle.getScoreboardActions().read(0); } public void setScoreboardAction(ScoreboardAction value) { handle.getScoreboardActions().write(0, value); } }
leomelki/LoupGarou
src/main/java/fr/leomelki/com/comphenix/packetwrapper/WrapperPlayServerScoreboardScore.java
876
/** * Set Objective Name. * * @param value - new value. */
block_comment
nl
/** * PacketWrapper - ProtocolLib wrappers for Minecraft packets * Copyright (C) dmulloy2 <http://dmulloy2.net> * Copyright (C) Kristian S. Strangeland * * 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 fr.leomelki.com.comphenix.packetwrapper; import com.comphenix.protocol.PacketType; import com.comphenix.protocol.events.PacketContainer; import com.comphenix.protocol.wrappers.EnumWrappers.ScoreboardAction; public class WrapperPlayServerScoreboardScore extends AbstractPacket { public static final PacketType TYPE = PacketType.Play.Server.SCOREBOARD_SCORE; public WrapperPlayServerScoreboardScore() { super(new PacketContainer(TYPE), TYPE); handle.getModifier().writeDefaults(); } public WrapperPlayServerScoreboardScore(PacketContainer packet) { super(packet, TYPE); } /** * Retrieve Score name. * <p> * Notes: the name of the score to be updated or removed. * * @return The current Score name */ public String getScoreName() { return handle.getStrings().read(0); } /** * Set Score name. * * @param value - new value. */ public void setScoreName(String value) { handle.getStrings().write(0, value); } /** * Retrieve Objective Name. * <p> * Notes: the name of the objective the score belongs to. * * @return The current Objective Name */ public String getObjectiveName() { return handle.getStrings().read(1); } /** * Set Objective Name.<SUF>*/ public void setObjectiveName(String value) { handle.getStrings().write(1, value); } /** * Retrieve Value. * <p> * Notes: the score to be displayed next to the entry. Only sent when * Update/Remove does not equal 1. * * @return The current Value */ public int getValue() { return handle.getIntegers().read(0); } /** * Set Value. * * @param value - new value. */ public void setValue(int value) { handle.getIntegers().write(0, value); } public ScoreboardAction getAction() { return handle.getScoreboardActions().read(0); } public void setScoreboardAction(ScoreboardAction value) { handle.getScoreboardActions().write(0, value); } }
False
682
21
781
20
812
25
781
20
921
26
false
false
false
false
false
true
845
1652_4
package be.pxl.h4.exoef1; /*Extra oefening 1 * * Geef 2 getallen in via het toetsenbord. Maak een afdruk als volgt: * het kleinste getal is ... * Het kwadraat van het kleinste getal is ...*/ import java.util.Scanner; public class H4ExOef1 { public static void main(String[] args) { //Scanner en variabelen aanmaken Scanner keyboard = new Scanner(System.in); int a, b, kleinste_getal, kwadraat_kleinste_getal; //Input vragen van de gebruiker System.out.println("Getal a: "); a = keyboard.nextInt(); System.out.println("Getal b: "); b = keyboard.nextInt(); //Bepalen welk getal het kleinste is if (a > b) { kleinste_getal = b; } else { kleinste_getal = a; } //Kwadraat berekenen en kleinste getal en zijn kwadraat uitrekenen kwadraat_kleinste_getal = kleinste_getal * kleinste_getal; // Opgelost zonder de math klasse - normaal wordt die voor deze berekening gebruikt. System.out.println("Het kleinste getal is " + kleinste_getal); System.out.println("Het kwadraat van het kleinste getal is " + kwadraat_kleinste_getal); keyboard.close(); } }
JoachimVeulemans/PXL-DIGITAL
PXL_DIGITAL_JAAR_1/Programming Basics/Oplossingen Oefeningen/H4/exoef1/H4ExOef1.java
421
//Kwadraat berekenen en kleinste getal en zijn kwadraat uitrekenen
line_comment
nl
package be.pxl.h4.exoef1; /*Extra oefening 1 * * Geef 2 getallen in via het toetsenbord. Maak een afdruk als volgt: * het kleinste getal is ... * Het kwadraat van het kleinste getal is ...*/ import java.util.Scanner; public class H4ExOef1 { public static void main(String[] args) { //Scanner en variabelen aanmaken Scanner keyboard = new Scanner(System.in); int a, b, kleinste_getal, kwadraat_kleinste_getal; //Input vragen van de gebruiker System.out.println("Getal a: "); a = keyboard.nextInt(); System.out.println("Getal b: "); b = keyboard.nextInt(); //Bepalen welk getal het kleinste is if (a > b) { kleinste_getal = b; } else { kleinste_getal = a; } //Kwadraat berekenen<SUF> kwadraat_kleinste_getal = kleinste_getal * kleinste_getal; // Opgelost zonder de math klasse - normaal wordt die voor deze berekening gebruikt. System.out.println("Het kleinste getal is " + kleinste_getal); System.out.println("Het kwadraat van het kleinste getal is " + kwadraat_kleinste_getal); keyboard.close(); } }
True
362
24
433
25
388
20
433
25
455
23
false
false
false
false
false
true