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
2,188
73378_4
package staticfactory; import java.util.ArrayList; import java.util.Iterator; // instance controlled class public class ManagedResource { static ArrayList<ManagedResource> instances = new ArrayList<>(); static final int MAX_POOL_SIZE = 10; private ManagedResource () { System.out.println("Creating managed resource number " +instances.size()); } private boolean isReady() { System.out.println("Checking whether this resource is ready."); if (Math.random() < .5) { System.out.println("Resource busy; try again later."); return false; } else { System.out.println("Resource ready to be used again."); return true; } } static ManagedResource getInstance() { // eerst kun je bijvoorbeeld kijken of er nog slots te vergeven zijn. if (instances.size()<=MAX_POOL_SIZE) { ManagedResource foo = new ManagedResource(); instances.add(foo); return foo; } // in het andere geval zou je iets moeten doen met // lock and wait; en geef je de eerste instantie terug die niets te doen heeft // (dit is uiteraard een slechts realisatie, alleen voor de demonstratie) boolean found = false; ManagedResource tmp=null;; while (!found) { Iterator<ManagedResource> itr = instances.iterator(); while(itr.hasNext()) { tmp = itr.next(); if (tmp.isReady()) { found = true; break; } } } return tmp; } }
bart314/practicum.2.3
week4/staticfactory/ManagedResource.java
433
// (dit is uiteraard een slechts realisatie, alleen voor de demonstratie)
line_comment
nl
package staticfactory; import java.util.ArrayList; import java.util.Iterator; // instance controlled class public class ManagedResource { static ArrayList<ManagedResource> instances = new ArrayList<>(); static final int MAX_POOL_SIZE = 10; private ManagedResource () { System.out.println("Creating managed resource number " +instances.size()); } private boolean isReady() { System.out.println("Checking whether this resource is ready."); if (Math.random() < .5) { System.out.println("Resource busy; try again later."); return false; } else { System.out.println("Resource ready to be used again."); return true; } } static ManagedResource getInstance() { // eerst kun je bijvoorbeeld kijken of er nog slots te vergeven zijn. if (instances.size()<=MAX_POOL_SIZE) { ManagedResource foo = new ManagedResource(); instances.add(foo); return foo; } // in het andere geval zou je iets moeten doen met // lock and wait; en geef je de eerste instantie terug die niets te doen heeft // (dit is<SUF> boolean found = false; ManagedResource tmp=null;; while (!found) { Iterator<ManagedResource> itr = instances.iterator(); while(itr.hasNext()) { tmp = itr.next(); if (tmp.isReady()) { found = true; break; } } } return tmp; } }
False
338
21
414
23
395
17
414
23
487
22
false
false
false
false
false
true
1,030
172967_3
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hellotvxlet; import org.havi.ui.*; import java.awt.*; import org.dvb.ui.*; /** * * @author student */ public class Sprite extends HComponent { private Image spaceship; private MediaTracker mtrack; //plaats en lovatie instellen in de constructor public Sprite(String file, int x, int y) { spaceship = this.getToolkit().getImage(file); mtrack = new MediaTracker(this); mtrack.addImage(spaceship, 0); try { mtrack.waitForAll(); // wacht tot alle bitmaps geladen zijn } catch (InterruptedException ex) { ex.printStackTrace(); } this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap } //paint methode overschrijven public void paint(Graphics g) { g.drawImage(spaceship, 0, 0, null); } public void Verplaats(int x, int y) { this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this)); } }
MTA-Digital-Broadcast-2/K-De-Maeyer-Didier-Schuddinck-Sam-Project-MHP
Didier De Maeyer/blz47/Oef1/HelloTVXlet/src/hellotvxlet/Sprite.java
367
// wacht tot alle bitmaps geladen zijn
line_comment
nl
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hellotvxlet; import org.havi.ui.*; import java.awt.*; import org.dvb.ui.*; /** * * @author student */ public class Sprite extends HComponent { private Image spaceship; private MediaTracker mtrack; //plaats en lovatie instellen in de constructor public Sprite(String file, int x, int y) { spaceship = this.getToolkit().getImage(file); mtrack = new MediaTracker(this); mtrack.addImage(spaceship, 0); try { mtrack.waitForAll(); // wacht tot<SUF> } catch (InterruptedException ex) { ex.printStackTrace(); } this.setBounds(x, y, spaceship.getWidth(null), spaceship.getHeight(null)); //opgeven plaats en afmetingen bitmap } //paint methode overschrijven public void paint(Graphics g) { g.drawImage(spaceship, 0, 0, null); } public void Verplaats(int x, int y) { this.setBounds(x, y, spaceship.getWidth(this), spaceship.getHeight(this)); } }
True
271
10
313
11
330
8
313
11
369
10
false
false
false
false
false
true
600
11641_4
import java.util.ArrayList;_x000D_ _x000D_ /**_x000D_ * Presentation houdt de slides in de presentatie bij._x000D_ * <p>_x000D_ * In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, [email protected]_x000D_ * @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ // Verandering: Presentation wordt een Observable_x000D_ public class Presentation {_x000D_ private String showTitle; // de titel van de presentatie_x000D_ private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_ private int currentSlideNumber = 0; // het slidenummer van de huidige Slide_x000D_ // Verandering: we kennen slideViewComponent niet meer direct_x000D_ // private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_ _x000D_ public Presentation() {_x000D_ // Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_ //slideViewComponent = null;_x000D_ clear();_x000D_ }_x000D_ _x000D_ // Methode die wordt gebruikt door de Controller_x000D_ // om te bepalen wat er getoond wordt._x000D_ public int getSize() {_x000D_ return showList.size();_x000D_ }_x000D_ _x000D_ public String getTitle() {_x000D_ return showTitle;_x000D_ }_x000D_ _x000D_ public void setTitle(String nt) {_x000D_ showTitle = nt;_x000D_ }_x000D_ _x000D_ // Verandering: deze methode hebben we niet meer nodig_x000D_ // public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_ // this.slideViewComponent = slideViewerComponent;_x000D_ // }_x000D_ _x000D_ // geef het nummer van de huidige slide_x000D_ public int getSlideNumber() {_x000D_ return currentSlideNumber;_x000D_ }_x000D_ _x000D_ // verander het huidige-slide-nummer en laat het aan het window weten._x000D_ public void setSlideNumber(int number) {_x000D_ currentSlideNumber = number;_x000D_ // Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_ //if (slideViewComponent != null) {_x000D_ // slideViewComponent.update(this, getCurrentSlide());_x000D_ //}_x000D_ }_x000D_ _x000D_ // Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_ void clear() {_x000D_ showList = new ArrayList<Slide>();_x000D_ setTitle("New presentation");_x000D_ setSlideNumber(-1);_x000D_ }_x000D_ _x000D_ // Voeg een slide toe aan de presentatie_x000D_ public void append(Slide slide) {_x000D_ showList.add(slide);_x000D_ }_x000D_ _x000D_ // Geef een slide met een bepaald slidenummer_x000D_ public Slide getSlide(int number) {_x000D_ if (number < 0 || number >= getSize()){_x000D_ return null;_x000D_ }_x000D_ return (Slide)showList.get(number);_x000D_ }_x000D_ _x000D_ // Geef de huidige Slide_x000D_ public Slide getCurrentSlide() {_x000D_ return getSlide(currentSlideNumber);_x000D_ }_x000D_ }_x000D_
GertSallaerts/jabbertest
Presentation.java
935
// het slidenummer van de huidige Slide_x000D_
line_comment
nl
import java.util.ArrayList;_x000D_ _x000D_ /**_x000D_ * Presentation houdt de slides in de presentatie bij._x000D_ * <p>_x000D_ * In the Presentation's world, page numbers go from 0 to n-1 * <p>_x000D_ * This program is distributed under the terms of the accompanying_x000D_ * COPYRIGHT.txt file (which is NOT the GNU General Public License)._x000D_ * Please read it. Your use of the software constitutes acceptance_x000D_ * of the terms in the COPYRIGHT.txt file._x000D_ * @author Ian F. Darwin, [email protected]_x000D_ * @version $Id: Presentation.java,v 1.1 2002/12/17 Gert Florijn_x000D_ * @version $Id: Presentation.java,v 1.2 2003/11/19 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.3 2004/08/17 Sylvia Stuurman_x000D_ * @version $Id: Presentation.java,v 1.4 2007/07/16 Sylvia Stuurman_x000D_ */_x000D_ _x000D_ // Verandering: Presentation wordt een Observable_x000D_ public class Presentation {_x000D_ private String showTitle; // de titel van de presentatie_x000D_ private ArrayList<Slide> showList = null; // een ArrayList met de Slides_x000D_ private int currentSlideNumber = 0; // het slidenummer<SUF> // Verandering: we kennen slideViewComponent niet meer direct_x000D_ // private SlideViewerComponent slideViewComponent = null; // de viewcomponent voor de Slides_x000D_ _x000D_ public Presentation() {_x000D_ // Verandering: Presentation heeft slideViewComponent nu niet meer als attribuut_x000D_ //slideViewComponent = null;_x000D_ clear();_x000D_ }_x000D_ _x000D_ // Methode die wordt gebruikt door de Controller_x000D_ // om te bepalen wat er getoond wordt._x000D_ public int getSize() {_x000D_ return showList.size();_x000D_ }_x000D_ _x000D_ public String getTitle() {_x000D_ return showTitle;_x000D_ }_x000D_ _x000D_ public void setTitle(String nt) {_x000D_ showTitle = nt;_x000D_ }_x000D_ _x000D_ // Verandering: deze methode hebben we niet meer nodig_x000D_ // public void setShowView(SlideViewerComponent slideViewerComponent) {_x000D_ // this.slideViewComponent = slideViewerComponent;_x000D_ // }_x000D_ _x000D_ // geef het nummer van de huidige slide_x000D_ public int getSlideNumber() {_x000D_ return currentSlideNumber;_x000D_ }_x000D_ _x000D_ // verander het huidige-slide-nummer en laat het aan het window weten._x000D_ public void setSlideNumber(int number) {_x000D_ currentSlideNumber = number;_x000D_ // Verandering: het updaten van de SlideViewerComponent gebeurt nu via het Observer patroon_x000D_ //if (slideViewComponent != null) {_x000D_ // slideViewComponent.update(this, getCurrentSlide());_x000D_ //}_x000D_ }_x000D_ _x000D_ // Verwijder de presentatie, om klaar te zijn voor de volgende_x000D_ void clear() {_x000D_ showList = new ArrayList<Slide>();_x000D_ setTitle("New presentation");_x000D_ setSlideNumber(-1);_x000D_ }_x000D_ _x000D_ // Voeg een slide toe aan de presentatie_x000D_ public void append(Slide slide) {_x000D_ showList.add(slide);_x000D_ }_x000D_ _x000D_ // Geef een slide met een bepaald slidenummer_x000D_ public Slide getSlide(int number) {_x000D_ if (number < 0 || number >= getSize()){_x000D_ return null;_x000D_ }_x000D_ return (Slide)showList.get(number);_x000D_ }_x000D_ _x000D_ // Geef de huidige Slide_x000D_ public Slide getCurrentSlide() {_x000D_ return getSlide(currentSlideNumber);_x000D_ }_x000D_ }_x000D_
True
1,280
17
1,460
19
1,393
16
1,460
19
1,552
20
false
false
false
false
false
true
2,850
65568_3
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.spellchecker.xml; import com.intellij.codeInspection.SuppressQuickFix; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.templateLanguages.TemplateLanguage; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.*; import com.intellij.spellchecker.inspections.PlainTextSplitter; import com.intellij.spellchecker.inspections.Splitter; import com.intellij.spellchecker.tokenizer.LanguageSpellchecking; import com.intellij.spellchecker.tokenizer.SuppressibleSpellcheckingStrategy; import com.intellij.spellchecker.tokenizer.TokenConsumer; import com.intellij.spellchecker.tokenizer.Tokenizer; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomUtil; import com.intellij.xml.util.XmlEnumeratedValueReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; public class XmlSpellcheckingStrategy extends SuppressibleSpellcheckingStrategy { private final Tokenizer<? extends PsiElement> myXmlTextTokenizer = createTextTokenizer(); private final Tokenizer<? extends PsiElement> myXmlAttributeTokenizer = createAttributeValueTokenizer(); @Override public @NotNull Tokenizer getTokenizer(PsiElement element) { if (element instanceof XmlText) { return myXmlTextTokenizer; } if (element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS && !isXmlDataCharactersParentHandledByItsStrategy(element.getParent())) { // Special case for all other XML_DATA_CHARACTERS, which are not handled through parent PSI if (isInTemplateLanguageFile(element)) return EMPTY_TOKENIZER; return TEXT_TOKENIZER; } if (element instanceof XmlAttributeValue) { return myXmlAttributeTokenizer; } return super.getTokenizer(element); } @Override public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String name) { DomElement domElement = DomUtil.getDomElement(element); if (domElement != null) { if (domElement.getAnnotation(NoSpellchecking.class) != null) { return true; } } return false; } @Override public SuppressQuickFix[] getSuppressActions(@NotNull PsiElement element, @NotNull String name) { return SuppressQuickFix.EMPTY_ARRAY; } protected Tokenizer<? extends PsiElement> createAttributeValueTokenizer() { return new XmlAttributeValueTokenizer(PlainTextSplitter.getInstance()); } private boolean isXmlDataCharactersParentHandledByItsStrategy(@Nullable PsiElement parent) { if (parent == null) return false; var strategy = ContainerUtil.findInstance( LanguageSpellchecking.INSTANCE.allForLanguage(parent.getLanguage()), XmlSpellcheckingStrategy.class); return strategy != null ? strategy.isXmlDataCharactersParentHandled(parent) : isXmlDataCharactersParentHandled(parent); } protected boolean isXmlDataCharactersParentHandled(@NotNull PsiElement parent) { return parent instanceof XmlText || parent.getNode().getElementType() == XmlElementType.XML_CDATA; } protected boolean isInTemplateLanguageFile(PsiElement element) { PsiFile file = element.getContainingFile(); return file == null || file.getLanguage() instanceof TemplateLanguage; } protected Tokenizer<? extends PsiElement> createTextTokenizer() { return new XmlTextTokenizer(PlainTextSplitter.getInstance()); } protected abstract static class XmlTextContentTokenizer<T extends XmlElement> extends XmlTokenizerBase<T> { public XmlTextContentTokenizer(Splitter splitter) { super(splitter); } protected abstract boolean isContentToken(IElementType tokenType); @Override protected @NotNull List<@NotNull TextRange> getSpellcheckOuterContentRanges(@NotNull T element) { List<TextRange> result = new SmartList<>(super.getSpellcheckOuterContentRanges(element)); element.acceptChildren(new XmlElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { if (element.getNode().getElementType() == XmlElementType.XML_CDATA) { element.acceptChildren(this); } else if (!(element instanceof LeafPsiElement) || !isContentToken(element.getNode().getElementType())) { result.add(element.getTextRangeInParent()); } } }); return result; } } protected static class XmlTextTokenizer extends XmlTextContentTokenizer<XmlText> { public XmlTextTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_DATA_CHARACTERS || tokenType == XmlTokenType.XML_CDATA_START || tokenType == XmlTokenType.XML_CDATA_END || XmlTokenType.WHITESPACES.contains(tokenType); } } protected static class XmlAttributeValueTokenizer extends XmlTextContentTokenizer<XmlAttributeValue> { public XmlAttributeValueTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER || XmlTokenType.WHITESPACES.contains(tokenType); } @Override protected @NotNull List<@NotNull SpellcheckRange> getSpellcheckRanges(@NotNull XmlAttributeValue element) { TextRange range = ElementManipulators.getValueTextRange(element); if (range.isEmpty()) return emptyList(); String text = ElementManipulators.getValueText(element); return singletonList(new SpellcheckRange(text, false, range.getStartOffset(), TextRange.allOf(text))); } @Override public void tokenize(@NotNull XmlAttributeValue element, @NotNull TokenConsumer consumer) { PsiReference[] references = element.getReferences(); for (PsiReference reference : references) { if (reference instanceof XmlEnumeratedValueReference) { if (reference.resolve() != null) { // this is probably valid enumeration value from XSD/RNG schema, such as SVG return; } } } final String valueTextTrimmed = element.getValue().trim(); // do not inspect colors like #00aaFF if (valueTextTrimmed.startsWith("#") && valueTextTrimmed.length() <= 9 && isHexString(valueTextTrimmed.substring(1))) { return; } super.tokenize(element, consumer); } private static boolean isHexString(final String s) { for (int i = 0; i < s.length(); i++) { if (!StringUtil.isHexDigit(s.charAt(i))) { return false; } } return true; } } }
google/intellij-community
xml/impl/src/com/intellij/spellchecker/xml/XmlSpellcheckingStrategy.java
2,180
// do not inspect colors like #00aaFF
line_comment
nl
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.spellchecker.xml; import com.intellij.codeInspection.SuppressQuickFix; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.intellij.psi.templateLanguages.TemplateLanguage; import com.intellij.psi.tree.IElementType; import com.intellij.psi.xml.*; import com.intellij.spellchecker.inspections.PlainTextSplitter; import com.intellij.spellchecker.inspections.Splitter; import com.intellij.spellchecker.tokenizer.LanguageSpellchecking; import com.intellij.spellchecker.tokenizer.SuppressibleSpellcheckingStrategy; import com.intellij.spellchecker.tokenizer.TokenConsumer; import com.intellij.spellchecker.tokenizer.Tokenizer; import com.intellij.util.SmartList; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xml.DomElement; import com.intellij.util.xml.DomUtil; import com.intellij.xml.util.XmlEnumeratedValueReference; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; public class XmlSpellcheckingStrategy extends SuppressibleSpellcheckingStrategy { private final Tokenizer<? extends PsiElement> myXmlTextTokenizer = createTextTokenizer(); private final Tokenizer<? extends PsiElement> myXmlAttributeTokenizer = createAttributeValueTokenizer(); @Override public @NotNull Tokenizer getTokenizer(PsiElement element) { if (element instanceof XmlText) { return myXmlTextTokenizer; } if (element instanceof XmlToken && ((XmlToken)element).getTokenType() == XmlTokenType.XML_DATA_CHARACTERS && !isXmlDataCharactersParentHandledByItsStrategy(element.getParent())) { // Special case for all other XML_DATA_CHARACTERS, which are not handled through parent PSI if (isInTemplateLanguageFile(element)) return EMPTY_TOKENIZER; return TEXT_TOKENIZER; } if (element instanceof XmlAttributeValue) { return myXmlAttributeTokenizer; } return super.getTokenizer(element); } @Override public boolean isSuppressedFor(@NotNull PsiElement element, @NotNull String name) { DomElement domElement = DomUtil.getDomElement(element); if (domElement != null) { if (domElement.getAnnotation(NoSpellchecking.class) != null) { return true; } } return false; } @Override public SuppressQuickFix[] getSuppressActions(@NotNull PsiElement element, @NotNull String name) { return SuppressQuickFix.EMPTY_ARRAY; } protected Tokenizer<? extends PsiElement> createAttributeValueTokenizer() { return new XmlAttributeValueTokenizer(PlainTextSplitter.getInstance()); } private boolean isXmlDataCharactersParentHandledByItsStrategy(@Nullable PsiElement parent) { if (parent == null) return false; var strategy = ContainerUtil.findInstance( LanguageSpellchecking.INSTANCE.allForLanguage(parent.getLanguage()), XmlSpellcheckingStrategy.class); return strategy != null ? strategy.isXmlDataCharactersParentHandled(parent) : isXmlDataCharactersParentHandled(parent); } protected boolean isXmlDataCharactersParentHandled(@NotNull PsiElement parent) { return parent instanceof XmlText || parent.getNode().getElementType() == XmlElementType.XML_CDATA; } protected boolean isInTemplateLanguageFile(PsiElement element) { PsiFile file = element.getContainingFile(); return file == null || file.getLanguage() instanceof TemplateLanguage; } protected Tokenizer<? extends PsiElement> createTextTokenizer() { return new XmlTextTokenizer(PlainTextSplitter.getInstance()); } protected abstract static class XmlTextContentTokenizer<T extends XmlElement> extends XmlTokenizerBase<T> { public XmlTextContentTokenizer(Splitter splitter) { super(splitter); } protected abstract boolean isContentToken(IElementType tokenType); @Override protected @NotNull List<@NotNull TextRange> getSpellcheckOuterContentRanges(@NotNull T element) { List<TextRange> result = new SmartList<>(super.getSpellcheckOuterContentRanges(element)); element.acceptChildren(new XmlElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { if (element.getNode().getElementType() == XmlElementType.XML_CDATA) { element.acceptChildren(this); } else if (!(element instanceof LeafPsiElement) || !isContentToken(element.getNode().getElementType())) { result.add(element.getTextRangeInParent()); } } }); return result; } } protected static class XmlTextTokenizer extends XmlTextContentTokenizer<XmlText> { public XmlTextTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_DATA_CHARACTERS || tokenType == XmlTokenType.XML_CDATA_START || tokenType == XmlTokenType.XML_CDATA_END || XmlTokenType.WHITESPACES.contains(tokenType); } } protected static class XmlAttributeValueTokenizer extends XmlTextContentTokenizer<XmlAttributeValue> { public XmlAttributeValueTokenizer(Splitter splitter) { super(splitter); } @Override protected boolean isContentToken(IElementType tokenType) { return tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER || tokenType == XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER || XmlTokenType.WHITESPACES.contains(tokenType); } @Override protected @NotNull List<@NotNull SpellcheckRange> getSpellcheckRanges(@NotNull XmlAttributeValue element) { TextRange range = ElementManipulators.getValueTextRange(element); if (range.isEmpty()) return emptyList(); String text = ElementManipulators.getValueText(element); return singletonList(new SpellcheckRange(text, false, range.getStartOffset(), TextRange.allOf(text))); } @Override public void tokenize(@NotNull XmlAttributeValue element, @NotNull TokenConsumer consumer) { PsiReference[] references = element.getReferences(); for (PsiReference reference : references) { if (reference instanceof XmlEnumeratedValueReference) { if (reference.resolve() != null) { // this is probably valid enumeration value from XSD/RNG schema, such as SVG return; } } } final String valueTextTrimmed = element.getValue().trim(); // do not<SUF> if (valueTextTrimmed.startsWith("#") && valueTextTrimmed.length() <= 9 && isHexString(valueTextTrimmed.substring(1))) { return; } super.tokenize(element, consumer); } private static boolean isHexString(final String s) { for (int i = 0; i < s.length(); i++) { if (!StringUtil.isHexDigit(s.charAt(i))) { return false; } } return true; } } }
False
1,502
11
1,692
11
1,810
11
1,692
11
2,114
11
false
false
false
false
false
true
4,476
193877_8
/** * This file is part of RefactorGuidance project. Which explores possibilities to generate context based * instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students) * * Copyright (C) 2018, Patrick de Beer, [email protected] * * 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 analysis.context; import aig.AdaptiveInstructionGraph; import aig.CodeContext; import analysis.ICodeAnalyzer; import analysis.MethodAnalyzer.ClassMethodFinder; import analysis.dataflow.MethodDataFlowAnalyzer; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * Class builds up a set of context detectors that are needed to detect contextual situations * in a given adaptive instruction graph. The list of detectors can be provided to the procedural * guidance generator */ public class ContextDetectorSetBuilder { private AdaptiveInstructionGraph _aig = null; private ContextConfiguration _analyzerConfig = null; private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>(); private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>(); public void SetAIT(AdaptiveInstructionGraph aig) { setAIT(aig); } public void setAIT(AdaptiveInstructionGraph aig) { this._aig = aig; } public List<IContextDetector> getContextDetectors() throws Exception { if(_analyzerConfig == null) { throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first"); } EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph(); String refactoringProcessName = this._aig.getRefactorMechanic(); if(refactoringProcessName.contentEquals("Rename Method")) { // Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen // They can be directly initialized if contextanalyzerconfiguration object is present // voor deze specifieke method // uitlezen cu + methodname of line numers // initieren ClassMethodFinder analyzer (en evt. andere analyzers) // instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector // intern weet op te vragen. // Voeg de analuzers toe aan ContextAnalyzerCOnfiguration BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input } else if(refactoringProcessName.contentEquals("Extract Method") ) { BuildExtractMethodContextDetectors(completeCodeContext); } return this._contextDetectors; } /** * Through the returned configuration object, the created analyzers can be accessed * - to initialize from the outside * - to be used by the detectors to access necessary information * @return */ public ContextConfiguration getContextAnalyzerConfiguration() { return _analyzerConfig; } public void setContextConfiguration(ContextConfiguration config) { _analyzerConfig = config; } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); _analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer()); _analyzerConfig.getMethodDataFlowAnalyzer().initialize( _analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(), _analyzerConfig.getCodeSection()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } /** * A set of context detectors is build based on the context set that is provided. * The @ContextConfiguration object is used to provide detectors with necessary input in a generic way * * @param completeCodeContext Context detectors that should be instantiated * @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers */ private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext, ContextConfiguration analyzerConfig) { if (ContextDetectorForAllContextDecisions(completeCodeContext)) { try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) { Class<?> classCtxt = Class.forName("analysis.context." + context.name()); Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration"); Constructor<?> constructor = classCtxt.getConstructor(classConfig); IContextDetector instance = (IContextDetector) constructor.newInstance(analyzerConfig); _contextDetectors.add(instance); } } } catch(ClassNotFoundException cnfe) { System.out.println(cnfe.getMessage()); } catch(Exception e) { System.out.println(e.getMessage()); } } } /** * Internally used to validate if all requested detectors in the context set are actually * present as classes in our java project * * @param completeCodeContext * @return True, when all necessary classes could be found */ private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { boolean allDefined = true; try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) Class.forName("analysis.context." + context.name()); } } catch(ClassNotFoundException cnfe) { System.out.println("class " + cnfe.getMessage() + " not defined"); allDefined = false; } return allDefined; } public void setConfiguration(ContextConfiguration configuration) { this._analyzerConfig = configuration; } }
the-refactorers/RefactorGuidanceTool
src/main/java/analysis/context/ContextDetectorSetBuilder.java
2,084
// intern weet op te vragen.
line_comment
nl
/** * This file is part of RefactorGuidance project. Which explores possibilities to generate context based * instructions on how to refactor a piece of Java code. This applied in an education setting (bachelor SE students) * * Copyright (C) 2018, Patrick de Beer, [email protected] * * 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 analysis.context; import aig.AdaptiveInstructionGraph; import aig.CodeContext; import analysis.ICodeAnalyzer; import analysis.MethodAnalyzer.ClassMethodFinder; import analysis.dataflow.MethodDataFlowAnalyzer; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; /** * Class builds up a set of context detectors that are needed to detect contextual situations * in a given adaptive instruction graph. The list of detectors can be provided to the procedural * guidance generator */ public class ContextDetectorSetBuilder { private AdaptiveInstructionGraph _aig = null; private ContextConfiguration _analyzerConfig = null; private List<IContextDetector> _contextDetectors = new ArrayList<IContextDetector>(); private List<ICodeAnalyzer> _analyzers = new ArrayList<ICodeAnalyzer>(); public void SetAIT(AdaptiveInstructionGraph aig) { setAIT(aig); } public void setAIT(AdaptiveInstructionGraph aig) { this._aig = aig; } public List<IContextDetector> getContextDetectors() throws Exception { if(_analyzerConfig == null) { throw new Exception("No ContextConfiguration object was defined. call setContextAnalyzerConfiguration(...) first"); } EnumSet<CodeContext.CodeContextEnum> completeCodeContext = this._aig.allUniqueCodeContextInGraph(); String refactoringProcessName = this._aig.getRefactorMechanic(); if(refactoringProcessName.contentEquals("Rename Method")) { // Maak de analyzers 1x aan in, om geen dubbele instanties te krijgen // They can be directly initialized if contextanalyzerconfiguration object is present // voor deze specifieke method // uitlezen cu + methodname of line numers // initieren ClassMethodFinder analyzer (en evt. andere analyzers) // instantieren detectors, waarbij in het config object de juiste analyzers staan, die een detector // intern weet<SUF> // Voeg de analuzers toe aan ContextAnalyzerCOnfiguration BuildRenameContextDetectors(completeCodeContext); // provides possible analyzers + input } else if(refactoringProcessName.contentEquals("Extract Method") ) { BuildExtractMethodContextDetectors(completeCodeContext); } return this._contextDetectors; } /** * Through the returned configuration object, the created analyzers can be accessed * - to initialize from the outside * - to be used by the detectors to access necessary information * @return */ public ContextConfiguration getContextAnalyzerConfiguration() { return _analyzerConfig; } public void setContextConfiguration(ContextConfiguration config) { _analyzerConfig = config; } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildRenameContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } //@Todo Move each specifc initiation of objects needed in a refactoring generator to a seperate Factory // private void BuildExtractMethodContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { // 1. setup the analyzers and add them to the generic config object. _analyzerConfig.setCMFAnalyzer(new ClassMethodFinder()); _analyzerConfig.getCMFAnalyzer().initialize(_analyzerConfig.getCompilationUnit(), _analyzerConfig.getClassName()); _analyzerConfig.setMethodDataFlowAnalyzer(new MethodDataFlowAnalyzer()); _analyzerConfig.getMethodDataFlowAnalyzer().initialize( _analyzerConfig.getCMFAnalyzer().getMethodDescriberForLocation(_analyzerConfig.getCodeSection().begin()).getMethodDeclaration(), _analyzerConfig.getCodeSection()); // 2. Create the relevant detectors and provided them with the generic config object UniversalBuildContextDetectors(completeCodeContext, _analyzerConfig); } /** * A set of context detectors is build based on the context set that is provided. * The @ContextConfiguration object is used to provide detectors with necessary input in a generic way * * @param completeCodeContext Context detectors that should be instantiated * @param analyzerConfig Necessary input to properly initialize detectors and possible analyzers */ private void UniversalBuildContextDetectors(EnumSet<CodeContext.CodeContextEnum> completeCodeContext, ContextConfiguration analyzerConfig) { if (ContextDetectorForAllContextDecisions(completeCodeContext)) { try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if (!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) { Class<?> classCtxt = Class.forName("analysis.context." + context.name()); Class<?> classConfig = Class.forName("analysis.context.ContextConfiguration"); Constructor<?> constructor = classCtxt.getConstructor(classConfig); IContextDetector instance = (IContextDetector) constructor.newInstance(analyzerConfig); _contextDetectors.add(instance); } } } catch(ClassNotFoundException cnfe) { System.out.println(cnfe.getMessage()); } catch(Exception e) { System.out.println(e.getMessage()); } } } /** * Internally used to validate if all requested detectors in the context set are actually * present as classes in our java project * * @param completeCodeContext * @return True, when all necessary classes could be found */ private boolean ContextDetectorForAllContextDecisions(EnumSet<CodeContext.CodeContextEnum> completeCodeContext) { boolean allDefined = true; try { for (CodeContext.CodeContextEnum context : completeCodeContext) { if(!context.toString().contentEquals(CodeContext.CodeContextEnum.always_true.toString())) Class.forName("analysis.context." + context.name()); } } catch(ClassNotFoundException cnfe) { System.out.println("class " + cnfe.getMessage() + " not defined"); allDefined = false; } return allDefined; } public void setConfiguration(ContextConfiguration configuration) { this._analyzerConfig = configuration; } }
False
1,646
9
1,755
10
1,835
7
1,755
10
2,099
9
false
false
false
false
false
true
645
69594_0
package AbsentieLijst.userInterfaceLaag;_x000D_ _x000D_ import AbsentieLijst.*;_x000D_ import javafx.collections.FXCollections;_x000D_ import javafx.collections.ObservableList;_x000D_ import javafx.event.ActionEvent;_x000D_ import javafx.fxml.FXMLLoader;_x000D_ import javafx.scene.Parent;_x000D_ import javafx.scene.Scene;_x000D_ import javafx.scene.control.Button;_x000D_ import javafx.scene.control.ComboBox;_x000D_ import javafx.scene.control.DatePicker;_x000D_ import javafx.scene.control.Label;_x000D_ import javafx.scene.image.Image;_x000D_ import javafx.stage.Modality;_x000D_ import javafx.stage.Stage;_x000D_ _x000D_ import java.sql.Time;_x000D_ import java.time.LocalDate;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashMap;_x000D_ _x000D_ public class ToekomstigAfmeldenController {_x000D_ public Button ButtonOpslaan;_x000D_ public Button ButtonAnnuleren;_x000D_ public DatePicker DatePickerDate;_x000D_ public ComboBox ComboBoxReden;_x000D_ public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_ public Button overzicht;_x000D_ public Label label;_x000D_ public ComboBox tijd;_x000D_ _x000D_ School HU = School.getSchool();_x000D_ ObservableList<String> options =_x000D_ FXCollections.observableArrayList(_x000D_ "Bruiloft",_x000D_ "Tandarts afspraak",_x000D_ "Begravenis", "Wegens corona.", "Overig"_x000D_ );_x000D_ _x000D_ _x000D_ public void initialize() {_x000D_ ComboBoxReden.setItems(options);_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ public void ActionOpslaan(ActionEvent actionEvent) {_x000D_ if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_ LocalDate datum = DatePickerDate.getValue();_x000D_ Object time = tijd.getValue();_x000D_ try {_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (String lesNaam : alleLessen.keySet()) {_x000D_ if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_ alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in de les_x000D_ student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ label.setText("ddddd");_x000D_ }_x000D_ } else label.setText("Je moet Datum en reden kiezen");_x000D_ }_x000D_ _x000D_ public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ _x000D_ public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_ ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ ArrayList<String> les = new ArrayList<>();_x000D_ _x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (Les lesNaam : alleLessen.values())_x000D_ if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_ // for (String les1 : alleLessen.keySet()) {_x000D_ les.add(lesNaam.getNaam());_x000D_ lessen.addAll(les);_x000D_ tijd.setItems(lessen);_x000D_ }_x000D_ _x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
HBO-ICT-GP-SD/Laatsteversie
AbsentieLijst/src/AbsentieLijst/userInterfaceLaag/ToekomstigAfmeldenController.java
1,160
//afgemeld_lijst in de les_x000D_
line_comment
nl
package AbsentieLijst.userInterfaceLaag;_x000D_ _x000D_ import AbsentieLijst.*;_x000D_ import javafx.collections.FXCollections;_x000D_ import javafx.collections.ObservableList;_x000D_ import javafx.event.ActionEvent;_x000D_ import javafx.fxml.FXMLLoader;_x000D_ import javafx.scene.Parent;_x000D_ import javafx.scene.Scene;_x000D_ import javafx.scene.control.Button;_x000D_ import javafx.scene.control.ComboBox;_x000D_ import javafx.scene.control.DatePicker;_x000D_ import javafx.scene.control.Label;_x000D_ import javafx.scene.image.Image;_x000D_ import javafx.stage.Modality;_x000D_ import javafx.stage.Stage;_x000D_ _x000D_ import java.sql.Time;_x000D_ import java.time.LocalDate;_x000D_ import java.util.ArrayList;_x000D_ import java.util.HashMap;_x000D_ _x000D_ public class ToekomstigAfmeldenController {_x000D_ public Button ButtonOpslaan;_x000D_ public Button ButtonAnnuleren;_x000D_ public DatePicker DatePickerDate;_x000D_ public ComboBox ComboBoxReden;_x000D_ public static ArrayList<Afspraak> afGmeld = new ArrayList<>();_x000D_ public Button overzicht;_x000D_ public Label label;_x000D_ public ComboBox tijd;_x000D_ _x000D_ School HU = School.getSchool();_x000D_ ObservableList<String> options =_x000D_ FXCollections.observableArrayList(_x000D_ "Bruiloft",_x000D_ "Tandarts afspraak",_x000D_ "Begravenis", "Wegens corona.", "Overig"_x000D_ );_x000D_ _x000D_ _x000D_ public void initialize() {_x000D_ ComboBoxReden.setItems(options);_x000D_ _x000D_ }_x000D_ _x000D_ _x000D_ public void ActionOpslaan(ActionEvent actionEvent) {_x000D_ if (DatePickerDate.getValue() != null && ComboBoxReden != null) {_x000D_ LocalDate datum = DatePickerDate.getValue();_x000D_ Object time = tijd.getValue();_x000D_ try {_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (String lesNaam : alleLessen.keySet()) {_x000D_ if (alleLessen.get(lesNaam).getDatum().equals(datum)) {_x000D_ alleLessen.get(lesNaam).setAbsent(student, " met reden:"+" "+(String) ComboBoxReden.getValue()); //afgemeld_lijst in<SUF> student.setAfgemeld("Vooraf afgemeld: " + alleLessen.get(lesNaam).getDatum() + " " + alleLessen.get(lesNaam).getLescode() + " met als reden: " + ComboBoxReden.getValue()); //afgemeld overzicht student._x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ } catch (Exception e) {_x000D_ label.setText("ddddd");_x000D_ }_x000D_ } else label.setText("Je moet Datum en reden kiezen");_x000D_ }_x000D_ _x000D_ public void ActionAnnuleren(ActionEvent actionEvent) {_x000D_ Button source = (Button) actionEvent.getSource();_x000D_ Stage stage = (Stage) source.getScene().getWindow();_x000D_ stage.close();_x000D_ }_x000D_ _x000D_ public void DatapickerOnAction(ActionEvent actionEvent) {_x000D_ ObservableList<String> lessen = FXCollections.observableArrayList();_x000D_ for (Klas klas : HU.getKlassen()) {_x000D_ for (Student student : klas.getStudenten()) {_x000D_ if (student.getisIngelogd()) {_x000D_ ArrayList<String> les = new ArrayList<>();_x000D_ _x000D_ HashMap<String, Les> alleLessen = klas.getLessen();_x000D_ for (Les lesNaam : alleLessen.values())_x000D_ if (lesNaam.getDatum().equals(DatePickerDate.getValue())) {_x000D_ // for (String les1 : alleLessen.keySet()) {_x000D_ les.add(lesNaam.getNaam());_x000D_ lessen.addAll(les);_x000D_ tijd.setItems(lessen);_x000D_ }_x000D_ _x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_ }_x000D_
True
1,461
16
1,586
17
1,603
16
1,586
17
1,762
17
false
false
false
false
false
true
4,535
10292_3
package be.kuleuven.cs.distrinet.jnome.core.type; import java.util.ArrayList; import java.util.List; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.core.validation.Valid; import org.aikodi.chameleon.core.validation.Verification; import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage; import org.aikodi.chameleon.oo.type.Type; import org.aikodi.chameleon.oo.type.TypeReference; import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter; import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint; import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType; import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter; import org.aikodi.chameleon.oo.type.generics.TypeArgument; import org.aikodi.chameleon.oo.type.generics.TypeConstraint; import org.aikodi.chameleon.oo.type.generics.TypeParameter; import org.aikodi.chameleon.oo.view.ObjectOrientedView; import org.aikodi.chameleon.workspace.View; import be.kuleuven.cs.distrinet.jnome.core.language.Java7; public class PureWildcard extends TypeArgument { public PureWildcard() { } public TypeParameter capture(FormalTypeParameter formal) { CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name()); capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c)); return newParameter; } /** * @param constraints * @return */ public List<TypeConstraint> capture(List<TypeConstraint> constraints) { List<TypeConstraint> newConstraints = new ArrayList<>(); for(TypeConstraint constraint: constraints) { TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint); newConstraints.add(clone); } //FIXME This should actually be determined by the type parameter itself. // perhaps it should compute its own upper bound reference if(newConstraints.size() == 0) { Java7 java = language(Java7.class); BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN()); TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace()); newConstraints.add(new ExtendsConstraint(tref)); } return newConstraints; } @Override protected PureWildcard cloneSelf() { return new PureWildcard(); } // TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat // wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad // verplaatst worden. NOPE, niet altijd eerst capturen. @Override public Type lowerBound() throws LookupException { View view = view(); ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class); return l.getNullType(view.namespace()); } @Override public Type type() throws LookupException { ExtendsWildcardType result = new ExtendsWildcardType(upperBound()); result.setUniParent(namespace().defaultNamespace()); return result; // PureWildCardType pureWildCardType = new PureWildCardType(parameterBound()); // pureWildCardType.setUniParent(this); // return pureWildCardType; } // public Type parameterBound() throws LookupException { //// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class); //// List<TypeArgument> args = nearestAncestor.typeArguments(); //// int index = args.indexOf(this); //// // Wrong, this should not be the type constructor, we need to take into account the //// // type instance //// Type typeConstructor = nearestAncestor.typeConstructor(); //// Type typeInstance = nearestAncestor.getElement(); //// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index); //// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index); //// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference(); //// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference); //// clonedUpperBoundReference.setUniParent(actualParameter); //// ////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse //// Type result = clonedUpperBoundReference.getElement(); //// return result; // } @Override public boolean uniSameAs(Element other) throws LookupException { return other instanceof PureWildcard; } @Override public Type upperBound() throws LookupException { //return language(ObjectOrientedLanguage.class).getDefaultSuperClass(); return view(ObjectOrientedView.class).topLevelType(); } @Override public Verification verifySelf() { return Valid.create(); } public String toString(java.util.Set<Element> visited) { return "?"; } @Override public boolean isWildCardBound() { return true; } }
tivervac/jnome
src/be/kuleuven/cs/distrinet/jnome/core/type/PureWildcard.java
1,478
// TypeVariable concept invoeren, en lowerbound,... verplaatsen naar daar? Deze is context sensitive. Hoewel, dat
line_comment
nl
package be.kuleuven.cs.distrinet.jnome.core.type; import java.util.ArrayList; import java.util.List; import org.aikodi.chameleon.core.element.Element; import org.aikodi.chameleon.core.lookup.LookupException; import org.aikodi.chameleon.core.validation.Valid; import org.aikodi.chameleon.core.validation.Verification; import org.aikodi.chameleon.oo.language.ObjectOrientedLanguage; import org.aikodi.chameleon.oo.type.Type; import org.aikodi.chameleon.oo.type.TypeReference; import org.aikodi.chameleon.oo.type.generics.CapturedTypeParameter; import org.aikodi.chameleon.oo.type.generics.ExtendsConstraint; import org.aikodi.chameleon.oo.type.generics.ExtendsWildcardType; import org.aikodi.chameleon.oo.type.generics.FormalTypeParameter; import org.aikodi.chameleon.oo.type.generics.TypeArgument; import org.aikodi.chameleon.oo.type.generics.TypeConstraint; import org.aikodi.chameleon.oo.type.generics.TypeParameter; import org.aikodi.chameleon.oo.view.ObjectOrientedView; import org.aikodi.chameleon.workspace.View; import be.kuleuven.cs.distrinet.jnome.core.language.Java7; public class PureWildcard extends TypeArgument { public PureWildcard() { } public TypeParameter capture(FormalTypeParameter formal) { CapturedTypeParameter newParameter = new CapturedTypeParameter(formal.name()); capture(formal.constraints()).forEach(c -> newParameter.addConstraint(c)); return newParameter; } /** * @param constraints * @return */ public List<TypeConstraint> capture(List<TypeConstraint> constraints) { List<TypeConstraint> newConstraints = new ArrayList<>(); for(TypeConstraint constraint: constraints) { TypeConstraint clone = cloneAndResetTypeReference(constraint,constraint); newConstraints.add(clone); } //FIXME This should actually be determined by the type parameter itself. // perhaps it should compute its own upper bound reference if(newConstraints.size() == 0) { Java7 java = language(Java7.class); BasicJavaTypeReference objectRef = java.createTypeReference(java.getDefaultSuperClassFQN()); TypeReference tref = java.createNonLocalTypeReference(objectRef,namespace().defaultNamespace()); newConstraints.add(new ExtendsConstraint(tref)); } return newConstraints; } @Override protected PureWildcard cloneSelf() { return new PureWildcard(); } // TypeVariable concept<SUF> // wordt toch nooit direct vergeleken. Er moet volgens mij altijd eerst gecaptured worden, dus dan moet dit inderdaad // verplaatst worden. NOPE, niet altijd eerst capturen. @Override public Type lowerBound() throws LookupException { View view = view(); ObjectOrientedLanguage l = view.language(ObjectOrientedLanguage.class); return l.getNullType(view.namespace()); } @Override public Type type() throws LookupException { ExtendsWildcardType result = new ExtendsWildcardType(upperBound()); result.setUniParent(namespace().defaultNamespace()); return result; // PureWildCardType pureWildCardType = new PureWildCardType(parameterBound()); // pureWildCardType.setUniParent(this); // return pureWildCardType; } // public Type parameterBound() throws LookupException { //// BasicJavaTypeReference nearestAncestor = nearestAncestor(BasicJavaTypeReference.class); //// List<TypeArgument> args = nearestAncestor.typeArguments(); //// int index = args.indexOf(this); //// // Wrong, this should not be the type constructor, we need to take into account the //// // type instance //// Type typeConstructor = nearestAncestor.typeConstructor(); //// Type typeInstance = nearestAncestor.getElement(); //// TypeParameter formalParameter = typeConstructor.parameter(TypeParameter.class,index); //// TypeParameter actualParameter = typeInstance.parameter(TypeParameter.class, index); //// TypeReference formalUpperBoundReference = formalParameter.upperBoundReference(); //// TypeReference clonedUpperBoundReference = clone(formalUpperBoundReference); //// clonedUpperBoundReference.setUniParent(actualParameter); //// ////// Type result = formalParameter.upperBound(); // This fixes testGenericRejuse //// Type result = clonedUpperBoundReference.getElement(); //// return result; // } @Override public boolean uniSameAs(Element other) throws LookupException { return other instanceof PureWildcard; } @Override public Type upperBound() throws LookupException { //return language(ObjectOrientedLanguage.class).getDefaultSuperClass(); return view(ObjectOrientedView.class).topLevelType(); } @Override public Verification verifySelf() { return Valid.create(); } public String toString(java.util.Set<Element> visited) { return "?"; } @Override public boolean isWildCardBound() { return true; } }
False
1,117
28
1,317
32
1,313
25
1,317
32
1,513
30
false
false
false
false
false
true
4,516
147808_16
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox 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. * * The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ /* Bad ones Model 1 = 93,119, Model 2 = 67,98, Classifier MP_ED acc =0.45555555555555555 Model 1 = 84,118, Model 2 = 66,109, */ package statistics.simulators; import fileIO.OutFile; import java.util.*; import java.io.*; import statistics.distributions.NormalDistribution; import statistics.simulators.DictionaryModel.ShapeType; import static statistics.simulators.Model.rand; import statistics.simulators.ShapeletModel.Shape; public class MatrixProfileModelVersion1 extends Model { private int nosLocations=2; // private int shapeLength=29; public static double MINBASE=-2; public static double MINAMP=2; public static double MAXBASE=2; public static double MAXAMP=4; DictionaryModel.Shape shape;//Will change for each series private static int GLOBALSERIESLENGTH=500; private int seriesLength; // Need to set intervals, maybe allow different lengths? private int base=-1; private int amplitude=2; private int shapeCount=0; private boolean invert=false; boolean discord=false; double[] shapeVals; ArrayList<Integer> locations; public static int getGlobalLength(){ return GLOBALSERIESLENGTH;} public MatrixProfileModelVersion1(){ shapeCount=0;//rand.nextInt(ShapeType.values().length); seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } public MatrixProfileModelVersion1(boolean d){ shapeCount=0;//rand.nextInt(ShapeType.values().length); discord=d; if(discord) nosLocations=1; seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } private void generateRandomShapeVals(){ for(int i=0;i<shapeLength;i++) shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); } public void setSeriesLength(int n){ seriesLength=n; } public static void setGlobalSeriesLength(int n){ GLOBALSERIESLENGTH=n; } public void setNonOverlappingIntervals(){ //Use Aarons way ArrayList<Integer> startPoints=new ArrayList<>(); for(int i=shapeLength+1;i<seriesLength-shapeLength;i++) startPoints.add(i); for(int i=0;i<nosLocations;i++){ int pos=rand.nextInt(startPoints.size()); int l=startPoints.get(pos); locations.add(l); //+/- windowSize/2 if(pos<shapeLength) pos=0; else pos=pos-shapeLength; for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++) startPoints.remove(pos); /* //Me giving up and just randomly placing the shapes until they are all non overlapping for(int i=0;i<nosLocations;i++){ boolean ok=false; int l=shapeLength/2; while(!ok){ ok=true; //Search mid points to level the distribution up somewhat // System.out.println("Series length ="+seriesLength); do{ l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2; } while((l+shapeLength/2)>=seriesLength-shapeLength); for(int in:locations){ //I think this is setting them too big if((l>=in-shapeLength && l<in+shapeLength) //l inside ins ||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l ok=false; // System.out.println(l+" overlaps with "+in); break; } } } */ // System.out.println("Adding "+l); } /*//Revert to start points for(int i=0;i<locations.size();i++){ int val=locations.get(i); locations.set(i, val-shapeLength/2); } */ Collections.sort(locations); // System.out.println("MODEL START POINTS ="); // for(int i=0;i<locations.size();i++) // System.out.println(locations.get(i)); } @Override public void setParameters(double[] p) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void setLocations(ArrayList<Integer> l, int length){ locations=new ArrayList<>(l); shapeLength=length; } public ArrayList<Integer> getIntervals(){return locations;} public int getShapeLength(){ return shapeLength;} public void generateBaseShape(){ //Randomise BASE and AMPLITUDE double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); ShapeType[] all=ShapeType.values(); ShapeType st=all[(shapeCount++)%all.length]; shape=new DictionaryModel.Shape(st,shapeLength,b,a); // shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a); // System.out.println("Shape is "+shape); // shape.nextShape(); // shape } @Override public double[] generateSeries(int n) { t=0; double[] d; generateRandomShapeVals(); //Resets the starting locations each time this is called if(invert){ d= new double[n]; for(int i=0;i<n;i++) d[i]=-generate(); invert=false; } else{ generateBaseShape(); d = new double[n]; for(int i=0;i<n;i++) d[i]=generate(); invert=true; } return d; } private double generateConfig1(){ //Noise // System.out.println("Error var ="+error.getVariance()); double value=0; //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(point<=t && point+shapeLength>t)//in shape1 value=shapeVals[(int)(t-point)]; else value= error.simulate(); // value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); t++; return value; } private double generateConfig2(){ //Noise // System.out.println("Error var ="+error.getVariance()); double value=error.simulate(); //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(insertionPoint>0 && point==t){//New shape, randomise scale // double b=shape.getBase()/5; // double a=shape.getAmp()/5; double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); shape.setAmp(a); shape.setBase(b); // System.out.println("changing second shape"); } if(point<=t && point+shapeLength>t){//in shape1 value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); } t++; return value; } //Generate point t @Override public double generate(){ return generateConfig1(); } public static void generateExampleData(){ int length=500; GLOBALSERIESLENGTH=length; Model.setGlobalRandomSeed(3); Model.setDefaultSigma(0); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[][] d=new double[20][]; for(int i=0;i<10;i++){ d[i]=m1.generateSeries(length); } for(int i=10;i<20;i++){ d[i]=m1.generateSeries(length); } OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv"); for(int i=0;i<length;i++){ for(int j=0;j<10;j++) of.writeString(d[j][i]+","); of.writeString("\n"); } } public String toString(){ String str=""; for(Integer i:locations) str+=i+","; return str; } public static void main(String[] args){ generateExampleData(); System.exit(0); //Set up two models with same intervals but different shapes int length=500; Model.setGlobalRandomSeed(10); Model.setDefaultSigma(0.1); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[] d1=m1.generateSeries(length); double[] d2=m2.generateSeries(length); OutFile of=new OutFile("C:\\temp\\MP_Ex.csv"); for(int i=0;i<length;i++) of.writeLine(d1[i]+","+d2[i]); } }
time-series-machine-learning/tsml-java
src/main/java/statistics/simulators/MatrixProfileModelVersion1.java
3,086
// System.out.println("Error var ="+error.getVariance());
line_comment
nl
/* * This file is part of the UEA Time Series Machine Learning (TSML) toolbox. * * The UEA TSML toolbox 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. * * The UEA TSML toolbox 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 the UEA TSML toolbox. If not, see <https://www.gnu.org/licenses/>. */ /* Bad ones Model 1 = 93,119, Model 2 = 67,98, Classifier MP_ED acc =0.45555555555555555 Model 1 = 84,118, Model 2 = 66,109, */ package statistics.simulators; import fileIO.OutFile; import java.util.*; import java.io.*; import statistics.distributions.NormalDistribution; import statistics.simulators.DictionaryModel.ShapeType; import static statistics.simulators.Model.rand; import statistics.simulators.ShapeletModel.Shape; public class MatrixProfileModelVersion1 extends Model { private int nosLocations=2; // private int shapeLength=29; public static double MINBASE=-2; public static double MINAMP=2; public static double MAXBASE=2; public static double MAXAMP=4; DictionaryModel.Shape shape;//Will change for each series private static int GLOBALSERIESLENGTH=500; private int seriesLength; // Need to set intervals, maybe allow different lengths? private int base=-1; private int amplitude=2; private int shapeCount=0; private boolean invert=false; boolean discord=false; double[] shapeVals; ArrayList<Integer> locations; public static int getGlobalLength(){ return GLOBALSERIESLENGTH;} public MatrixProfileModelVersion1(){ shapeCount=0;//rand.nextInt(ShapeType.values().length); seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } public MatrixProfileModelVersion1(boolean d){ shapeCount=0;//rand.nextInt(ShapeType.values().length); discord=d; if(discord) nosLocations=1; seriesLength=GLOBALSERIESLENGTH; locations=new ArrayList<>(); setNonOverlappingIntervals(); shapeVals=new double[shapeLength]; generateRandomShapeVals(); } private void generateRandomShapeVals(){ for(int i=0;i<shapeLength;i++) shapeVals[i]=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); } public void setSeriesLength(int n){ seriesLength=n; } public static void setGlobalSeriesLength(int n){ GLOBALSERIESLENGTH=n; } public void setNonOverlappingIntervals(){ //Use Aarons way ArrayList<Integer> startPoints=new ArrayList<>(); for(int i=shapeLength+1;i<seriesLength-shapeLength;i++) startPoints.add(i); for(int i=0;i<nosLocations;i++){ int pos=rand.nextInt(startPoints.size()); int l=startPoints.get(pos); locations.add(l); //+/- windowSize/2 if(pos<shapeLength) pos=0; else pos=pos-shapeLength; for(int j=0;startPoints.size()>pos && j<(3*shapeLength);j++) startPoints.remove(pos); /* //Me giving up and just randomly placing the shapes until they are all non overlapping for(int i=0;i<nosLocations;i++){ boolean ok=false; int l=shapeLength/2; while(!ok){ ok=true; //Search mid points to level the distribution up somewhat // System.out.println("Series length ="+seriesLength); do{ l=rand.nextInt(seriesLength-shapeLength)+shapeLength/2; } while((l+shapeLength/2)>=seriesLength-shapeLength); for(int in:locations){ //I think this is setting them too big if((l>=in-shapeLength && l<in+shapeLength) //l inside ins ||(l<in-shapeLength && l+shapeLength>in) ){ //ins inside l ok=false; // System.out.println(l+" overlaps with "+in); break; } } } */ // System.out.println("Adding "+l); } /*//Revert to start points for(int i=0;i<locations.size();i++){ int val=locations.get(i); locations.set(i, val-shapeLength/2); } */ Collections.sort(locations); // System.out.println("MODEL START POINTS ="); // for(int i=0;i<locations.size();i++) // System.out.println(locations.get(i)); } @Override public void setParameters(double[] p) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void setLocations(ArrayList<Integer> l, int length){ locations=new ArrayList<>(l); shapeLength=length; } public ArrayList<Integer> getIntervals(){return locations;} public int getShapeLength(){ return shapeLength;} public void generateBaseShape(){ //Randomise BASE and AMPLITUDE double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); ShapeType[] all=ShapeType.values(); ShapeType st=all[(shapeCount++)%all.length]; shape=new DictionaryModel.Shape(st,shapeLength,b,a); // shape=new DictionaryModel.Shape(DictionaryModel.ShapeType.SPIKE,shapeLength,b,a); // System.out.println("Shape is "+shape); // shape.nextShape(); // shape } @Override public double[] generateSeries(int n) { t=0; double[] d; generateRandomShapeVals(); //Resets the starting locations each time this is called if(invert){ d= new double[n]; for(int i=0;i<n;i++) d[i]=-generate(); invert=false; } else{ generateBaseShape(); d = new double[n]; for(int i=0;i<n;i++) d[i]=generate(); invert=true; } return d; } private double generateConfig1(){ //Noise // System.out.println("Error var ="+error.getVariance()); double value=0; //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(point<=t && point+shapeLength>t)//in shape1 value=shapeVals[(int)(t-point)]; else value= error.simulate(); // value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); t++; return value; } private double generateConfig2(){ //Noise // System.out.println("Error var<SUF> double value=error.simulate(); //Find the next shape int insertionPoint=0; while(insertionPoint<locations.size() && locations.get(insertionPoint)+shapeLength<t) insertionPoint++; //Bigger than all the start points, set to last if(insertionPoint>=locations.size()){ insertionPoint=locations.size()-1; } int point=locations.get(insertionPoint); if(insertionPoint>0 && point==t){//New shape, randomise scale // double b=shape.getBase()/5; // double a=shape.getAmp()/5; double b=MINBASE+(MAXBASE-MINBASE)*Model.rand.nextDouble(); double a=MINAMP+(MAXAMP-MINAMP)*Model.rand.nextDouble(); shape.setAmp(a); shape.setBase(b); // System.out.println("changing second shape"); } if(point<=t && point+shapeLength>t){//in shape1 value+=shape.generateWithinShapelet((int)(t-point)); // System.out.println(" IN SHAPE 1 occurence "+insertionPoint+" Time "+t); } t++; return value; } //Generate point t @Override public double generate(){ return generateConfig1(); } public static void generateExampleData(){ int length=500; GLOBALSERIESLENGTH=length; Model.setGlobalRandomSeed(3); Model.setDefaultSigma(0); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[][] d=new double[20][]; for(int i=0;i<10;i++){ d[i]=m1.generateSeries(length); } for(int i=10;i<20;i++){ d[i]=m1.generateSeries(length); } OutFile of=new OutFile("C:\\temp\\MP_ExampleSeries.csv"); for(int i=0;i<length;i++){ for(int j=0;j<10;j++) of.writeString(d[j][i]+","); of.writeString("\n"); } } public String toString(){ String str=""; for(Integer i:locations) str+=i+","; return str; } public static void main(String[] args){ generateExampleData(); System.exit(0); //Set up two models with same intervals but different shapes int length=500; Model.setGlobalRandomSeed(10); Model.setDefaultSigma(0.1); MatrixProfileModelVersion1 m1=new MatrixProfileModelVersion1(); MatrixProfileModelVersion1 m2=new MatrixProfileModelVersion1(); double[] d1=m1.generateSeries(length); double[] d2=m2.generateSeries(length); OutFile of=new OutFile("C:\\temp\\MP_Ex.csv"); for(int i=0;i<length;i++) of.writeLine(d1[i]+","+d2[i]); } }
False
2,361
15
2,635
17
2,844
17
2,635
17
3,061
18
false
false
false
false
false
true
222
167130_0
package keezen; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Decks implements Serializable{ Kaart[] drawPile; Kaart[] discardPile; public Decks (){ } public Kaart[] getDrawPile(){ return drawPile; } public void setAantalKaarten(int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public void setDrawPile(Kaart[] drawPile){ this.drawPile = drawPile; } public Kaart[] getDiscardPile(){ return discardPile; } public void setDiscardPile(Kaart[] discardPile){ this.discardPile = discardPile; } } /*public class Decks implements Serializable { Kaart[] drawPile; Kaart[] discardPile; public Decks (int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public Kaart[] getDrawPile() { return drawPile; } public void setDrawPile(Kaart[] drawPile) { this.drawPile = drawPile; } public Kaart[] getDiscardPile() { return discardPile; } public void setDiscardPile(Kaart[] discardPile) { this.discardPile = discardPile; } }*/
Bobster94/Keezen
src/keezen/Decks.java
459
/*public class Decks implements Serializable { Kaart[] drawPile; Kaart[] discardPile; public Decks (int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public Kaart[] getDrawPile() { return drawPile; } public void setDrawPile(Kaart[] drawPile) { this.drawPile = drawPile; } public Kaart[] getDiscardPile() { return discardPile; } public void setDiscardPile(Kaart[] discardPile) { this.discardPile = discardPile; } }*/
block_comment
nl
package keezen; import java.io.Serializable; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; public class Decks implements Serializable{ Kaart[] drawPile; Kaart[] discardPile; public Decks (){ } public Kaart[] getDrawPile(){ return drawPile; } public void setAantalKaarten(int aantalKaarten){ drawPile = new Kaart[aantalKaarten]; discardPile = new Kaart[aantalKaarten]; } public void setDrawPile(Kaart[] drawPile){ this.drawPile = drawPile; } public Kaart[] getDiscardPile(){ return discardPile; } public void setDiscardPile(Kaart[] discardPile){ this.discardPile = discardPile; } } /*public class Decks<SUF>*/
False
342
157
420
186
367
162
420
186
474
208
false
false
false
false
false
true
556
77274_2
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_SCALE = 1/1.149604398f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner values for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float COEFF) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= COEFF; } else { s[i] /= COEFF; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
GRSEB9S/Jypec
src/com/jypec/wavelet/liftingTransforms/LiftingCdf97WaveletTransform.java
1,512
// Predict inner values
line_comment
nl
package com.jypec.wavelet.liftingTransforms; import com.jypec.util.arrays.ArrayTransforms; import com.jypec.wavelet.Wavelet; import com.jypec.wavelet.kernelTransforms.cdf97.KernelCdf97WaveletTransform; /** * CDF 9 7 adaptation from: * https://github.com/VadimKirilchuk/jawelet/wiki/CDF-9-7-Discrete-Wavelet-Transform * * @author Daniel * */ public class LiftingCdf97WaveletTransform implements Wavelet { private static final float COEFF_PREDICT_1 = -1.586134342f; private static final float COEFF_PREDICT_2 = 0.8829110762f; private static final float COEFF_UPDATE_1= -0.05298011854f; private static final float COEFF_UPDATE_2 = 0.4435068522f; private static final float COEFF_SCALE = 1/1.149604398f; /** * Adds to each odd indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array <br> * E.g: {1, 0, 1} with COEFF = 1 -> {1, 2, 1} <br> * {1, 0, 2, 0} with COEFF = 1 -> {1, 3, 1, 4} * @param s the signal to be treated * @param n the length of s * @param COEFF the prediction coefficient */ private void predict(float[] s, int n, float COEFF) { // Predict inner<SUF> for (int i = 1; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 == 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Adds to each EVEN indexed sample its neighbors multiplied by the given coefficient * Wraps around if needed, mirroring the array * E.g: {1, 1, 1} with COEFF = 1 -> {3, 1, 3} * {1, 1, 2, 1} with COEFF = 1 -> {3, 1, 4, 1} * @param s the signal to be treated * @param n the length of s * @param COEFF the updating coefficient */ private void update(float[]s, int n, float COEFF) { // Update first coeff if (n > 1) { s[0] += 2*COEFF*s[1]; } // Update inner values for (int i = 2; i < n - 1; i+=2) { s[i] += COEFF * (s[i-1] + s[i+1]); } // Wrap around if (n % 2 != 0 && n > 1) { s[n-1] += 2*COEFF*s[n-2]; } } /** * Scales the ODD samples by COEFF, and the EVEN samples by 1/COEFF * @param s the signal to be scaled * @param n the length of s * @param COEFF the coefficient applied */ private void scale(float[] s, int n, float COEFF) { for (int i = 0; i < n; i++) { if (i%2 == 1) { s[i] *= COEFF; } else { s[i] /= COEFF; } } } @Override public void forwardTransform(float[] s, int n) { //predict and update predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_1); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, LiftingCdf97WaveletTransform.COEFF_UPDATE_2); //scale values scale(s, n, LiftingCdf97WaveletTransform.COEFF_SCALE); //pack values (low freq first, high freq last) ArrayTransforms.pack(s, n); } @Override public void reverseTransform(float[] s, int n) { //unpack values ArrayTransforms.unpack(s, n); //unscale values scale(s, n, 1/LiftingCdf97WaveletTransform.COEFF_SCALE); //unpredict and unupdate update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_2); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_2); update(s, n, -LiftingCdf97WaveletTransform.COEFF_UPDATE_1); predict(s, n, -LiftingCdf97WaveletTransform.COEFF_PREDICT_1); } @Override public float maxResult(float min, float max) { return new KernelCdf97WaveletTransform().maxResult(min, max); } @Override public float minResult(float min, float max) { return new KernelCdf97WaveletTransform().minResult(min, max); } }
False
1,313
4
1,421
4
1,427
4
1,421
4
1,623
5
false
false
false
false
false
true
4,470
18288_9
/* * Copyright 2008, 2009, 2010, 2011: * Tobias Fleig (tfg[AT]online[DOT]de), * Michael Haas (mekhar[AT]gmx[DOT]de), * Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de) * * - All rights reserved - * * * This file is part of Centuries of Rage. * * Centuries of Rage 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. * * Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>. * */ package de._13ducks.cor.game.server; import de._13ducks.cor.debug.UltimateDebug; import de._13ducks.cor.game.server.movement.ServerMoveManager; import de._13ducks.cor.networks.server.ServerNetController; import de._13ducks.cor.game.Building; import de._13ducks.cor.game.Unit; import de._13ducks.cor.game.NetPlayer.races; import java.io.*; import java.util.*; import javax.swing.JFrame; import javax.swing.JOptionPane; import de._13ducks.cor.game.Core; import de._13ducks.cor.game.NetPlayer; import de._13ducks.cor.game.server.movement.ServerAttackManager; /** * Der Server-Kern * * Startet einen Server mit den dazugehörigen Server-Modulen etc... * * Erzeugt ein seperates Logfile (server_log.txt) * * @author tfg */ public class ServerCore extends Core { ServerCore.InnerServer rgi; ServerNetController servNet; ServerMapModule mapMod; ServerGameController gamectrl; ServerStatistics sstat; //Statistik ServerMoveManager smoveman; public boolean ready; // gibt an, ob das Spiel gestartet werden soll. public ServerCore(boolean debug, String Mapname) { debugmode = debug; rgi = new ServerCore.InnerServer(); initLogger(); rgi.logger("[Core] Reading config..."); if (debugmode) { System.out.println("Configuration:"); } // Konfigurationsdatei lesen cfgvalues = new HashMap(); File cfgFile = new File("server_cfg.txt"); try { FileReader cfgReader = new FileReader(cfgFile); BufferedReader reader = new BufferedReader(cfgReader); String zeile = null; int i = 0; // Anzahl der Durchläufe zählen while ((zeile = reader.readLine()) != null) { // Liest Zeile fuer Zeile, jetzt auswerten und in Variablen // schreiben int indexgleich = zeile.indexOf('='); // Istgleich suchen if (indexgleich == -1) { } else { String v1 = zeile.substring(0, indexgleich); // Vor dem = // rauschneiden String v2 = zeile.substring(indexgleich + 1); // Nach dem // = // rausschneiden System.out.println(v1 + " = " + v2); cfgvalues.put(v1, v2); if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen rgi.logger("[Core-Log] " + v1 + "=" + v2); } } } reader.close(); } catch (FileNotFoundException e1) { // cfg-Datei nicht gefunden - inakzeptabel! rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one..."); try { cfgFile.createNewFile(); } catch (IOException ex) { System.out.print("Error creating server_cfg.txt ."); } //rgi.shutdown(1); } catch (IOException e2) { // Inakzeptabel e2.printStackTrace(); rgi.logger("[Core-ERROR] Critical I/O Error"); rgi.shutdown(1); } if ("true".equals(cfgvalues.get("ultimateDebug"))) { UltimateDebug udb = UltimateDebug.getInstance(); udb.authorizeDebug(this, rgi); } // Läuft als Server rgi.logger("[CoreInit]: Starting server mode..."); // Module laden rgi.logger("[CoreInit]: Loading modules..."); rgi.logger("[CoreInit]: Loading gamecontroller"); gamectrl = new ServerGameController(rgi); // Netzwerk rgi.logger("[CoreInit]: Loading serverNetController"); servNet = new ServerNetController(rgi, this); rgi.logger("[CoreInit]: Loading serverMapmodul"); mapMod = new ServerMapModule(rgi); rgi.logger("[CoreInit]: Loading serverStatistics"); sstat = new ServerStatistics(rgi); rgi.logger("[CoreInit]: Loading serverMoveManager"); smoveman = new ServerMoveManager(); // Alle Module geladen, starten rgi.initInner(); rgi.logger("[Core]: Initializing modules..."); mapMod.initModule(); rgi.logger("[Core]: Init done, starting Server..."); Thread t = new Thread(servNet); t.start(); rgi.logger("[Core]: Server running"); try { // Auf Startsignal warten while (!this.ready) { Thread.sleep(1000); } // Jetzt darf niemand mehr rein servNet.closeAcception(); // Zufallsvölker bestimmen und allen Clients mitteilen: for (NetPlayer p : this.gamectrl.playerList) { if (p.lobbyRace == races.random) { if (Math.rint(Math.random()) == 1) { p.lobbyRace = 1; this.servNet.broadcastString(("91" + p.nickName), (byte) 14); } else { p.lobbyRace = 2; this.servNet.broadcastString(("92" + p.nickName), (byte) 14); } } } // Clients vorbereiten servNet.loadGame(); // Warte darauf, das alle soweit sind waitForStatus(1); // Spiel laden mapMod.loadMap(Mapname); waitForStatus(2); // Game vorbereiten servNet.initGame((byte) 8); // Starteinheiten & Gebäude an das gewählte Volk anpassen: for (NetPlayer player : this.gamectrl.playerList) { // Gebäude: for (Building building : this.rgi.netmap.buildingList) { if (building.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { building.performUpgrade(rgi, 1001); } else if (player.lobbyRace == races.human) { building.performUpgrade(rgi, 1); } } } // Einheiten: for (Unit unit : this.rgi.netmap.unitList) { if (unit.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { // 401=human worker, 1401=undead worker if (unit.getDescTypeId() == 401) { unit.performUpgrade(rgi, 1401); } // 402=human scout, 1402=undead mage if (unit.getDescTypeId() == 402) { unit.performUpgrade(rgi, 1402); } } else if (player.lobbyRace == races.human) { // 1401=undead worker, 401=human worker if (unit.getDescTypeId() == 1401) { unit.performUpgrade(rgi, 401); } // 1402=undead mage, 402=human scout if (unit.getDescTypeId() == 1402) { unit.performUpgrade(rgi, 402); } } } } } waitForStatus(3); servNet.startGame(); } catch (InterruptedException ex) { } } /** * Synchronisierte Funktipon zum Strings senden * wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat * @param s - zu sendender String * @param cmdid - command-id */ public synchronized void broadcastStringSynchronized(String s, byte cmdid) { s += "\0"; this.servNet.broadcastString(s, cmdid); } private void waitForStatus(int status) throws InterruptedException { while (true) { Thread.sleep(50); boolean go = true; for (ServerNetController.ServerHandler servhan : servNet.clientconnection) { if (servhan.loadStatus < status) { go = false; break; } } if (go) { break; } } } @Override public void initLogger() { if (!logOFF) { // Erstellt ein neues Logfile try { FileWriter logcreator = new FileWriter("server_log.txt"); logcreator.close(); } catch (IOException ex) { // Warscheinlich darf man das nicht, den Adminmodus emfehlen JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); rgi.shutdown(2); } } } public class InnerServer extends Core.CoreInner { public ServerNetController netctrl; public ServerMapModule netmap; public ServerGameController game; public ServerStatistics serverstats; String lastlog = ""; public ServerMoveManager moveMan; public ServerAttackManager atkMan; @Override public void initInner() { super.initInner(); // Server-Referenz initialisiern: Server.setInnerServer(this); netctrl = servNet; netmap = mapMod; game = gamectrl; serverstats = sstat; moveMan = smoveman; atkMan = new ServerAttackManager(); } @Override public void logger(String x) { if (!logOFF) { if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern lastlog = x; // Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die // log-Datei try { FileWriter logwriter = new FileWriter("server_log.txt", true); String temp = String.format("%tc", new Date()) + " - " + x + "\n"; logwriter.append(temp); logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } @Override public void logger(Throwable t) { if (!logOFF) { // Nimmt Exceptions an und schreibt den Stacktrace ins // logfile try { if (debugmode) { System.out.println("ERROR!!!! More info in logfile..."); } FileWriter logwriter = new FileWriter("server_log.txt", true); logwriter.append('\n' + String.format("%tc", new Date()) + " - "); logwriter.append("[JavaError]: " + t.toString() + '\n'); StackTraceElement[] errorArray; errorArray = t.getStackTrace(); for (int i = 0; i < errorArray.length; i++) { logwriter.append(" " + errorArray[i].toString() + '\n'); } logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } }
tfg13/Centuries-of-Rage
src/de/_13ducks/cor/game/server/ServerCore.java
3,501
// Alle Module geladen, starten
line_comment
nl
/* * Copyright 2008, 2009, 2010, 2011: * Tobias Fleig (tfg[AT]online[DOT]de), * Michael Haas (mekhar[AT]gmx[DOT]de), * Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de) * * - All rights reserved - * * * This file is part of Centuries of Rage. * * Centuries of Rage 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. * * Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>. * */ package de._13ducks.cor.game.server; import de._13ducks.cor.debug.UltimateDebug; import de._13ducks.cor.game.server.movement.ServerMoveManager; import de._13ducks.cor.networks.server.ServerNetController; import de._13ducks.cor.game.Building; import de._13ducks.cor.game.Unit; import de._13ducks.cor.game.NetPlayer.races; import java.io.*; import java.util.*; import javax.swing.JFrame; import javax.swing.JOptionPane; import de._13ducks.cor.game.Core; import de._13ducks.cor.game.NetPlayer; import de._13ducks.cor.game.server.movement.ServerAttackManager; /** * Der Server-Kern * * Startet einen Server mit den dazugehörigen Server-Modulen etc... * * Erzeugt ein seperates Logfile (server_log.txt) * * @author tfg */ public class ServerCore extends Core { ServerCore.InnerServer rgi; ServerNetController servNet; ServerMapModule mapMod; ServerGameController gamectrl; ServerStatistics sstat; //Statistik ServerMoveManager smoveman; public boolean ready; // gibt an, ob das Spiel gestartet werden soll. public ServerCore(boolean debug, String Mapname) { debugmode = debug; rgi = new ServerCore.InnerServer(); initLogger(); rgi.logger("[Core] Reading config..."); if (debugmode) { System.out.println("Configuration:"); } // Konfigurationsdatei lesen cfgvalues = new HashMap(); File cfgFile = new File("server_cfg.txt"); try { FileReader cfgReader = new FileReader(cfgFile); BufferedReader reader = new BufferedReader(cfgReader); String zeile = null; int i = 0; // Anzahl der Durchläufe zählen while ((zeile = reader.readLine()) != null) { // Liest Zeile fuer Zeile, jetzt auswerten und in Variablen // schreiben int indexgleich = zeile.indexOf('='); // Istgleich suchen if (indexgleich == -1) { } else { String v1 = zeile.substring(0, indexgleich); // Vor dem = // rauschneiden String v2 = zeile.substring(indexgleich + 1); // Nach dem // = // rausschneiden System.out.println(v1 + " = " + v2); cfgvalues.put(v1, v2); if (debugmode) { // Im Debugmode alles ausgeben, zum nachvollziehen rgi.logger("[Core-Log] " + v1 + "=" + v2); } } } reader.close(); } catch (FileNotFoundException e1) { // cfg-Datei nicht gefunden - inakzeptabel! rgi.logger("[Core-ERROR] Configfile (server_cfg.txt) not found, creating new one..."); try { cfgFile.createNewFile(); } catch (IOException ex) { System.out.print("Error creating server_cfg.txt ."); } //rgi.shutdown(1); } catch (IOException e2) { // Inakzeptabel e2.printStackTrace(); rgi.logger("[Core-ERROR] Critical I/O Error"); rgi.shutdown(1); } if ("true".equals(cfgvalues.get("ultimateDebug"))) { UltimateDebug udb = UltimateDebug.getInstance(); udb.authorizeDebug(this, rgi); } // Läuft als Server rgi.logger("[CoreInit]: Starting server mode..."); // Module laden rgi.logger("[CoreInit]: Loading modules..."); rgi.logger("[CoreInit]: Loading gamecontroller"); gamectrl = new ServerGameController(rgi); // Netzwerk rgi.logger("[CoreInit]: Loading serverNetController"); servNet = new ServerNetController(rgi, this); rgi.logger("[CoreInit]: Loading serverMapmodul"); mapMod = new ServerMapModule(rgi); rgi.logger("[CoreInit]: Loading serverStatistics"); sstat = new ServerStatistics(rgi); rgi.logger("[CoreInit]: Loading serverMoveManager"); smoveman = new ServerMoveManager(); // Alle Module<SUF> rgi.initInner(); rgi.logger("[Core]: Initializing modules..."); mapMod.initModule(); rgi.logger("[Core]: Init done, starting Server..."); Thread t = new Thread(servNet); t.start(); rgi.logger("[Core]: Server running"); try { // Auf Startsignal warten while (!this.ready) { Thread.sleep(1000); } // Jetzt darf niemand mehr rein servNet.closeAcception(); // Zufallsvölker bestimmen und allen Clients mitteilen: for (NetPlayer p : this.gamectrl.playerList) { if (p.lobbyRace == races.random) { if (Math.rint(Math.random()) == 1) { p.lobbyRace = 1; this.servNet.broadcastString(("91" + p.nickName), (byte) 14); } else { p.lobbyRace = 2; this.servNet.broadcastString(("92" + p.nickName), (byte) 14); } } } // Clients vorbereiten servNet.loadGame(); // Warte darauf, das alle soweit sind waitForStatus(1); // Spiel laden mapMod.loadMap(Mapname); waitForStatus(2); // Game vorbereiten servNet.initGame((byte) 8); // Starteinheiten & Gebäude an das gewählte Volk anpassen: for (NetPlayer player : this.gamectrl.playerList) { // Gebäude: for (Building building : this.rgi.netmap.buildingList) { if (building.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { building.performUpgrade(rgi, 1001); } else if (player.lobbyRace == races.human) { building.performUpgrade(rgi, 1); } } } // Einheiten: for (Unit unit : this.rgi.netmap.unitList) { if (unit.getPlayerId() == player.playerId) { if (player.lobbyRace == races.undead) { // 401=human worker, 1401=undead worker if (unit.getDescTypeId() == 401) { unit.performUpgrade(rgi, 1401); } // 402=human scout, 1402=undead mage if (unit.getDescTypeId() == 402) { unit.performUpgrade(rgi, 1402); } } else if (player.lobbyRace == races.human) { // 1401=undead worker, 401=human worker if (unit.getDescTypeId() == 1401) { unit.performUpgrade(rgi, 401); } // 1402=undead mage, 402=human scout if (unit.getDescTypeId() == 1402) { unit.performUpgrade(rgi, 402); } } } } } waitForStatus(3); servNet.startGame(); } catch (InterruptedException ex) { } } /** * Synchronisierte Funktipon zum Strings senden * wird für die Lobby gebraucht, vielleicht später auch mal für ingame-chat * @param s - zu sendender String * @param cmdid - command-id */ public synchronized void broadcastStringSynchronized(String s, byte cmdid) { s += "\0"; this.servNet.broadcastString(s, cmdid); } private void waitForStatus(int status) throws InterruptedException { while (true) { Thread.sleep(50); boolean go = true; for (ServerNetController.ServerHandler servhan : servNet.clientconnection) { if (servhan.loadStatus < status) { go = false; break; } } if (go) { break; } } } @Override public void initLogger() { if (!logOFF) { // Erstellt ein neues Logfile try { FileWriter logcreator = new FileWriter("server_log.txt"); logcreator.close(); } catch (IOException ex) { // Warscheinlich darf man das nicht, den Adminmodus emfehlen JOptionPane.showMessageDialog(new JFrame(), "Cannot write to logfile. Please start CoR as Administrator", "admin required", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); rgi.shutdown(2); } } } public class InnerServer extends Core.CoreInner { public ServerNetController netctrl; public ServerMapModule netmap; public ServerGameController game; public ServerStatistics serverstats; String lastlog = ""; public ServerMoveManager moveMan; public ServerAttackManager atkMan; @Override public void initInner() { super.initInner(); // Server-Referenz initialisiern: Server.setInnerServer(this); netctrl = servNet; netmap = mapMod; game = gamectrl; serverstats = sstat; moveMan = smoveman; atkMan = new ServerAttackManager(); } @Override public void logger(String x) { if (!logOFF) { if (!lastlog.equals(x)) { // Nachrichten nicht mehrfach speichern lastlog = x; // Schreibt den Inhalt des Strings zusammen mit dem Zeitpunkt in die // log-Datei try { FileWriter logwriter = new FileWriter("server_log.txt", true); String temp = String.format("%tc", new Date()) + " - " + x + "\n"; logwriter.append(temp); logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } @Override public void logger(Throwable t) { if (!logOFF) { // Nimmt Exceptions an und schreibt den Stacktrace ins // logfile try { if (debugmode) { System.out.println("ERROR!!!! More info in logfile..."); } FileWriter logwriter = new FileWriter("server_log.txt", true); logwriter.append('\n' + String.format("%tc", new Date()) + " - "); logwriter.append("[JavaError]: " + t.toString() + '\n'); StackTraceElement[] errorArray; errorArray = t.getStackTrace(); for (int i = 0; i < errorArray.length; i++) { logwriter.append(" " + errorArray[i].toString() + '\n'); } logwriter.flush(); logwriter.close(); } catch (IOException ex) { ex.printStackTrace(); shutdown(2); } } } } }
True
2,732
8
3,026
9
3,095
6
3,026
9
3,534
8
false
false
false
false
false
true
501
15652_9
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package fhv; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = true; static int bufsize; static int available; static int tokenBegin; /** Position in buffer. */ static public int bufpos = -1; static protected int bufline[]; static protected int bufcolumn[]; static protected int column = 0; static protected int line = 1; static protected boolean prevCharIsCR = false; static protected boolean prevCharIsLF = false; static protected java.io.Reader inputStream; static protected char[] buffer; static protected int maxNextCharInd = 0; static protected int inBuf = 0; static protected int tabSize = 8; static protected void setTabSize(int i) { tabSize = i; } static protected int getTabSize(int i) { return tabSize; } static protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ static public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } static protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ static public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ static public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ static public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ static public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ static public int getEndLine() { return bufline[bufpos]; } /** Get token beginning column number. */ static public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ static public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ static public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { if (inputStream != null) throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" + " You must either use ReInit() or set the JavaCC option STATIC to false\n" + " during the generation of this class."); inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ static public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ static public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ static public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ static public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
FHV-ITM13/Just-Language
Justy_Wachter/src/fhv/SimpleCharStream.java
3,932
/** Get token beginning column number. */
block_comment
nl
/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=true,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ package fhv; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (without unicode processing). */ public class SimpleCharStream { /** Whether parser is static. */ public static final boolean staticFlag = true; static int bufsize; static int available; static int tokenBegin; /** Position in buffer. */ static public int bufpos = -1; static protected int bufline[]; static protected int bufcolumn[]; static protected int column = 0; static protected int line = 1; static protected boolean prevCharIsCR = false; static protected boolean prevCharIsLF = false; static protected java.io.Reader inputStream; static protected char[] buffer; static protected int maxNextCharInd = 0; static protected int inBuf = 0; static protected int tabSize = 8; static protected void setTabSize(int i) { tabSize = i; } static protected int getTabSize(int i) { return tabSize; } static protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos += (bufsize - tokenBegin)); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; maxNextCharInd = (bufpos -= tokenBegin); } } catch (Throwable t) { throw new Error(t.getMessage()); } bufsize += 2048; available = bufsize; tokenBegin = 0; } static protected void FillBuff() throws java.io.IOException { if (maxNextCharInd == available) { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = maxNextCharInd = 0; available = tokenBegin; } else if (tokenBegin < 0) bufpos = maxNextCharInd = 0; else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } int i; try { if ((i = inputStream.read(buffer, maxNextCharInd, available - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { --bufpos; backup(0); if (tokenBegin == -1) tokenBegin = bufpos; throw e; } } /** Start. */ static public char BeginToken() throws java.io.IOException { tokenBegin = -1; char c = readChar(); tokenBegin = bufpos; return c; } static protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ static public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } if (++bufpos >= maxNextCharInd) FillBuff(); char c = buffer[bufpos]; UpdateLineColumn(c); return c; } @Deprecated /** * @deprecated * @see #getEndColumn */ static public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ static public int getLine() { return bufline[bufpos]; } /** Get token end column number. */ static public int getEndColumn() { return bufcolumn[bufpos]; } /** Get token end line number. */ static public int getEndLine() { return bufline[bufpos]; } /** Get token beginning<SUF>*/ static public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** Get token beginning line number. */ static public int getBeginLine() { return bufline[tokenBegin]; } /** Backup a number of characters. */ static public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { if (inputStream != null) throw new Error("\n ERROR: Second call to the constructor of a static SimpleCharStream.\n" + " You must either use ReInit() or set the JavaCC option STATIC to false\n" + " during the generation of this class."); inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public SimpleCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Get token literal value. */ static public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** Get the suffix. */ static public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Reset buffer when finished. */ static public void Done() { buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ static public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=767e99b039c1576e8d2b2c644c6d31bb (do not edit this line) */
False
3,180
8
3,372
8
3,750
8
3,372
8
3,978
8
false
false
false
false
false
true
3,832
169507_0
package nl.njtromp.adventofcode_2020; import java.util.Arrays; public class Infi { static long aantalPakjes(long lengteZijkant) { return 3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal 4 * sommatie(lengteZijkant) + // Schuine zijden (4 halve driehoeken) 2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven) } private static long sommatie(long n) { return (n-1)*n/2; } private static long bepaalLengte(long aantalInwoners) { long lengte = 1; while (aantalPakjes(lengte) < aantalInwoners) { lengte++; } return lengte; } public static void main(String[] args) { long lengte = bepaalLengte(17_493_412); System.out.printf("De minimale lengte van een zijde is: %d\n", lengte); long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L}; System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8); } }
njtromp/AdventOfCode-2020
src/main/java/nl/njtromp/adventofcode_2020/Infi.java
436
// Schuine zijden (4 halve driehoeken)
line_comment
nl
package nl.njtromp.adventofcode_2020; import java.util.Arrays; public class Infi { static long aantalPakjes(long lengteZijkant) { return 3 * lengteZijkant * lengteZijkant + // Middenstuk horizontaal 4 * sommatie(lengteZijkant) + // Schuine zijden<SUF> 2 * lengteZijkant * lengteZijkant; // Rechte stukken tussen de schuine zijden (onder en boven) } private static long sommatie(long n) { return (n-1)*n/2; } private static long bepaalLengte(long aantalInwoners) { long lengte = 1; while (aantalPakjes(lengte) < aantalInwoners) { lengte++; } return lengte; } public static void main(String[] args) { long lengte = bepaalLengte(17_493_412); System.out.printf("De minimale lengte van een zijde is: %d\n", lengte); long[] aantalInwoners = {42_732_096L, 369_030_498L, 430_839_868L, 747_685_826L, 1_340_952_816L, 4_541_536_619L}; System.out.printf("Totaal aantal lappen stof: %d\n", Arrays.stream(aantalInwoners).map(Infi::bepaalLengte).sum() * 8); } }
True
416
15
461
17
420
12
461
17
465
14
false
false
false
false
false
true
1,893
30813_5
package shapes; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import properties.Property; import utility.MeasureFetcher; import utility.Util; import be.kuleuven.cs.oss.polymorphicviews.plugin.PolymorphicChartParameters; public abstract class ShapeGenerator { protected MeasureFetcher measureFetcher; protected Shape[] shapes; protected PolymorphicChartParameters params; private Property<Double> width; private Property<Double> height; private Property<Color> color; public ShapeGenerator(MeasureFetcher measureFetcher, Property<Double> width, Property<Double> height, Property<Color> color) { this.measureFetcher=measureFetcher; this.width = width; this.height = height; this.color = color; } /** * This method gives all boxes the correct values. * @param width that should be given to all boxes (number or metric) * @param height that should be given to all boxes (number or metric) * @param color that should be given to all boxes (rgb format or grayscale with metric) * @return */ public Shape[] getShapes() { return this.shapes; } /** * This method returns a list of colors, one for each shape. If * the input is in RGB format, the color is the same for all shapes. If the * format "min<float>max<float>key<string>" is used as input, the color of * each box is dependent on a specific measure of the box. Else, the color * will be set to default color * * @param color * the color/metric to be used * @return a list with a color for each box */ protected List<Color> getShapeColors(String color) { List<Color> result = new ArrayList<Color>(); if(Util.isValidColor(color)){ Color rgb = Util.parseColor(color); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } else{ //the color parsing is invalid and the string should be of the format "min<float>max<float>key<string>" try{ String[] splitted = Util.splitOnDelimiter(color, new String[]{"min","max","key"}); Double min = Double.parseDouble(splitted[0]); Double max = Double.parseDouble(splitted[1]); String key = splitted[2]; result = getGrayScaleColors(min, max, key); } //Given input is not valid catch (IllegalArgumentException f){ Color rgb = Util.parseColor(PolymorphicChartParameters.DEFAULT_BOXCOLOR); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } } return result; } /** * This method scales a list of metric values to a new list, with the lowest * value of the metric scaled to min, and the highest scaled to max. * * @param min * the minimum color value of the list with scaled colors * @param max * the maximum color value of the list with scaled colors * @param key * the key that represents the metric that should be scaled * @return a list with the scaled color values */ private List<Color> getGrayScaleColors(Double min, Double max, String key) throws IllegalArgumentException{ //TODO hoe werkt dees eigenlijk. vage opgave Map<String, Double> colors = measureFetcher.getMeasureValues(key); Map<String, Double> scaledColors = Util.scaleGrey(colors, min, max); List<Color> result = new ArrayList<Color>(); try{ for (int i = 0; i < shapes.length; i++) { String name = shapes[i].getName(); int colorValue = scaledColors.get(name).intValue(); Color c = new Color(colorValue, colorValue, colorValue); result.add(c); } return result; } catch(Exception e){ throw new IllegalArgumentException(); } } /** * This method names all the shapes with the correct resource names. */ protected void nameShapes() { List<String> names = measureFetcher.getResourceNames(); int i = 0; for (String s : names) { shapes[i].setName(s); i++; } } }
WoutV/OSS_1415
sonar-polymorphic-views/src/main/java/shapes/ShapeGenerator.java
1,195
//TODO hoe werkt dees eigenlijk. vage opgave
line_comment
nl
package shapes; import java.awt.Color; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import properties.Property; import utility.MeasureFetcher; import utility.Util; import be.kuleuven.cs.oss.polymorphicviews.plugin.PolymorphicChartParameters; public abstract class ShapeGenerator { protected MeasureFetcher measureFetcher; protected Shape[] shapes; protected PolymorphicChartParameters params; private Property<Double> width; private Property<Double> height; private Property<Color> color; public ShapeGenerator(MeasureFetcher measureFetcher, Property<Double> width, Property<Double> height, Property<Color> color) { this.measureFetcher=measureFetcher; this.width = width; this.height = height; this.color = color; } /** * This method gives all boxes the correct values. * @param width that should be given to all boxes (number or metric) * @param height that should be given to all boxes (number or metric) * @param color that should be given to all boxes (rgb format or grayscale with metric) * @return */ public Shape[] getShapes() { return this.shapes; } /** * This method returns a list of colors, one for each shape. If * the input is in RGB format, the color is the same for all shapes. If the * format "min<float>max<float>key<string>" is used as input, the color of * each box is dependent on a specific measure of the box. Else, the color * will be set to default color * * @param color * the color/metric to be used * @return a list with a color for each box */ protected List<Color> getShapeColors(String color) { List<Color> result = new ArrayList<Color>(); if(Util.isValidColor(color)){ Color rgb = Util.parseColor(color); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } else{ //the color parsing is invalid and the string should be of the format "min<float>max<float>key<string>" try{ String[] splitted = Util.splitOnDelimiter(color, new String[]{"min","max","key"}); Double min = Double.parseDouble(splitted[0]); Double max = Double.parseDouble(splitted[1]); String key = splitted[2]; result = getGrayScaleColors(min, max, key); } //Given input is not valid catch (IllegalArgumentException f){ Color rgb = Util.parseColor(PolymorphicChartParameters.DEFAULT_BOXCOLOR); result = new ArrayList<Color>(Collections.nCopies(shapes.length,rgb)); } } return result; } /** * This method scales a list of metric values to a new list, with the lowest * value of the metric scaled to min, and the highest scaled to max. * * @param min * the minimum color value of the list with scaled colors * @param max * the maximum color value of the list with scaled colors * @param key * the key that represents the metric that should be scaled * @return a list with the scaled color values */ private List<Color> getGrayScaleColors(Double min, Double max, String key) throws IllegalArgumentException{ //TODO hoe<SUF> Map<String, Double> colors = measureFetcher.getMeasureValues(key); Map<String, Double> scaledColors = Util.scaleGrey(colors, min, max); List<Color> result = new ArrayList<Color>(); try{ for (int i = 0; i < shapes.length; i++) { String name = shapes[i].getName(); int colorValue = scaledColors.get(name).intValue(); Color c = new Color(colorValue, colorValue, colorValue); result.add(c); } return result; } catch(Exception e){ throw new IllegalArgumentException(); } } /** * This method names all the shapes with the correct resource names. */ protected void nameShapes() { List<String> names = measureFetcher.getResourceNames(); int i = 0; for (String s : names) { shapes[i].setName(s); i++; } } }
False
937
15
1,078
16
1,099
12
1,078
16
1,275
17
false
false
false
false
false
true
1,859
150349_0
/* avondvierdaagse.java * * Pieter Eendebak * eendebak at math uu nl * */ import java.util.StringTokenizer; import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.lang.Math; class Mud { public long x, y; } class MudCompare implements Comparator{ public int compare(Object a, Object b) { Mud A = (Mud)a; Mud B = (Mud)b; return (A.x-B.x)<0?-1:1; } } class Main { public static StringTokenizer tok; public static String line; public static BufferedReader in; public static void write(String s) { System.out.print(s); } public static void writen(String s) { System.out.print(s+"\n"); } public static int readInt() throws Exception { tok(); return nextInt(); } public static void tok() throws Exception { tok = new StringTokenizer(in.readLine()); } public static String nextString() throws Exception { return (String)tok.nextToken(); } public static int nextInt() throws Exception { return Integer.parseInt((String)tok.nextToken()); } public static void main(String[] args) throws Exception { in = new BufferedReader( new InputStreamReader(System.in) ); int runs = readInt(); for( int run=0; run<runs; run++ ) doit(); } public static void doit() throws Exception { int n; long l; // read in data tok(); n = nextInt(); l = nextInt(); //writen("Doing run with "+n+" mudpools"); Mud [] mudpool = new Mud[n]; int i = 0, j; for(i=0;i<n;i++) { tok(); mudpool[i] = new Mud(); mudpool[i].x = nextInt(); mudpool[i].y = nextInt(); //writen("read " + mudpool[i].x + " " + mudpool[i].y); } // find optimal number of planks Arrays.sort( mudpool, new MudCompare()); long end=0; long pl=0; i=0; while(i<n) { //writen("i: " + i + " pl: " + pl + " end: " + end); if(mudpool[i].y>end) { // add new plank end = l + Math.max(end, mudpool[i].x); pl++; } else i++; } // print the results writen(""+pl); } }
WISVCH/chipcie-website
static/archive/2004/nkp/c/oplossing.java
782
/* avondvierdaagse.java * * Pieter Eendebak * eendebak at math uu nl * */
block_comment
nl
/* avondvierdaagse.java *<SUF>*/ import java.util.StringTokenizer; import java.io.*; import java.util.Arrays; import java.util.Comparator; import java.lang.Math; class Mud { public long x, y; } class MudCompare implements Comparator{ public int compare(Object a, Object b) { Mud A = (Mud)a; Mud B = (Mud)b; return (A.x-B.x)<0?-1:1; } } class Main { public static StringTokenizer tok; public static String line; public static BufferedReader in; public static void write(String s) { System.out.print(s); } public static void writen(String s) { System.out.print(s+"\n"); } public static int readInt() throws Exception { tok(); return nextInt(); } public static void tok() throws Exception { tok = new StringTokenizer(in.readLine()); } public static String nextString() throws Exception { return (String)tok.nextToken(); } public static int nextInt() throws Exception { return Integer.parseInt((String)tok.nextToken()); } public static void main(String[] args) throws Exception { in = new BufferedReader( new InputStreamReader(System.in) ); int runs = readInt(); for( int run=0; run<runs; run++ ) doit(); } public static void doit() throws Exception { int n; long l; // read in data tok(); n = nextInt(); l = nextInt(); //writen("Doing run with "+n+" mudpools"); Mud [] mudpool = new Mud[n]; int i = 0, j; for(i=0;i<n;i++) { tok(); mudpool[i] = new Mud(); mudpool[i].x = nextInt(); mudpool[i].y = nextInt(); //writen("read " + mudpool[i].x + " " + mudpool[i].y); } // find optimal number of planks Arrays.sort( mudpool, new MudCompare()); long end=0; long pl=0; i=0; while(i<n) { //writen("i: " + i + " pl: " + pl + " end: " + end); if(mudpool[i].y>end) { // add new plank end = l + Math.max(end, mudpool[i].x); pl++; } else i++; } // print the results writen(""+pl); } }
False
600
30
721
34
720
29
721
34
847
34
false
false
false
false
false
true
2,133
202595_10
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] INTUITION, go along to diaonals and incrememnt but i-1, j+1 to do in reverse order, store all elements in arraylist and then reverse REGULAR DIAONGAL MATRIX class Solution { public int[] findDiagonalOrder(int[][] matrix) { int m= matrix.length; int n= matrix[0].length; int index =0; int[] res = new int[m*n]; for(int k=0; k<=m-1; k++){ int i=k; // to print all the diagonals starting on left row int j=0; //starts on first col always while(i>=0){ //go until we reach the upper bord res[index++]=matrix[i][j]; i=i-1; j=j+1; } } for(int k=1; k<=n-1; k++){ //HAVE TO START FROM K=1 to skip over the diagonl that gets counted twice int i = m-1; //starts on last rol always int j= k; //to print all diagonals starting at bottom row while(j<=n-1){ //go until we reach the right border res[index++]=matrix[i][j]; i=i-1; j=j+1; } } return res; } } SAME AS DIAOGONAL, but if the diagonl we are on is odd, we will reverse all the elemetnts, THEN add to result //TC: O(N*M) to go thorugh the entire matrix, O(K) to clear the matrix //SC: O(min(N,M)) to store elements in arraylist class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return new int[0]; int m = matrix.length; int n = matrix[0].length; int[] res = new int[m*n]; int resIndex = 0; ArrayList<Integer> temp = new ArrayList<>(); for(int k=0; k<m; k++){ temp.clear(); //clear out this temp array int i = k; int j =0; while(i>=0){ temp.add(matrix[i][j]); //copy this elemeent i= i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } for(int k=1; k<n; k++){ //NOTE, need to go from k=1 to skip of, BIGGEST DIAGONAL counted twice temp.clear(); //clear out this temp array int i = m-1; int j = k; while(j< n){ temp.add((matrix[i][j])); i=i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } return res; } } // If out of bottom border (row >= m) then row = m - 1; col += 2; change walk direction. // if out of right border (col >= n) then col = n - 1; row += 2; change walk direction. // if out of top border (row < 0) then row = 0; change walk direction. // if out of left border (col < 0) then col = 0; change walk direction. // Otherwise, just go along with the current direction. BEST SOLUTION //O(M*N) //O(1) constant space solutioN!!!! public class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix == null || matrix.length == 0) return new int[0]; int m = matrix.length, n = matrix[0].length; int[] result = new int[m * n]; int row = 0, col = 0, d = 0; //first direction we go is upright int[][] dirs = {{-1, 1}, {1, -1}}; for (int i = 0; i < m * n; i++) { result[i] = matrix[row][col]; row += dirs[d][0]; col += dirs[d][1]; if (row >= m) { row = m - 1; col += 2; d = 1 - d;} if (col >= n) { col = n - 1; row += 2; d = 1 - d;} //out on right botder if (row < 0) { row = 0; d = 1 - d;} //out on top border, reset if (col < 0) { col = 0; d = 1 - d;} // out on left border, reset col } return result; } }
armankhondker/best-leetcode-resources
leetcode-solutions/diagonalMatrixPrint.java
1,455
//copy this elemeent
line_comment
nl
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image. Example: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] INTUITION, go along to diaonals and incrememnt but i-1, j+1 to do in reverse order, store all elements in arraylist and then reverse REGULAR DIAONGAL MATRIX class Solution { public int[] findDiagonalOrder(int[][] matrix) { int m= matrix.length; int n= matrix[0].length; int index =0; int[] res = new int[m*n]; for(int k=0; k<=m-1; k++){ int i=k; // to print all the diagonals starting on left row int j=0; //starts on first col always while(i>=0){ //go until we reach the upper bord res[index++]=matrix[i][j]; i=i-1; j=j+1; } } for(int k=1; k<=n-1; k++){ //HAVE TO START FROM K=1 to skip over the diagonl that gets counted twice int i = m-1; //starts on last rol always int j= k; //to print all diagonals starting at bottom row while(j<=n-1){ //go until we reach the right border res[index++]=matrix[i][j]; i=i-1; j=j+1; } } return res; } } SAME AS DIAOGONAL, but if the diagonl we are on is odd, we will reverse all the elemetnts, THEN add to result //TC: O(N*M) to go thorugh the entire matrix, O(K) to clear the matrix //SC: O(min(N,M)) to store elements in arraylist class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix.length == 0 || matrix[0].length == 0) return new int[0]; int m = matrix.length; int n = matrix[0].length; int[] res = new int[m*n]; int resIndex = 0; ArrayList<Integer> temp = new ArrayList<>(); for(int k=0; k<m; k++){ temp.clear(); //clear out this temp array int i = k; int j =0; while(i>=0){ temp.add(matrix[i][j]); //copy this<SUF> i= i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } for(int k=1; k<n; k++){ //NOTE, need to go from k=1 to skip of, BIGGEST DIAGONAL counted twice temp.clear(); //clear out this temp array int i = m-1; int j = k; while(j< n){ temp.add((matrix[i][j])); i=i-1; j=j+1; } if(k%2 == 1){ Collections.reverse(temp); } for(int x: temp){ res[resIndex++] = x; } } return res; } } // If out of bottom border (row >= m) then row = m - 1; col += 2; change walk direction. // if out of right border (col >= n) then col = n - 1; row += 2; change walk direction. // if out of top border (row < 0) then row = 0; change walk direction. // if out of left border (col < 0) then col = 0; change walk direction. // Otherwise, just go along with the current direction. BEST SOLUTION //O(M*N) //O(1) constant space solutioN!!!! public class Solution { public int[] findDiagonalOrder(int[][] matrix) { if (matrix == null || matrix.length == 0) return new int[0]; int m = matrix.length, n = matrix[0].length; int[] result = new int[m * n]; int row = 0, col = 0, d = 0; //first direction we go is upright int[][] dirs = {{-1, 1}, {1, -1}}; for (int i = 0; i < m * n; i++) { result[i] = matrix[row][col]; row += dirs[d][0]; col += dirs[d][1]; if (row >= m) { row = m - 1; col += 2; d = 1 - d;} if (col >= n) { col = n - 1; row += 2; d = 1 - d;} //out on right botder if (row < 0) { row = 0; d = 1 - d;} //out on top border, reset if (col < 0) { col = 0; d = 1 - d;} // out on left border, reset col } return result; } }
False
1,213
7
1,293
7
1,374
7
1,293
7
1,445
7
false
false
false
false
false
true
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
5
Edit dataset card